Portfolio System with Relative Strength Levy and Cast Out Rank




Hello everyone,

I’m relatively new and currently trying to build a simple relative strength model based on Levy for the Russell 1000 universe.

My goal is straightforward:

  • Use a relative strength metric defined as Close / SMA(130)
  • Apply a market filter using SPY with two moving averages to avoid major drawdowns
  • Select the Top 10 stocks based on relative strength
  • Use a Cast-Out Rank of 20%
  • The Russell 1000 stocks are organized in a watchlist, which also includes SPY for the market filter

Unfortunately, I’m currently not getting any results in my backtest.

I’m sharing my code and settings (screenshots) and would really appreciate any help. Feel free to adjust or improve the code as needed.

Thanks in advance for your support!

// ============================================================
// Relative Strength System after Levy (Close / SMA130)
// Universe  : Russell 1000 Watchlist (set in AA window)
// Entry     : Top 10 stocks by Levy RS score
// Exit 1    : Cast-Out-Rank (rank drops below threshold)
// Exit 2    : Crisis filter - SPY SMA5 < SPY SMA200
// ============================================================

// --- Parameters ---
MaxPositions     = 10;
CastOutPct       = Optimize( "CastOutPct", 20, 5, 50, 5 );
LevyPeriod       = 130;

// --- Levy Relative Strength ---
LevyRS = Close / MA( Close, LevyPeriod );

// --- Cross-sectional Ranking (Rank 1 = strongest) ---
StaticVarSet( "LevyRS_" + Name(), LevyRS );
StaticVarGenerateRanks( "rank_LevyRS_", "LevyRS_", 0, 1 );
CurrentRank      = StaticVarGet( "rank_LevyRS_" + Name() );
CastOutThreshold = MaxPositions * ( 1 + CastOutPct / 100 );

// --- Crisis Filter: SPY SMA5 > SMA200 ---
SpyClose  = Foreign( "SPY", "C" );
MarketOK  = IIf( BarIndex() > 200, MA( SpyClose, 5 ) > MA( SpyClose, 200 ), 0 );

// --- Signals ---
Buy   = CurrentRank <= MaxPositions AND MarketOK;
Sell  = CurrentRank > CastOutThreshold OR NOT MarketOK;
Short = 0;
Cover = 0;

// --- Execution & Sizing ---
BuyPrice     = Open;
SellPrice    = Open;
PositionSize  = -10;
PositionScore = LevyRS;

// --- Portfolio Settings ---
SetOption( "MaxOpenPositions",       MaxPositions );
SetOption( "AllowPositionShrinking", True );

You are not using StaticVarGenerateRanks correctly. You should set the static variables for all symbols before that function gets called. Look for examples in the AmiBroker Help pages or in this forum.

If you're still not getting trades after fixing that issue, then use an Exploration to check that the values of the variables that affect entry and exit are what you expect them to be.

@mradtke thank you can i also use the. Rotational system for this?

I don’t think the built-in rotational mode will handle all your rules exactly as written, for example the 20% Cast Off rule. AmiBroker uses Worst Rank Held, which I believe needs to be a single numeric value rather than a potentially different value on each bar.

You can do pretty much everything in custom backtester and yes custom backtester works in rotational mode too.

As to the code - you need to understand what you wrote (or what AI wrote for you). To do so you much learn basic debugging / analysis skills.

To get better understanding of what is happening in your code and how functions work, use advice given here:

I read the help in amibroker and tried this code:

// ============================================================
// Relative Strength System after Levy - enhanced
// Universe : Russell 1000 Watchlist (set in AA window)
// Entry : Top 10 stocks by smoothed Levy RS score
// Exit 1 : Rank drops below WorstRankHeld (Cast-Out)
// Exit 2 : Crisis filter - SPY SMA5 < SPY SMA200
// Filter : Minimum volume to exclude frozen/takeover stocks
// Mode : Rotational - no manual buy/sell signals needed
// ============================================================

// --- Rotational Mode ---
SetBacktestMode( backtestRotational );

// --- Optimizable Parameters ---
CastOutRank = Optimize( "CastOutRank", 200, 50, 300, 10 );
LevyPeriod = Optimize( "LevyPeriod", 130, 50, 250, 10 );

// --- Fixed Parameters ---
MaxPositions = 10;
Smoothing = 5; // SMA smoothing for Levy RS
CrisisShort = 5; // fixed short SMA for crisis filter
CrisisLong = 200; // fixed long SMA for crisis filter
MinVolume = 500000; // minimum avg daily volume
MinPrice = 5; // minimum price

// --- Portfolio Settings ---
SetOption( "MaxOpenPositions", MaxPositions );
SetOption( "WorstRankHeld", CastOutRank );
SetPositionSize( 10, spsPercentOfEquity );

// --- Levy Relative Strength with Smoothing ---
RawLevyRS = Close / MA( Close, LevyPeriod );
LevyRS = MA( RawLevyRS, Smoothing );

// --- Frozen / Takeover Stock Filter ---
AvgRangePct = MA( High - Low, 20 ) / Close * 100;

StockOK = MA( Volume, 20 ) > MinVolume
AND AvgRangePct > 0.5
AND Close > MinPrice;

