March 6, 2006
Re-balancing open positions
Here is an example that shows how to code rotational trading system with rebalancing. The system buys and shorts top 20 securities according to absolute value of positionscore (user definable – in this example we used 20 day rate-of-change) – each at 5% of equity then each day it rebalances existing positions to 5% if only the difference between current position value and “ideal” value is greater than 0.5% and bigger than one share.
Note that this code sample uses Custom Backtester interface that is documented here.
EnableRotationalTrading();
EachPosPercent = 5;
PositionScore = ROC( C, 20 );
PositionSize = -EachPosPercent;
SetOption("WorstRankHeld", 40 );
SetOption("MaxOpenPositions", 20 );
SetOption("UseCustomBacktestProc", True );
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.PreProcess(); // Initialize backtester
for(bar=0; bar < BarCount; bar++)
{
bo.ProcessTradeSignals( bar );
CurEquity = bo.Equity;
for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
{
posval = pos.GetPositionValue();
diff = posval - 0.01 * EachPosPercent * CurEquity;
price = pos.GetPrice( bar, "C" );
// rebalance only if difference between desired and
// current position value is greater than 0.5% of equity
// and greater than price of single share
if( diff != 0 AND
abs( diff ) > 0.005 * CurEquity AND
abs( diff ) > price )
{
bo.ScaleTrade( bar, pos.Symbol, diff < 0, price, abs( diff ) );
}
}
}
bo.PostProcess(); // Finalize backtester
Filed by Tomasz Janeczko at 3:50 pm under Custom Backtest
Comments Off on Re-balancing open positions