// Downloaded From https://www.WiseStockTrader.com
// --- MRS_Optimizable.afl ---
 
/* 
** -----------------------------------------
**
** Momentum Rotation Strategy
**
** idea by Marc Cohn
** http://seekingalpha.com/article/2041703-return-like-a-stock-risk-like-a-bond-15_5-percent-cagr-with-17-percent-drawdown
**
** afl-code by TrendXplorer
** trendxplorer@gmail.com
** www.trendxplorer.info
** version: Mar 22, 2014
**
** -----------------------------------------
*/
 
// --- backtester settings --- 
PosQty = 1; // Position Quantity: max number of positions
SetOption( "CommissionAmount", 0.00 );
SetOption( "InitialEquity", 100000 );
SetOption( "MaxOpenshort", 0 );
SetOption( "MaxOpenLong", PosQty );
SetOption( "MaxOpenPositions", PosQty );
SetOption( "WorstRankHeld", PosQty );
SetOption( "AllowPositionShrinking", True );
SetPositionSize( 100 / PosQty, spsPercentOfEquity );
SetTradeDelays( 0, 0, 0, 0 );
SetBacktestMode( backtestRotational );
Filter = Status( "LastBarInTest" );
 
// --- inputs ---
MomStart  = Param( "Momentum StartValue",   1, 1, 100, 1 );
MomEnd    = Param( "Momentum EndValue"  , 100, 1, 100, 1 );
AvgStart  = Param( "Smooth StartValue"  ,   1, 1,  30, 1 );
AvgEnd    = Param( "Smooth EndValue"    ,  30, 1,  30, 1 );
  
MomLength = Optimize( "Momentum Period", MomStart, MomStart, MomEnd, 1 );
AvgLength = Optimize( "Smooth Period"  , AvgStart, AvgStart, AvgEnd, 1 );
 
// --- detect watchlist ---
wlnumber       = GetOption( "FilterIncludeWatchlist" );
watchlist      = GetCategorySymbols( categoryWatchlist, wlnumber );
 
// --- ranking routine ---
// based on https://groups.yahoo.com/neo/groups/amibroker/conversations/topics/178791
if ( Status( "stocknum" ) == 0 )
{
    StaticVarRemove( "Mom*" );
    StaticVarRemove( "RankMom*" );
 
    for ( i = 0; ( symbol = StrExtract( watchlist, i ) )  != "";  i++ )
    {
        SetForeign ( symbol );
        Data = MA( Close, AvgLength );
        Mom  = ( Data / Ref( Data, -MomLength ) ) * 100;
        RestorePriceArrays();
         
        StaticVarSet( "Mom" + symbol, Mom );
    }
    // generate ranks for Momentum
    StaticVarGenerateRanks( "Rank", "Mom", 0, 1224 );
}
 
// --- get values and ranks for Momentum ---
symbol  =  Name();
Mom     =  StaticVarGet( "Mom"     +  symbol );
RankMom =  StaticVarGet( "RankMom" +  symbol );
 
// --- portfolio rebalancing ---                 
PositionScore = 1000 - RankMom; // always positive to prevent short trades
 
// --- generate columns for strategy exploration ---
ColorMom     = IIf( Mom > 0, colorLime, colorRed );
ColorTopX    = IIf( RankMom <= PosQty, IIf( Mom > 0, colorGold, colorRed ), colorWhite );
AddColumn( Mom       , "Momentum", 3.3, 1, ColorMom  );
AddColumn( RankMom   , "RankMom" , 1.0, 1, ColorTopX );
AddTextColumn( Name(), "Tickers" , 1.0, 1, ColorTopX );
if ( Status( "action" ) == actionExplore ) SetSortColumns( -2, 4 ); // sort for Exploration only
 
// --- end of code ---