// --- Crisis Filter: SPY SMA5 > SMA200 (fixed) ---
SpyClose = Foreign( "SPY", "C" );
MarketOK = IIf( BarIndex() > CrisisLong,
MA( SpyClose, CrisisShort ) > MA( SpyClose, CrisisLong ),
0 );

// --- Position Score ---
PositionScore = IIf( MarketOK AND StockOK, LevyRS, 0 );

Don't forget those code tags!

You said you tried that code. Did it work? Do you have a question?

I will answer in Weekend - amibroker is very!!! Powerful.

I have to spend more time here to learn!

Thanks for all help by now i will answer more detailed.

And i will Tag the Code right.

This is my final code - i was missunderstanding the rotational mode.

any idea how i can reduce the draw down of 42 % ?

// ============================================================
// Relative Strength System after Levy - FINAL
// Universe  : Russell 1000 Watchlist (set in AA window)
// Entry     : Top 10 stocks by Levy RS score
// Exit 1    : Rank drops below CastOutRank
// Exit 2    : Crisis filter - SPY SMA5 < SPY SMA200
// Filter    : Illiquidity (High = Low = frozen/takeover stock)
// Mode      : Rotational - LONG ONLY
// Investment: 10% equity per position
// ============================================================

// --- Rotational Mode ---
SetBacktestMode( backtestRotational );

// --- Optimizable Parameters ---
LevyPeriod  = Optimize( "LevyPeriod",  130,  50, 250, 10 );
CastOutRank = Optimize( "CastOutRank", 230, 100, 300, 10 );

// --- Fixed Parameters ---
MaxPositions    = 10;
CrisisShort     = 5;    // fixed short SMA for crisis filter
CrisisLong      = 200;  // fixed long  SMA for crisis filter
IlliqPeriod     = 20;   // lookback for illiquidity check
IlliqMaxDays    = 3;    // max allowed illiquid days in period

// --- Portfolio Settings ---
SetOption( "MaxOpenPositions", MaxPositions );
SetOption( "WorstRankHeld",    CastOutRank  );
SetOption( "AllowSameBarExit", False        );
SetOption( "MaxOpenLong",      MaxPositions );
SetOption( "MaxOpenShort",     0            );
SetPositionSize( 10, spsPercentOfEquity     );

// --- Levy Relative Strength ---
LevyRS = Close / MA( Close, LevyPeriod );

// --- Illiquidity Filter ---
// High = Low means no price movement = frozen/takeover stock
Illiq       = High == Low;
Summe_Illiq = Sum( Illiq, IlliqPeriod );
StockOK     = Summe_Illiq <= IlliqMaxDays;

// --- Crisis Filter: SPY SMA5 > SMA200 ---
SpyClose = Foreign( "SPY", "C" );
MarketOK = IIf( BarIndex() > CrisisLong,
                MA( SpyClose, CrisisShort ) > MA( SpyClose, CrisisLong ),
                0 );

// --- Position Score ---
PositionScore = IIf( MarketOK AND StockOK, Max( LevyRS, 0 ), 0 );

I tested the 3 D Optimation Graph... next i will learn to make a walk forward and test the system of clenow.

Your code comments say that you tested against the Russell 1000 index, but there's nothing in your code that checks whether a stock is a member of the index on the day of entry. Based on this, I believe you are testing against the current Russell 1000 constituents, which introduces a lot of lookahead bias into your backtest results. If you use data from Norgate Data, you can easily test for index membership on a historical basis. I do not know of any other AmiBroker-friendly data providers that offer this feature.

The smallest value you tested for Worst Rank Held was 100. That still seems very high to me for a rotational strategy that only holds 10 positions at a time. If you want to reduce drawdowns, I would test WRH values between 10 and 100.

Hello, @mradtke thank you very much for your message and for the information about survivorship bias.
I am currently using a German data provider from InFront, which does not allow me to exclude survivorship bias. To address this, I would need Northgate data.
How much do you think the results would differ if I were able to test using historical index memberships?
Thank you very much for your input and feedback.

The impact of the bias will depend on when your backtest starts. The further back in time that you go, the more unrealistic the current index membership becomes.

For example, here are the results for four backtests:

  1. 2020-Present using current R1000
  2. 2020-Present using historically accurate R1000 members
  3. 2010-Present using current R1000
  4. 2010-Present using historically accurate R1000 members

Wow thats crazy! The DrawDown looks relativ stable but the effect on CAR is crazy impact. So i think i need norgate data - without i train the system on the historic winners.... and the robust 3D tool gives me wrong stable results cause i use wrong data. (survivors)

thank you very much for this point to share with me.

Make sure to purchase the Norgate package that includes historical index constituency. I believe it's their Platinum package or higher.


this right?

Yes - Platinum for Historical Index Constituents.

i also bought the book from Trading Systems (Second edition): A new approach to system development and portfolio optimisation Taschenbuch.

so i will learn and not generate AI Post anymore. But AI help me at the moment to create my idea into afl code.

i hope this is okay.

@mradtke i now have norgate data.

is this the right watchlist for sp500 with the historical index membership to test without surivorship bias?

I replied to your post, but it's awaiting moderator approval for some reason.

Norgate Data's website has detailed instructions on how to use their data.