amibroker

HomeKnowledge Base

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 ROCC20 ); 

PositionSize = -EachPosPercent

SetOption("WorstRankHeld"40 );
SetOption("MaxOpenPositions"20 ); 

SetOption("UseCustomBacktestProc"True ); 

if( 
Status("action") == actionPortfolio )
{
  
bo GetBacktesterObject();

  
bo.PreProcess(); // Initialize backtester

  
for(bar=0bar BarCountbar++)
  {
   
bo.ProcessTradeSignalsbar );
  
   
CurEquity bo.Equity;
  
   for( 
pos bo.GetFirstOpenPos(); pospos bo.GetNextOpenPos() )
   {
    
posval pos.GetPositionValue();
   
    
diff posval 0.01 EachPosPercent CurEquity;
    
price pos.GetPricebar"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 != AND
        
absdiff ) > 0.005 CurEquity AND
        
absdiff ) > price )
    {
     
bo.ScaleTradebarpos.Symboldiff 0priceabsdiff ) );
    }
   }
  }
  
bo.PostProcess(); // Finalize backtester

Comments are closed.