Hi,
I would greatly appreciate some assistance. I am attempting to code rotational trading system where the position sizing of each stock position is based on the inverse volatility. The sum of these position should equal ~100%
My thought is to extract what the 5 highest ranked stocks in positionscore to variable "#onlist" along with their ticker, how do I do this? Any method that is better? See code below
SetBacktestMode(backtestRotational);
SetOption("PortfolioReportMode", 1);
SetOption( "InitialEquity", 100000 );
// Set the number of positions
NumberofAssets = 5;
SetOption("MaxOpenPositions", NumberofAssets);
SetOption("WorstRankHeld", NumberofAssets);
// Momentum score
PositionScore = (ROC(Close,21*1) + ROC(Close,21*3);
// Allocate available funds unequally based on inverse of 21 day historical volatility
A1 = 1/(StDev(1onlist, 21));
A2 = 1/(StDev(2onlist, 21));
A3 = 1/(StDev(3onlist, 21));
A4 = 1/(StDev(4onlist, 21));
A5 = 1/(StDev(5onlist, 21));
SumA = A1 + A2 + A3 + A4 + A5;
AC1 = round((1A/SumA)*100);
AC2 = round((2A/SumA)*100);
AC3 = round((3A/SumA)*100);
AC4 = round((4A/SumA)*100);
AC5 = round((5A/SumA)*100);
PositionSize = IIf( Name() == "1onlist", -AC1, // Number 1 on position score list
IIf( Name() == "2onlist", -AC2, // Number 2 on position score list
IIf( Name() == "3onlist", -AC3, // Number 3 on position score list
IIf( Name() == "4onlist", -AC4, // Number 4 on position score list
IIf( Name() == "5onlist", -AC5, // Number 5 on position score list
0)))));
// Monthly
firstDayofMonth = Month() != Ref(Month(),-1);
rebalance = firstDayofMonth AND Cum(
firstDayofMonth ) > 1;
//Rebalance Instruction
PositionScore = IIf( rebalance, PositionScore, scoreNoRotate );
SetOption( "UseCustomBacktestProc", True );
if( Status( "action" ) == actionPortfolio )
{
bo = GetBacktesterObject();
bo.PreProcess();
for( bar = 0; bar < BarCount; bar++ )
{
bo.ProcessTradeSignals( bar );
CurEquity = bo.Equity;
if( rebalance[bar] == 1 )
{
for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
{
posval = pos.GetPositionValue();
if( pos.Symbol == "SPY" )
{
diff = posval - 0.01 * 25 * CurEquity;
}
else
{
diff = posval - 0.01 * 25 * CurEquity;
}
price = pos.GetPrice( bar, "O" );
if( diff != 0 AND abs( diff ) > price )
{
bo.ScaleTrade( bar, pos.Symbol, diff < 0, price, abs( diff )
);
}
}
}
}
bo.PostProcess();
}