Hello,
I'm trying to create a code to size positions according to Kelly Optimal f from this formula:
f = [p x (PLR + 1) - 1] / PLR, where
PLR = the ratio of average profit to average loss
p = the probability of a winning trade.
I am new when it comes to custom backtest, I was checking the information in the website and the forum but I still can't figure out how to get the stats for trading out of the custom backtest. Probably it's quite simple, I would thank some help about it.
For example, I can get the graphic representation of the stats that I need, according to the following entry: https://www.amibroker.com/kb/2008/05/19/historical-portfolio-backtest-metrics/, the code would be like this one (to easy the code, I buy all the 100 symbols from a category and rebalance them annualy):
/// --- CustomBacktest ---
SetOption("UseCustomBacktestProc", True );
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.PreProcess();
WinnersPercent = Null;
WinnersAvgProfit = Null;
LosersAvgLoss = Null;
for(bar=0; bar < BarCount; bar++)
{
bo.ProcessTradeSignals( bar );
stats = bo.GetPerformanceStats( 0 );
WinnersPercent[bar] = stats.GetValue("WinnersPercent");
WinnersAvgProfit[bar] = stats.GetValue("WinnersAvgProfit");
LosersAvgLoss[bar] = stats.GetValue("LosersAvgLoss");
}
bo.PostProcess();
AddToComposite( WinnersPercent, "~~~WinnersPercent_Historical", "X", atcFlagEnableInPortfolio | atcFlagDefaults );
AddToComposite( WinnersAvgProfit, "~~~WinnersAvgProfit_Historical", "X", atcFlagEnableInPortfolio | atcFlagDefaults );
AddToComposite( LosersAvgLoss, "~~~LosersAvgLoss_Historical", "X", atcFlagEnableInPortfolio | atcFlagDefaults );
}
/// --- Trading Rules ---
Rebalance = Year() != Ref(Year(), -1);
Buy = 1;
Sell = Rebalance;
SetPositionSize(1/100; spsPercentOfEquity);
/// --- Graph ---
PlotForeign("~~~WinnersPercent_Historical", "WinnersPercen", colorRed, styleLine );
PlotForeign("~~~WinnersAvgProfit_Historical", "WinnersAvgProfit", colorBlue, styleLine );
PlotForeign("~~~LosersAvgLoss_Historical", "WinnersAvgProf", colorBlack, styleLine );
What I would need to do is what is represented next (I write the code in a conceptual way, of course it doesn't work)
/// --- Trading Rules ---
Rebalance = Year() != Ref(Year(), -1);
Buy = 1;
Sell = Rebalance;
WinningTradeProbability = WinnersPercent;
AverageProfitLossRatio = WinnersAvgProfit / LosersAvgLoss;
Optimalf = ((WinningTradeProbability * (AverageProfitLossRatio + 1))-1) / AverageProfitLossRatio;
DilutedOptimalf = DilutedOptimalf * 0.1;
SetPositionSize(Optimalf, spsPercentOfEquity);
Finally, the question is how to get the WinnersPercent, WinnersAvgProfit and LosersAvgLoss for each bar from the custom backtest section, so that I can use them for sizing the position of new trades.
Thank you beforehand.
Best regards.