Help will be appreciated. Suppose some buy-and-hold investor decided to buy 1/3 of initial $100K capital in NVDA on 12/01/2008, then 1/3 more of MSFT on 01/02/2020, and finally last 1/3 of TLT on 11/01/2023. I coded this as follows:
SetOption("InitialEquity", 100000);
SetBacktestMode(backtestRegular);
PositionSize=-100/3;
if ( Name () == "NVDA" ) {
BUY = Year()==2008 AND Month()==12 AND Day()==1;
Sell=0;
}
if ( Name () == "MSFT" ) {
BUY = Year()==2020 AND Month()==1 AND Day()==2;
Sell=0;}
if ( Name () == "TLT" ) {
BUY = Year()==2023 AND Month()==11 AND Day()==1;
Sell=0;
}
BuyPrice=SellPrice=Close;
According to the backtest report, 1/3 is allocated to NVDA as expected, but the remaining 2/3 to MSFT, and there is nothing left for TLT.
@makhar88, in addition to the @pmxgs suggestion (btw, it is a lot easier to use the SetPostion() function) I recommend also to examine the "Detailed log" (Analysis Setting dialogs / Report tab) to better understand why your previous code was not doing what you expected (check what are the positions and the free cash at the entry dates).
You are allocating 33.3% of your percent of portfolio-level equity. (Not a 1/3 of the initial capital).
Since your first entry is NVDA whose price has increased greatly over time, when executing the following operations there is not enough capital to execute them.
Furthermore, without the flagged "Allow position size shrinking" option in the "general" analysis settings, at least in my tests, not even the second operation (MSFT) is successful.
Personally I recommend making all these options explicit in the code to be able to replicate the results exactly on other machines that may have different "default" settings.
@bebbe, I included a detailed log. In addition, by the time MSFT is entered, NVDA has already increased a lot. I cannot infer from your explanation why MSFT took the remaining 2/3 of initial capital, and why there is nothing left for TLT. Thank you.
@makhar88, when carrying out the operation on MSFT, approx. 33% of the portfolio-level equity is required (not the initial capital $ 33.3k). Given the value of the equity (due to the growth of NVDA) there would not be enough free cash to carry out the operation, but since you have the "Allow position size shrinking" option enabled in your settings, the MSFT purchase takes place using almost all the available cash.
Obviously in the end there isn't even enough left for TLT to buy a single share.
If you try to remove the flag from "Allow position size shrinking" you will see that not even the second operation (MSFT) can be performed.