I'm trying to use Historical Volatility as a positionscore in my portfolio backtest. The HV formula uses Log() and stdev().
The formula works fine as an indicator, but in a backtest, positionscore rank is always zero.
I read this is due to the fact that arrays are not to be used in the 2nd phase of the BT:
Below is my code for a custom metric. It works except the part where I try to get the standard deviation of my list of trades. This gives me no output at all. I don't understand what I am missing.
I looped though my trades to get all the profits and losses into an array called pnl. Checking with my ami broker output pnl[1] indeed matches the first trade profit or loss output from the backtest. There are 30 trades in the backtest so I hardcoded the 30. At the bottom of the metrics output win…
However, I am clueless how to make this work in portfolio BT mode: any help appreciated please.
(...buy/sell trading system code here...)
function getHistoricalVolatility(src, periods)
{
logret = log(src/Ref(src,-1));
volatilityonebar = StDev(logret, periods, False);
dv = IIf(Interval()==inWeekly, 52, 252);
dv = IIf(Interval()==inMonthly, 12, dv);
annualisedHV = (volatilityonebar*sqrt(dv))*100;
return annualisedHV;
}
positionscore = getHistoricalVolatility(Close, 20);
There is no problem using arrays in the second phase of the backtest. The post you referenced just shows how one can calculate standard deviation without using the built-in AmiBroker StDev() function.
I suggest you read this post: How do I debug my formula? for some ideas on how to better understand what's happening with your code and why your trades are not being taken.
2 Likes
Thank you mradtke.
I went through that debugging article, and using a detailed backtest report found out that I had a line buried deep in my code of:
positionscore = IIf(positionscore<0, 0, positionscore);
Which was creating the problem.
On removing it, the positionscore was showing as I needed it in the rank.
I must have got confused by that original article when I was searching for answers.
system
Closed
August 8, 2021, 9:13am
#5
This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.