January 2009
TRADERS’ TIPS


Here is this month’s selection of Traders’ Tips, contributed by various developers of technical analysis software to help readers more easily implement some of the strategies presented in this and other issues.

Other code appearing in articles in this issue is posted in the Subscriber Area of our website at https://technical.traders.com/sub/sublogin.asp. Login requires your last name and subscription number (from mailing label). Once logged in, scroll down to beneath the “Optimized trading systems” area until you see “Code from articles.” From there, code can be copied and pasted into the appropriate technical analysis program so that no retyping of code is required for subscribers.


You can copy these formulas and programs for easy use in your spreadsheet or analysis software. Simply “select” the desired text by highlighting as you would in any word processing program, then use your standard key command for copy or choose “copy” from the browser menu. The copied text can then be “pasted” into any open spreadsheet or other software by selecting an insertion point and executing a paste command. By toggling back and forth between an application window and the open web page, data can be transferred with ease.

This month’s tips include formulas and programs for:  

or return to January 2009 Contents

TRADESTATION: Megan Ratio

Oscar Cagigas’s article in this issue, “The Megan Ratio,” describes the Megan ratio (maximum exponential growth annualized). Cagigas compares Megan to the Sharpe ratio and K-ratio, and suggests that Megan be utilized as a means of comparing trading systems. He presents three strategies to demonstrate Megan’s ability to improve the trader’s ability to critique different strategy options.

We have implemented Megan in such a way that it can be used in charting, RadarScreen, and in the new Scanner (available in TradeStation 8.4). Cagigas’s three strategies are presented here. The code for running his first strategy in RadarScreen and in the Scanner will be posted in the Trade­Station and EasyLanguage support forum.

To download the EasyLanguage code for this study, go to the TradeStation and EasyLanguage Support Forum. Search for the file “Megan.Eld.”

FIGURE 1: TRADESTATION, MEGAN RATIO. Here are sample Megan ratio results shown in a chart (lower right), RadarScreen (left), and Scanner (upper right). The chart shows changes in Megan over time (red line). RadarScreen holds the S&P 100, sorted from high Megan ratio to low. Scanner can search for high Megan ratios in a security list of any length. .

This article is for informational purposes. No type of trading or investment recommendation, advice, or strategy is being made, given, or in any manner provided by TradeStation Securities or its affiliates.

Strategy:  CagigasA

inputs:
	FundSize( 100000 ),
	BuyLookback( 20 ),
	ExitLookBack( 10 ) ;

variables:
	Quantity( 0 ),
	MEGAN( 0 ) ;

Quantity = Floor( ( FundSize + NetProfit ) / Close /
 100 ) * 100 ; 

Buy Quantity shares next bar Highest( High,
 BuyLookBack ) stop ;

Sell next bar at Lowest( Low, ExitLookBack ) stop ;

MEGAN = MEGAN_Calc( FundSize ) ;


Strategy:  CagigasB

inputs:
	FundSize( 100000 ),
	FastLength( 5 ),
	SlowLength( 20 ),
 	ExitLookBack( 2 ) ;

variables:
	Quantity( 0 ),
	MEGAN( 0 ) ;

Quantity = Floor( ( FundSize + NetProfit ) / Close /
 100 ) * 100 ; 

if Average( Close, FastLength) > Average( Close,
 SlowLength ) then
	Buy Quantity shares next bar High stop ;
Sell next bar at Lowest( Low, ExitLookBack ) stop ;

MEGAN = MEGAN_Calc( FundSize ) ;


Strategy:  CagigasC

inputs:
	FundSize( 100000 ),
	FastLength( 5 ),
	SlowLength( 20 ),
	StartMonth( 7 ),
 	EndMonth( 4 ) ;

variables:
	Quantity( 0 ),
	MEGAN( 0 ) ;

Quantity = Floor( ( FundSize + NetProfit ) / Close /
 100 ) * 100 ; 

if Average( Close, FastLength ) > Average( Close,
 SlowLength ) and ( Month( Date ) > StartMonth or
 Month( Date ) < EndMonth ) then
	Buy Quantity shares next bar High stop ;

Sell next bar at Lowest( Low[1], 10 ) stop ;  

MEGAN = MEGAN_Calc( FundSize ) ;


Function:  MEGAN_Calc_

inputs:
	FundSize( numericsimple),
	OutsideTotalTrades( numericsimple ),
	MyNetProfit( numericsimple ),
	OutsideBarsSinceEntry( numericsimple ),
	OutsideMarketPosition( numericsimple ),
	OutsideNumWinTrades( numericsimple ),
	PrintOut( truefalsesimple ) ;

variables:
	InitialDate( 0 ),
	GeometricMean( 0 ),
	MaxTradesPerYear( 0 ),
	MEGAN( 0 ),
	TotalInDays( 0 ),
	MyBarsSinceEntry( 0 ),
	MyMarketPosition( 0 ),
	MyTotalTrades( 0 ) ;

if BarType <> 2 then
	RaiseRunTimeError( “Incorrect bar interval.  “ +
	 “MEGAN_Calc can be applied to daily bars only.” ) ;

if OutsideTotalTrades - MyTotalTrades > 1 then
	RaiseRunTimeError( “MEGAN_Calc allows only one “ +
	 “trade in each bar.” ) ;

if CurrentBar = 1 then
	InitialDate = Date ;

if MyTotalTrades <> OutsideTotalTrades then
	begin
	TotalInDays = TotalInDays + MyBarsSinceEntry ;
	if OutsideTotalTrades > 0 then
		begin
		if TotalInDays <> 0 then
			MaxTradesPerYear = 252 / ( TotalInDays /
			 OutsideTotalTrades ) ;
		GeometricMean = Power( ( FundSize +
		 MyNetProfit ) / FundSize, 1 /
		 OutsideTotalTrades ) ;
		MEGAN = MaxTradesPerYear *
		 Log( GeometricMean ) ;
		end ;
	end ;

if LastBarOnChart
	and OutsideTotalTrades > 0
	and Printout
then
	begin
	
	Print( “ Start Trading Date:  “,
	 ELDateToString( InitialDate ), NewLine,
	 “ Last Trading Date:  “,  ELDateToString( Date ),
	 NewLine, “ Initial Fund Value:  “, FundSize:8:0,
	 NewLine, “ Final Fund Value:  “, FundSize +
	 MyNetProfit:8:0, NewLine, “ Total Trades: “,
	 OutsideTotalTrades:6:0, NewLine, “ %W:  “,
	 OutsideNumWinTrades / OutsideTotalTrades * 100:6:0,
	 NewLine, “ Avg Days In Trade:  “, TotalInDays /
	 OutsideTotalTrades:8:1 ) ;
	
	Print( “ Terminal Wealth Relative (TWR):  “, 
	 iff( FundSize > 0, ( FundSize + MyNetProfit ) /
	 FundSize, 0 ), NewLine,
	 “ Max Trades Per Year (N):  “,
	 MaxTradesPerYear:8:1, NewLine,
	 “ Geometric Mean:  “, ( GeometricMean - 1 ) *
	 100:8:1, NewLine, “ MEGAN: “, MEGAN ) ;
	end ; 

MyMarketPosition = OutsideMarketPosition ;
MyBarsSinceEntry = OutsideBarsSinceEntry ;
MyTotalTrades = OutsideTotalTrades ; 

MEGAN_Calc_ = MEGAN ;

—Mark Mills
TradeStation Securities, Inc.
A subsidiary of TradeStation Group, Inc.
www.TradeStation.com


BACK TO LIST

WEALTH-LAB: Megan Ratio

Here you will find a C# code fragment of the actual Performance Visualizer that implements the Megan ratio as presented in the article by Oscar Cagigas in this issue, “The Megan Ratio.” Nonetheless, we’ve taken the trouble of coding it for you — there’s only one step left to power your analysis with the Megan ratio. Select «Extension Manager» from the Tools menu and notice an update available to the open source Community.Visualizers library, which includes the Megan ratio. (If you haven’t already done so, get the library free from the www.wealth-lab.com site.) After updating, any Strategy running in Portfolio Simulation mode can benefit from another view on its profitability analysis. (See Figure 2.)

However, the trader should keep in mind that there are drawbacks to this performance metric. First and foremost, it doesn’t take into account the risk side of the equation. And by design, it seems to favor strategies that continuously reinvest profits.

FIGURE 2: WEALTH-LAB, MEGAN RATIO. A Strategy window in Wealth-Lab Developer 5.1 demonstrates the Megan ratio.

C# Code:
	...

    /* MEGAN */

    double StartingCapital = performance.PositionSize.StartingCapital;
    double EndingCapital = StartingCapital + results.NetProfit;
    int Trades = results.Positions.Count;

    // Geometric mean
    
    double geom = Math.Pow( ( EndingCapital / StartingCapital ), 1.0d / Trades );

    // Geometric mean percentage
    
    double geomp = 100 * (geom - 1.0); 

    // Maximum number of trades per year

    double AverageBarsHeld;
    double TotalShares = 0;

    if (Trades > 0)
    {
        double BarsHeldTotal = 0.0;

        foreach (Position p in results.Positions)
        {
            BarsHeldTotal += p.BarsHeld;
            TotalShares += p.Shares;
        }

        AverageBarsHeld = BarsHeldTotal / Convert.ToDouble( Trades );
    }
    else
    {
        AverageBarsHeld = 0.0;
    }

    double mtpy = 252 / AverageBarsHeld;
    double meg = mtpy * Math.Log(geom);
	
	...

—Eugene
www.wealth-lab.com


BACK TO LIST

eSIGNAL: Megan Ratio

For this month’s Traders’ Tip, we’ve provided the eSignal formulas MeganRatio.efs, Cagigas_System1.efs, and Cagigas_System2.efs, based on the formula code from Oscar Cagigas’s article in this issue, “The Megan Ratio.”

The Megan ratio formula is a simple calculator that allows you to enter the inputs used from any backtesting formula to calculate the Megan ratio through the Edit Studies option. The study draws the result to the upper-right corner of the chart to the right of the price bars. Scroll the chart to the left to view the ratio or add a margin offset of 30 under the Properties options.

The other two formulas use the trading system examples from the article and calculate the Megan ratio directly (Figures 3 and 4). The P&L, Total Trades, and Megan ratio are drawn on the lower-right corner of the chart to the right of the price bars. Both formulas are also compatible for backtesting with the eSignal Strategy Analyzer.

To discuss this study or download a complete copy of the formula code, please visit the Efs Library Discussion Board forum under the Forums link at www.esignalcentral.com or visit our Efs KnowledgeBase at www.esignalcentral.com/support/kb/efs/. The eSignal formula scripts (Efs) are also available for copying and pasting from the Stocks & Commodities website at www.traders.com.

FIGURE 3: eSIGNAL, Cagigas System1. This sample eSignal chart shows the Cagigas System1 and Megan ratio calculator on a daily chart of INTC.

FIGURE 4: eSIGNAL, Cagigas System2. This sample eSignal chart shows the Cagigas System2 and Megan ratio calculator on a daily chart of INTC.

 Cagigas System1

/*********************************
Provided By:  
    eSignal (Copyright c eSignal), a division of Interactive Data 
    Corporation. 2008. All rights reserved. This sample eSignal 
    Formula Script (EFS) is for educational purposes only and may be 
    modified and saved under a new file name.  eSignal is not responsible
    for the functionality once modified.  eSignal reserves the right 
    to modify and overwrite this EFS file with each new release.

Description:        
    Cagigas System1

Version:            1.0  11/07/2008

Formula Parameters:                     Default:
    Entry (Highest Period)              20
    Exit (Lowest Period)                10
    Start Capital                       100000
    Max Trades Per Year                 8

Notes: 
    System 1 is a breakout system of using 20 and 10 periods.    
    The related article is copyrighted material. If you are not
    a subscriber of Stocks & Commodities, please visit www.traders.com.


**********************************/

var fpArray = new Array();
var bInit = false;
var bVersion = null;

function preMain() {
    setPriceStudy(true);
    setShowTitleParameters( false );
    setStudyTitle(“Cagigas System1”);
    setColorPriceBars(true);
    setDefaultPriceBarColor(Color.grey);
    setCursorLabelName(“HH”, 0);
    setCursorLabelName(“LL”, 1);
    setDefaultBarFgColor(Color.green, 0);
    setDefaultBarFgColor(Color.red, 1);
    setDefaultBarThickness(2, 0);
    setDefaultBarThickness(2, 1);
    

    var x=0;
    fpArray[x] = new FunctionParameter(“Entry”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Entry (Highest Period)”);
        setLowerLimit(1);		
        setDefault(20);
    }
    fpArray[x] = new FunctionParameter(“Exit”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Exit (Lowest Period)”);
        setLowerLimit(1);		
        setDefault(10);
    }
    fpArray[x] = new FunctionParameter(“StartCapital”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Start Capital”);
        setLowerLimit(0);		
        setDefault(100000);
    }
    fpArray[x] = new FunctionParameter(“MaxTradesPerYear”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Max Trades Per Year”);
        setDefault(8);
    } 
}

var xEntry = null;
var xExit = null;
var nPriceL = 0;
var nPriceS = 0;
var nTradeCounter = 0;
var NetProfit = 0;
var NetProfit_1 = 0

function main(Entry, Exit, MaxTradesPerYear, StartCapital) {

    if (bVersion == null) bVersion = verify();
    if (bVersion == false) return;   

    if (getCurrentBarIndex() == 0) return;

    if ( bInit == false ) { 
        xEntry = upperDonchian(Entry);
        xExit = lowerDonchian(Exit);
        NetProfit_1 = StartCapital; 
        bInit = true; 
    } 
    if(getBarState()==BARSTATE_NEWBAR) NetProfit_1 = NetProfit
    
    if (!Strategy.isLong()) {
        if (high(0) > xEntry.getValue(-1)) {
            nPriceL = Math.max(high(-1), open(0));
            Strategy.doLong(“Entry”, Strategy.LIMIT, Strategy.THISBAR,Strategy.DEFAULT, nPriceL);  
        }
    } 
    if (Strategy.isLong()) {
        setPriceBarColor(Color.blue);
        if (low(0) < xExit.getValue(-1)) {
            nPriceS = Math.min(xExit.getValue(-1),open(0));
            if(Strategy.isLong()) NetProfit = NetProfit_1+((nPriceS-nPriceL)* Strategy.getDefaultLotSize());
            nTradeCounter ++;
            Strategy.doSell(“Exit”, Strategy.LIMIT, Strategy.THISBAR,Strategy.DEFAULT, nPriceS); 
            var cTradeColor = Color.green;
            if ((nPriceS-nPriceL) < 0) cTradeColor = Color.maroon;
            drawTextRelative(0,BottomRow1,(nPriceS-nPriceL).toFixed(2),cTradeColor,null,Text.PRESET|Text.FRAME|Text.BOLD,”Arial”,10,”TradeProfit”+rawtime(0));
        }    
    }
    
    drawTextRelative(4,BottomRow3,”Net Profit/Loss “+NetProfit.toFixed(2),Color.black,null,Text.PRESET,”Arial”,12,”NetProfit”);
    drawTextRelative(4,BottomRow2,”Total Trades “+nTradeCounter,Color.black,null,Text.PRESET,”Arial”,12,”nTradeCounter”);
    
var nMeganRatio = 0;
var nTWR = 0;
var ngeom = 0;
var Trades = nTradeCounter;

    nTWR = (StartCapital + NetProfit) / StartCapital;
    ngeom = Math.pow(nTWR, 1 / Trades);
    nMeganRatio = MaxTradesPerYear * Math.log(ngeom);
   
    drawTextRelative( 4, BottomRow1, “Megan Ratio = “+nMeganRatio.toFixed(6) , Color.black, null, Text.PRESET,”Arial”,12, “MeganRatio”);    

    return new Array(xEntry.getValue(0), xExit.getValue(0)); 
}

function verify() {
    var b = false;
    if (getBuildNumber() < 779) {
        drawTextAbsolute(5, 35, “This study requires version 8.0 or later.”, 
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, “error”);
        drawTextAbsolute(5, 20, “Click HERE to upgrade.@URL=https://www.esignal.com/download/default.asp”, 
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, “upgrade”);
        return b;
    } else {
        b = true;
    }
    return b;
}

MeganRatio.efs

/*********************************
Provided By:  
    eSignal (Copyright c eSignal), a division of Interactive Data 
    Corporation. 2008. All rights reserved. This sample eSignal 
    Formula Script (EFS) is for educational purposes only and may be 
    modified and saved under a new file name.  eSignal is not responsible
    for the functionality once modified.  eSignal reserves the right 
    to modify and overwrite this EFS file with each new release.

Description:        
    Megan Ratio

Version:            1.0  11/07/2008

Formula Parameters:                     Default:
    MaxTradesPerYear                    8
    Trades                              3
    StartCapital                        100000
    NetProfit                           1000

Notes: 
    The related article is copyrighted material. If you are not
    a subscriber of Stocks & Commodities, please visit www.traders.com.


**********************************/

var fpArray = new Array();
var bVersion = null;

function preMain() {
    setPriceStudy(true);
    setShowCursorLabel(false);
    setShowTitleParameters( false );
    setStudyTitle(“Megan Ratio”);

    var x=0;
    fpArray[x] = new FunctionParameter(“StartCapital”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Start Capital”);
        setLowerLimit(0);	
        setDefault(100000);
    }
    fpArray[x] = new FunctionParameter(“NetProfit”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“NetProfit”);
        setDefault(1000);
    }
    fpArray[x] = new FunctionParameter(“MaxTradesPerYear”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Max Trades Per Year”);
        setLowerLimit(1);
        setDefault(8);
    }
    fpArray[x] = new FunctionParameter(“Trades”, FunctionParameter.NUMBER);
	with(fpArray[x++]){
        setName(“Total Trades”);
        setLowerLimit(1);
        setDefault(3);
    }   
}

function main(MaxTradesPerYear, Trades, StartCapital, NetProfit) {
var nMeganRatio = 0;
var nTWR = 0;
var ngeom = 0;

    if (bVersion == null) bVersion = verify();
    if (bVersion == false) return;   

    nTWR = (StartCapital + NetProfit) / StartCapital;
    ngeom = Math.pow(nTWR, 1 / Trades);
    nMeganRatio = MaxTradesPerYear * Math.log(ngeom);
   
    drawTextRelative( 2, TopRow3, “Megan Ratio = “+nMeganRatio.toFixed(6), Color.black, null, Text.PRESET,”Arial”,12, “MeganRatio”);    
    return; 
}

function verify() {
    var b = false;
    if (getBuildNumber() < 779) {
        drawTextAbsolute(5, 35, “This study requires version 8.0 or later.”, 
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, “error”);
        drawTextAbsolute(5, 20, “Click HERE to upgrade.@URL=https://www.esignal.com/download/default.asp”, 
            Color.white, Color.blue, Text.RELATIVETOBOTTOM|Text.RELATIVETOLEFT|Text.BOLD|Text.LEFT,
            null, 13, “upgrade”);
        return b;
    } else {
        b = true;
    }
    return b;
}

—Jason Keck
eSignal, a division of Interactive Data Corp.
800 815-8256, www.esignalcentral.com


BACK TO LIST

NEUROSHELL TRADER: Megan Ratio

The Megan ratio described by Oscar Cagigas in his article in this issue, “The Megan Ratio,” can be easily implemented in NeuroShell Trader by combining a few of the NeuroShell Trader’s 800+ indicators.

To recreate the Megan ratio based on a previously created Trading Strategy, select “New Indicator ...” from the Insert menu and use the Indicator Wizard to create the following indicators:

geom:
Power( Add2( 1, Divide( NetProfit(TradingStrategy), RequiredAccountSize(TradingStrategy) ) ), Divide ( 1 , NumTrades(TradingStrategy) ) )

mtpy:
Divide( 252, Divide( TotalTradeSpan(TradingStrategy), NumTrades(TradingStrategy) ) )

Geometric Percentage:
Multiply2( 100, Subtract( geom, 1 ) )

Meagan Ratio:
Multiply2 ( mtpy, ln( geom ) )

To recreate the system 1 described in the article (Figure 5), select “New Trading Strategy...” from the Insert menu and enter the following in the appropriate locations of the Trading Strategy Wizard:

Long Entry when all of the following conditions are true:  
  HighChannelBreakout ( High, 20 )

Long Exit when all of the following conditions are true:
  LowChannelBreakout ( Low, 10 )


FIGURE 5: NeuroShell, MEGAN RATIO. Here is the Megan ratio on a chart of AAPL.

To recreate the system 2 described in the article, select “New Trading Strategy...” from the Insert menu and enter the following in the appropriate locations of the Trading Strategy Wizard:

 Long Entry when all of the following conditions are true:  
   HighChannelBreakout ( High, 1 )
   A=B( Lag( AvgCrossoverAbove( Close, 5, 20 ), 1), 1 )

Long Exit when all of the following conditions are true:
   LowChannelBreakout ( Low, 2 )


 

If you have NeuroShell Trader Professional, you can also choose whether the system parameters should be optimized. After backtesting the trading strategy, use the “Detailed Analysis...” button to view the backtest and trade-by-trade statistics for the strategies.

Users of NeuroShell Trader can go to the Stocks & Commodities section of the NeuroShell Trader free technical support website to download a copy of this or any past Traders’ Tips.

—Marge Sherald, Ward Systems Group, Inc.
301 662-7950, sales@wardsystems.com
www.neuroshell.com


BACK TO LIST

AIQ: Megan Ratio

The Aiq code is shown here for Oscar Cagigas’s metric, the Megan ratio, as described in his article in this issue, “The Megan Ratio.” The code includes the two systems described by the author as examples of comparing the systems using the Megan ratio metric. I have also included the code for the filter on the second system.

I used the same portfolio and time period as the author did in my tests, but my resulting metrics are different than the author’s. This is due to the fact that I ran 20 tests for each system using a random variable to choose the trades. A full 100% of the capital was applied to each trade. I then averaged the 20 random runs to get the inputs for the Megan ratio.

In the table in Figure 6, I show the three reports that are produced by the Eds module. Although my Megan ratios are somewhat different than those of the author, I have the same relative results, in that system 1 has a higher ratio than system 2, and the filtered system 2 has a higher ratio than the unfiltered system.

FIGURE 6: AIQ, MEGAN RATIO. Here is a comparison of the three systems using the metrics given in Oscar Cagigas’s article.

!! THE MEGAN RATIO.TASC Jan 2008
! Author: Oscar G. Cagigas
! Coded by: Richard Denning 11/06/2008
! TradersEdgeSystems.com


Symbols if symbol() <> “SYSTEM1” 
	and symbol() <> “SYSTEM2”
	and symbol() <> “SYSTEM3”.


!! SYSTEM 1 (from article):
H is [high].
H1 is valresult(H,1).
L is [low].
O is [open].
C is [close].
PD is {position days}.


LE1 if H > highresult(H,20,1) and Symbols.
EntryPr1 is max(H1,O).
LX1 if L < lowresult(L,10,1) and PD >= 2.
ExitPr1 is min(lowresult(L,10,1),O).

!! SYSTEM 2 (from article):
Setup if simpleavg(C,5) > simpleavg(C,20).
LE2 if valrule(Setup,1) and H > H1 and Symbols.
EntryPr2 is max(O,H1).
LX2 if L < lowresult(L,2,1) and PD >= 2.
ExitPr2 is min(lowresult(L,2,1),O).


!! SYSTEM 2 WITH ADDED FILTER (from article):
LE2F if LE2 and (month() < 4 or month() > 7).
! All other parts fo the system are the same


!------------------------------------------------------------------------
!---After running system tests, use the summary reports
! to get the inputs which must be manually typed in below
! then run the EDS reports:


!! INPUTS FROM THE SYSTEM TESTS
! RUN IN PORTFOLIO MANAGER
! THREE SYSTEMS CAN BE COMPARED:
! INPUT1:
BegEq1 is 	 100000.
EndEq1 is 	 5839557.
TotTrds1 is  85.55.
AvgHold1 is  29.70.



! INPUT2:
BegEq2 is 	 100000.
EndEq2 is 	 2283895.
TotTrds2 is  443.15.
AvgHold2 is  5.45.


! INPUT3:  
BegEq3 is 	 100000.
EndEq3 is 	 990958.
TotTrds3 is  294.5.
AvgHold3 is  5.80.


! COMPUTE METRICS AND MEGAN RATIO:
TWR1		is EndEq1 / BegEq1.
GeoMean1 	is Power(TWR1,1/TotTrds1).
MaxTrdsYr1	is 252 / AvgHold1.
MeganRatio1	is MaxTrdsYr1 * ln(GeoMean1).


SystemReport1	if symbol() = “SYSTEM1”.


TWR2		is EndEq2 / BegEq2.
GeoMean2 	is Power(TWR2,1/TotTrds2).
MaxTrdsYr2	is 252 / AvgHold2.
MeganRatio2	is MaxTrdsYr2 * ln(GeoMean2).


SystemReport2	if symbol() = “SYSTEM2”.


TWR3		is EndEq3 / BegEq3.
GeoMean3	is Power(TWR3,1/TotTrds3).
MaxTrdsYr3	is 252 / AvgHold3.
MeganRatio3	is MaxTrdsYr3 * ln(GeoMean3).


SystemReport3	if symbol() = “SYSTEM3”.


 

The code can be downloaded from the Aiq website at www.aiqsystems.com and also from www.tradersedgesystems.com/traderstips.htm.

—Richard Denning
For AIQ Systems
richard.denning@earthlink.net


BACK TO LIST

TRADERSTUDIO: Megan Ratio

The TradersStudio code is shown here for Oscar Cagigas’s system metric, the Megan ratio, described in his article in this issue.

In the article, Cagigas provides the code for two simple trading systems that trade on the long side only and were compared using a 30-stock portfolio. I converted the code for use on futures by adding the trading rules for the short side.

The code for the systems is not shown here but can be downloaded from either of the two websites listed below. The code shown here is for the custom report, which calculates the Megan ratio for any system on any portfolio.

One problem that many beginning futures traders face is that with a small account balance, they are limited in what they can trade. I decided to try to use the Megan ratio report to help in selecting a single market to trade with each system. I assumed that $50,000 would be allocated to each system. I wanted to limit the maximum drawdowns to 25–30%. To select which market to trade on each system, I first ran 16 actively traded markets on each system using the percent margin trade plan that is included in the TradersStudio product. I set the margin percent to 25% for the initial test of all 16 markets.

In the table in Figure 7, I show the custom report for system 1 and also for system 2. I have sorted each report by the Megan ratio so that the better markets for each system are shown at the top. I highlighted in green the market that I decided to use for my single-market trading. In choosing the two markets, I used both the Megan ratio and the net profit to maximum drawdown ratio. For system 1, I chose the TY market (10-year note) and for system 2, I chose the LH market (live hogs).

FIGURE 7: TRADERSTUDIO, MEGAN RATIO, INITIAL REPORT. Here is a Megan ratio custom report for system 1 and system 2 on 16 different markets. From this, it appears as though system 2 is the superior system.

It appears from the first test that system 2 is the better system since it has a higher Megan ratio. However, this test was run without commissions or slippage factored in. For the final test, I included a commission of $5 and slippage of $50 per contract round-turn. The final results of trading the chosen single market in each system are shown in Figure 8, which includes the resulting equity curve, underwater equity, and the custom report for each system. Using an initial account size of $50,000 for each system, I adjusted the percent of margin utilized until the maximum drawdown percent was within the target range of 25–30%. Now that the commission and slippage have been added, it is clear that system 1 is superior to system 2, since the Megan ratio for system 1 is now 0.0184 versus 0.0049 for system 2, and the profit is 3.7 times higher for system 1. The code can be downloaded from the TradersStudio website at www.TradersStudio.com ->Traders Resources->FreeCode and also from www.TradersEdgeSystems.com/traderstips.htm.

FIGURE 8: TRADERSTUDIO, MEGAN RATIO, FINAL RESULTS. Here are sample final results for system 1 trading TY and system 2 trading LH. Once commission and slippage are added in, system 1 proves to be the superior system.

 Sub CUSTOM_MetricReport(BegEq)
Dim RowNum, NetPL, MaxDD, TotTrds, AvgHold, EndEq
Dim TWR, GeoMean, MaxTrdsYr, MeganRatio, i, MeganSum
Dim MeganAvg, Years, AvgTrdsYr, AvgTrdsYrAll, TotTrdsYr
Dim TotMaxTrdsYr, AvgMaxTrdsYr, minMktsNeeded, LongPftPct
Dim meganArr As Array
Dim avgTrdsYrArr As Array
Dim avgMaxTrdsYrArr As Array
ReDim(meganArr,GetMomSeriesCount())
ReDim(avgTrdsYrArr,GetMomSeriesCount())
ReDim(avgMaxTrdsYrArr,GetMomSeriesCount())
    If BarNumber=FirstBar Then Gvalue30 = Date
    If MomSeries=1 Then Gvalue50 = 1
    If BarNumber = LastBar Then
        RowNum = Gvalue50
        meganArr = Gvalue51
        avgTrdsYrArr = Gvalue52
        avgMaxTrdsYrArr = Gvalue53
        If RowNum=1 Then
            SetTextValue(“Custom Metrics Report”,1,1,5)
            SetTextValue(“Symbol”,RowNum+2,1,5)
            SetTextValue(“Start Date”,RowNum+2,2,8)
            SetTextValue(“End Date”,RowNum+2,3,8)
            SetTextValue(“         Net Profit”,RowNum+2,4,10)
            SetTextValue(“          Max DD”,RowNum+2,5,10)
            SetTextValue(“ NetPft/MaxDD”,RowNum+2,6,10)
            SetTextValue(“  Tot Trades”,RowNum+2,7,10)
            SetTextValue(“  AvgTrades/Yr”,RowNum+2,8,10)
            SetTextValue(“        Avg Hold”,RowNum+2,9,10)
            SetTextValue(“             TWR”,RowNum+2,10,10)
            SetTextValue(“        GeoMean”,RowNum+2,11,10)
            SetTextValue(“  MaxTrades/Yr”,RowNum+2,12,10)
            SetTextValue(“    Megan Ratio”,RowNum+2,13,10)
            SetTextValue(“  LongNetPftPct”,RowNum+2,14,10)
            RowNum = RowNum+2
        End If 
        RowNum = RowNum + 1
        Gvalue50 = RowNum
        NetPL = Round(GetNetProfit(0)+OpenPositionProfit,0)
        If NetPL>0 Then LongPftPct = (getSysPerformance(“LN”,0)/NetPL)*100
        MaxDD = Round(GetSysPerformance(“DD”,0),0)
        TotTrds = notrades
        Years = (Date - Gvalue30) / 365
        If Years > 0 Then AvgTrdsYr = TotTrds / Years   
        AvgHold = AveHoldPeriod   
        EndEq = Max(BegEq + thisMarket.CurEquity,0)
        If BegEq > 0 Then TWR = Round(EndEq / BegEq,6)
        If TotTrds > 0 Then GeoMean = TWR ^ (1/TotTrds)
        If AvgHold > 0 Then MaxTrdsYr = 252 / AvgHold
        If GeoMean > 0 Then MeganRatio=MaxTrdsYr*Log(GeoMean)
        meganArr[RowNum-4] = MeganRatio
        avgTrdsYrArr[RowNum-4] = AvgTrdsYr
        avgMaxTrdsYrArr[RowNum-4] = MaxTrdsYr
        For i = 0 To RowNum-4
           MeganSum = MeganSum + meganArr[i] 
           If (i+1) > 0 Then MeganAvg = MeganSum / (i+1)
           TotTrdsYr = TotTrdsYr + avgTrdsYrArr[i]
           If (i+1) > 0 Then AvgTrdsYrAll = TotTrdsYr / (i+1)
           TotMaxTrdsYr = TotMaxTrdsYr + avgMaxTrdsYrArr[i]
           If (i+1) > 0 Then AvgMaxTrdsYr = TotMaxTrdsYr / (i+1)
        Next
        Gvalue51 = meganArr
        Gvalue52 = avgTrdsYrArr
        Gvalue53 = avgMaxTrdsYrArr
        SetTextValue(MySymbol(),RowNum,1,8)
        SetTextValue(FormatDateTime(Gvalue30),RowNum,2,8)
        SetTextValue(FormatDateTime(Date),RowNum,3,8)
        SetCurrencyValue(NetPL,RowNum,4,10)   
        SetCurrencyValue(MaxDD,RowNum,5,10)
        If -MaxDD > 0 Then SetFloatValue(NetPL/-MaxDD,RowNum,6,10)
        SetLongValue(TotTrds,RowNum,7,10)
        SetLongValue(AvgTrdsYr,RowNum,8,10)
        SetFloatValue(AvgHold,RowNum,9,10)   
        SetFloatValue(TWR,RowNum,10,10)
        SetFloatValue(GeoMean,RowNum,11,10)   
        SetLongValue(MaxTrdsYr,RowNum,12,10)
        SetFloatValue(MeganRatio,RowNum,13,10)
        SetLongValue(LongPftPct,RowNum,14,10)
        If RowNum-3 = GetMomSeriesCount() Then
            SetTextValue(“Average All Markets”,RowNum+2,1,5)
            SetLongValue(AvgTrdsYrAll,RowNum+2,8,10)
            SetLongValue(AvgMaxTrdsYr,RowNum+2,12,10)
            SetFloatValue(MeganAvg,RowNum+2,13,10)
            SetTextValue(“Total All Markets”,RowNum+3,1,5) 
            SetLongValue(TotTrdsYr,RowNum+3,8,5)
            SetTextValue(“Minimum Markets Needed for Megan Ratio”,RowNum+4,1,5)
            If AvgTrdsYrAll > 0 Then minMktsNeeded=Floor(AvgMaxTrdsYr/AvgTrdsYrAll)+1
            SetLongValue(minMktsNeeded,RowNum+4,13,10)
        End If 
    End If
End Sub

—Richard Denning
ForTradersStudio
richard.denning@earthlink.net


BACK TO LIST

STRATASEARCH: Megan Ratio

Instead of focusing on an indicator that allows the trader to select profitable buy and sell signals, Oscar Cagigas’s article in this issue, “The Megan Ratio,” focuses on the ability to select profitable trading systems in general. There are many aspects to consider when evaluating a trading system, and an examination of reinvested profits is a worthwhile objective.

Since StrataSearch allows users to create custom performance metrics for both display and filtering, we first added the formulas for Megan ratio and geometric mean percentage to the program. Next, we ran an automated search to investigate a few hundred thousand unique trading systems, looking for the system with the highest Megan ratio value. While this proved effective at picking the system with the greatest profits, it also became apparent that the use of additional performance metrics alongside the Megan ratio is necessary to select a robust system, just as the author suggests.

While the Megan ratio can certainly be used in StrataSearch, users can also change the “Report To Variable Trade Equity” instead of “Fixed Trade Equity.” The “Variable Trade Equity” approach adjusts trade amounts based on available equity, and therefore allows users to see the full spectrum of performance metrics based exclusively on reinvesting profits.

As with all other Traders’ Tips, additional information, including plug-ins, can be found in the Shared Area of the StrataSearch User Forum. This month’s plug-in contains the Megan ratio and geometric mean column definitions, as well as a new Detailed Analysis View incorporating these columns. See Figure 9.

FIGURE 9: STRATASEARCH, MEGAN RATIO. As shown in this Detailed Analysis window, the Megan ratio can be used alongside other performance metrics to evaluate the quality of your trading systems.

//*************************************************************************
// MEGAN Ratio Formulas
//*************************************************************************
MEGANRatio = 252/$F_AvgDays * ($F_EndEquity/$F_InitEquity)^(1/$F_NumTrades)
GeomMean% = 100*((($F_EndEquity/$F_InitEquity)^(1/$F_NumTrades))-1)


   

—Pete rast
Avarin Systems, Inc.
www.StrataSearch.com


BACK TO LIST

NINJATRADER: Megan Ratio

We have implemented the Megan ratio, as discussed by Oscar Cagigas in his article in this issue, “The Megan Ratio,” as methods in two sample strategies. These are available for download at www.ninjatrader.com/SC/January2009SC.zip.

Once downloaded, from within the NinjaTrader Control Center window, select the menu File > Utilities > Import NinjaScript and select the downloaded file. These indicators are for NinjaTrader Version 6.5 or greater.

You can review the strategy’s source code by selecting the menu Tools > Edit NinjaScript > Strategy from within the NinjaTrader Control Center window and selecting either MeganRatioStrategy1 or MeganRatioStrategy2.

NinjaScript strategies are compiled Dlls that run native, not interpreted, which provides you with the highest performance possible.

FIGURE 10: NINJATRADER, MEGAN RATIO. This NinjaTrader screenshot shows the Megan ratio values plotted in the lower left-hand corner of the chart, where the strategy is running.

—Raymond Deux & Josh Peng
NinjaTrader, LLC
www.ninjatrader.com


BACK TO LIST

TRADE NAVIGATOR/TRADESENSE: Megan Ratio

Trade Navigator allows you to compare the results of two or more strategies. You can recreate the strategies described in “The Megan Ratio” by Oscar Cagigas in this issue using the following TradeSense code:

System 1:
System 1 Entry

IF High > Highest (High , 20).1
Long Entry (Buy)
Stop
Max (High.1 , Open)

System 1 Exit

IF Low < Lowest (Low , 10).1
Long Exit (Sell)
Stop
Min (Lowest (Low , 10).1 , Open)

System 2:
System 2 Entry

IF MovingAvg (Close , 5) > MovingAvg (Close , 20) And High > High.1
Long Entry (Buy)
Stop
High.1

System 2 Exit

IF Low < Lowest (Low , 2).1
Long Exit (Sell)
Stop
Min (Lowest (Low , 2).1 , Open)

System 2 w/Filter:
System 2 Entry

IF MovingAvg (Close , 5) > MovingAvg (Close , 20) And High > High.1 And (Month < 4 Or Month > 7)
Long Entry (Buy)
Stop
High.1

System 2 Exit

IF Low < Lowest (Low , 2).1
Long Exit (Sell)
Stop
Min (Lowest (Low , 2).1 , Open)

FIGURE 11: TRADE NAVIGATOR/TRADESENSE, MEGAN RATIO. Shown are sample results.

When you have the strategies that you want to compare, enter the strategies in a strategy basket. With the strategies in a strategy basket, you can run all strategies in the basket at the same time and compare or combine the results by simply running the basket.

To add strategies to a strategy basket and run them for comparison, follow these steps:

  1. Go to the “Strategy Baskets” tab in the Trader’s Toolbox of Trade Navigator and click the New button.
  2. Select the first strategy to compare from the Strategy dropdown menu, select the symbol or symbol group that you wish to run the strategy on, set the period to “test,” and click the OK button.
  3. To add more strategies to the basket, click on the “Add Item” button and repeat step #2.
  4. Click the Save button on the “New Strategy Basket” window, type in a name for the basket, and click OK.
  5. Click the Run button. (See Figure 11.) On this screen, you can see items for each strategy, such as:

Win%; Trades (number of trades); Wins; Losses; Payout;
Average Win; Return %; Average Loss ;Largest Win; Largest Loss;
Net Profit; Profit Factor; Average Trade; and Max Drawdown

For more detailed reports, click on the “Reports” button. For reports that show how the strategies would perform used in combination, click on the “Merged reports” button.

The equity curve can be displayed for strategies when you view the “money management” tab in Reports after running a strategy.

Genesis Financial Technologies has provided these strategies and strategy basket in a special file named “SC0109,” downloadable through Trade Navigator.

—Michael Herman
Genesis Financial Technologies
www.GenesisFT.com


BACK TO LIST

VT TRADER: Megan Ratio

Our Traders’ Tip submission is inspired by Oscar Cagigas’s article in this issue, “The Megan Ratio.” In the article, Cagigas describes a mathematical calculation called the maximum exponential growth annualized (Megan, for short) ratio. Cagigas describes the Megan ratio as, “...a metric specifically designed to highlight the system that generates more returns per year when the profits are reinvested, regardless of the number of trades, holding period, drawdown, and so on.”

FIGURE 12: VT TRADER, the MEGAN RATIO. Here is a sample trading system with equity, geometric mean %, and Megan ratio plots attached to a EUR/USD daily candle chart.

We’ll be offering a sample trading system that calculates equity, geometric mean %, and the Megan ratio for download in our client forums. The VT Trader instructions for creating the aforementioned sample trading system are as follows:

Sample trading system for calculating the Megan ratio

1. Navigator Window>Tools>Trading Systems Builder>[New] button
2. In the Indicator Bookmark, type the following text for each field:

Name: TASC - 01/2009 - The Megan Ratio
Short Name: tasc_MeganRatio
Label Mask: TASC - 01/2009 - The Megan Ratio


 

3. In the Input Bookmark, create the following variables:

   [New] button... Name: SP , Display Name: Currency Spread (in 
     Pips) , Type: integer , Default: 2
   [New] button... Name: InitialCapital , Display Name: Simulated 
    Initial Capital , Type: float , Default: 100000.00
   [New] button... Name: LS , Display Name: Simulated Lot Size ,
    Type: float , Default: 1.0000
   [New] button... Name: CT , Display Name: Chart Type (BidAsk)?
    , Type: Enumeration , Default: Bid (Click […] button -> [New]
    button -> type Bid; [New] button -> type Ask; [OK] button)

4. In the Output Bookmark, create the following variables:

 [New] button...
        Var Name: LongEntrySignal
        Name: LongEntrySignal
        Description: Long Entry Signal Alert 
        * Checkmark: Graphic Enabled
        Select Graphic Bookmark
                 Font […]: Up Arrow
                 Size: Medium
                 Color: Blue
                 Symbol Position: Below price plot
        [OK] button...


 [New] button...
        Var Name: LongExitSignal
        Name: LongExitSignal
        Description: Long Exit Signal Alert 
        * Checkmark: Graphic Enabled
        Select Graphic Bookmark
                 Font […]: Exit Sign
                 Size: Medium
                 Color: Blue
                 Symbol Position: Above price plot
       [OK] button...

 
 [New] button...
        Var Name: ShortEntrySignal
        Name: ShortEntrySignal
        Description: Short Entry Signal Alert 
        * Checkmark: Graphic Enabled
        Select Graphic Bookmark
                 Font […]: Down Arrow
                 Size: Medium
                 Color: Red
                 Symbol Position: Above price plot
        [OK] button...


 [New] button...
        Var Name: ShortExitSignal
        Name: ShortExitSignal
        Description: Short Exit Signal Alert 
        * Checkmark: Graphic Enabled
        Select Graphic Bookmark
                 Font […]: Exit Sign
                 Size: Medium
                 Color: Red
                 Symbol Position: Below price plot
        [OK] button...


 [New] button...
        Var Name: Equity
        Name: Equity
        * Checkmark: Indicator Output
        Select Indicator Output Bookmark
                 Color: black
                 Line Width: slightly thicker
                 Line Style: solid
                 Placement: Additional Frame 1
	    [OK] button...


 [New] button...
        Var Name: GeometricMeanPercentage
        Name: Geometric Mean %
        * Checkmark: Indicator Output
        Select Indicator Output Bookmark
                 Color: purple
                 Line Width: slightly thicker
                 Line Style: solid
                 Placement: Additional Frame 2
        [OK] button...

	
 [New] button...
        Var Name: MeganRatio
        Name: Megan Ratio
        * Checkmark: Indicator Output
        Select Indicator Output Bookmark
                 Color: blue
                 Line Width: slightly thicker
                 Line Style: solid
                 Placement: Additional Frame 3
        [OK] button...

5. In the Formula Bookmark, copy and paste the following formula:

//Provided By: Visual Trading Systems, LLC & Capital Market Services, LLC
//Copyright (c): 2008
//Notes: January 2009 T.A.S.C. magazine
//Notes: “Which System = Higher Return; The Megan Ratio” by Oscar G. Cagigas}
//Description: Equity, Geometric Mean %, and Megan Ratio
//File: tasc_MeganRatio.vttrs


{Pip Values}


Spread:= SP * SymbolPoint();
LotSize:= LS * 100000.00;


{Sample Trading System Entry/Exit Signals}


BuyCondition:= H > ref(HHV(H,20),-1);
SellCondition:= L < ref(LLV(L,20),-1);


LongEntrySignal:= LongTradeAlert=0 AND BuyCondition;
LongExitSignal:= LongTradeAlert=1 AND SellCondition;
ShortEntrySignal:= ShortTradeAlert=0 AND SellCondition;
ShortExitSignal:= ShortTradeAlert=1 AND BuyCondition;


{Simulated Open Trade Determination for Signals}


LongTradeAlert:= SignalFlag(LongEntrySignal,LongExitSignal);
ShortTradeAlert:= SignalFlag(ShortEntrySignal,ShortExitSignal);


{Simulated Entry/Exit Prices}


LongEntryPrice:= valuewhen(1,ref(LongEntrySignal,-1),O) + (if(CT=0,Spread,0));
LongExitPrice:= valuewhen(1,ref(LongExitSignal,-1),O) - (if(CT=1,Spread,0));
ShortEntryPrice:= valuewhen(1,ref(ShortEntrySignal,-1),O) - (if(CT=1,Spread,0));
ShortExitPrice:= valuewhen(1,ref(ShortExitSignal,-1),O) + (if(CT=0,Spread,0));


{Simulated Profit/Loss Statistics}


TradeProfit:= (if(ref(LongExitSignal,-1)=1,LongExitPrice - LongEntryPrice,
       if(ref(ShortExitSignal,-1)=1,ShortEntryPrice - ShortExitPrice,
       0))) * LotSize;


AvgBarsHeld:= (cum(if(LongExitSignal,BarsSince(LongEntrySignal),0)) +
       cum(if(ShortExitSignal,BarsSince(ShortEntrySignal),0))) / 
       TotalTrades;


MaxTradesPerYear:= 252/AvgBarsHeld;


TotalTrades:= if(LongExitSignal=NULL OR ShortExitSignal=NULL,0,
                 cum(LongExitSignal) + cum(ShortExitSignal));


Equity:= InitialCapital + cum(TradeProfit);


TWR:= Equity/InitialCapital;


GeometricMean:= if(TotalTrades<1 OR Equity<=0,NULL,power(TWR,(1/TotalTrades)));
GeometricMeanPercentage:= 100 * (GeometricMean-1);

MeganRatio:= MaxTradesPerYear * log(GeometricMean);

6. Click the “Save” icon to finish building the trading system.

To attach the trading system to a chart, select the “Add Trading System” option from the chart’s contextual menu, select “TASC — 01/200 — The Megan Ratio” from the trading systems list, and click the [Add] button. See Figure 12 for a sample chart.

To learn more about VT Trader, visit www.cmsfx.com.

Forex trading involves a substantial risk of loss and may not be suitable for all investors.

—Chris Skidmore
Visual Trading Systems, LLC (courtesy of CMS Forex)
(866) 51-CMSFX, trading@cmsfx.com
www.cmsfx.com


BACK TO LIST

TRADE IDEAS: Megan Ratio

“Things may come to those who wait, but only the things left by those who hustle.”—Abraham Lincoln

For this month’s Traders’ Tips, we’ve provided a strategy that came from our support forum but that is inspired by Oscar Cagigas’s article in this issue, “The Megan Ratio.” Our inspiration comes from the same question, “Which system will generate more return?”, but this article won’t be heavy on the math and equations.

The following strategy aims to find and profit from a V-bottom pattern. Then using the OddsMaker, which is Trade-Ideas’s backtesting tool, we derive the optimum hold time and stop loss.

The strategy’s configuration within Trade-Ideas Pro can be seen in Figure 13.

FIGURE 13: TRADE-IDEAS PRO, STRATEGY CONFIGURATION. This strategy aims to find and profit from a V-bottom pattern.

Step 1: Create a V-bottom pattern-recognition strategy
Use the short-term “Running up now” alert as the trigger. Set the alert-specific filter to $0.35, meaning that the stock has to move up at least 35 cents in the last minute to appear in the results.

Step 2: Draw the V part of the pattern using filters
To make sure every alert looks like the V-bottom pattern, we use the “Position in range” filter set to a maximum of 5%. This means that the “Running up now” alert will only be triggered if it does so in the lower 5% (percentile) of the stock’s daily trading range. In this particular example, we also added a “maximum price” filter of $150 to limit ourselves to stocks we could potentially trade with some size. In addition, we added the “Min average daily volume” filter set to 100,000; a “Maximum spread” filter of 10 cents; and the “Maximum Distance from Inside Market or Unusual bad market data” filter to avoid alerts triggered by bad prints.

The definitions of this alert and these filters appear here: https://www.trade-ideas.com/Help.html.

Step 3: OddsMaker Analysis: Creating the backtest (Figure 14)
In the tradition of V-bottoms, we are looking to buy or go long the stocks that appear in this strategy. After taking several time options, we optimized that the best hold time was 30 minutes, meaning we would exit this trade 30 minutes after we entered the position or sooner if we were stopped out.

Risk management:
Today’s market is more volatile than most traders are used to. What that means is you can no longer trade stocks and have arbitrary 10—, 15—, or 20—cent stops. The range of stock movement is much more exaggerated. To compensate, Trade-Ideas invented a proprietary stop-loss metric called “the wiggle.” The wiggle takes the average 15-minute volatility and multiplies it by the relative volume at the time of the alert. That means that for every stock you have a unique, statistically valid stop. In Figure 14, you see the stop-loss of 1 cent plus the wiggle.

FIGURE 14: TRADE-IDEAS, CONFIGURING THE ODDSMAKER. Using OddsMaker, which is Trade-Ideas’s backtesting tool, the optimum hold time and stop loss values are derived.

Here are the trade rules used:

Figure 15 shows the results (last backtested for the period 10/20/2008 to 11/5/2008): 15 out of 19 possible trades were winners — with an average winner to average loser ratio of almost twice.

FIGURE 15: TRADE-IDEAS, the MEGAN RATIO. Here are sample results for the strategy, 10/20/2008 to 11/5/2008.

You can learn more about interpreting backtest results from the OddsMaker by reading the user’s manual at https://www.trade-ideas.com/OddsMaker/Help.html.

—Dan Mirkin, Trade Ideas LLC
dan@trade-ideas.com
www.trade-ideas.com


BACK TO LIST

AMIBROKER: Megan Ratio (Cagigas Article Code)

Calculating the megan ratio
The AmiBroker code to calculate the Megan ratio is provided below. AmiBroker allows adding a custom metric to the standard statistics. In this case we will add the geometric average and the Megan ratio.

We can add the code below to our system or save it in the include folder and just add the following line to the system:

#include <geom.afl>

That will add 2 metrics to the standard statistics, the geometric mean and the Megan ratio.

 MEGAN RATIO CALCULATION
//	geom.afl
//
SetCustomBacktestProc(“”);
if (Status(“action”) == actionPortfolio)
{
	bo = GetBacktesterObject();
	bo.backtest();
	st = bo.getperformancestats(0);
	geom = (st.getvalue(“EndingCapital”)/st.getvalue(“InitialCapital”))^(1/st.getvalue(“AllQty”));
	geomp = 100*(geom-1); //geom percentage
	mtpy = 252/st.getvalue(“AllAvgBarsHeld”); //maximum number of trades per year
	meg= mtpy*ln(geom); //max exponential growth rate (annual)
	bo.addcustommetric(“Geom%”, geomp);	
	bo.addcustommetric(“MEGAN Ratio”, meg);	


 

Comparing two trading systems
System 1 is a breakout system of using 20 and 10 periods .

 //entry//
Buy = Cond = H > Ref(HHV(H,20),-1);
BuyPrice = Max(Ref(H,-1),Open);

//exit//
Sell= L < Ref(LLV(L,10),-1);
SellPrice = Min(Ref(LLV(L,10),-1),Open);

 

System 2 is a moving average system that takes long trades after the crossover if the previous high is exceeded. We sell only if the low of 2 previous bars is broken.

 //SETUP//
setup=MA(C,5) > MA(C,20);

//Long Entry//
Buy= Ref(setup,-1) AND H > Ref(H,-1);
BuyPrice=Ref(H,-1);

//SELL//
Sell=L < Ref(LLV(L,2),-1);
SellPrice=Min(Ref(LLV(L,2),-1),Open);

Evaluating the effect of a filter
In this case we are going to remove trades from April to July inclusive. The new filtered code is seen below.

#include 
//SETUP//
setup=MA(C,5) > MA(C,20);
//filter//
filtro=Month() < 4 OR Month() > 7;
//Long Entry//
Buy= Ref(setup,-1) AND H > Ref(H,-1) AND filtro;
BuyPrice=Ref(H,-1);
//SELL//
Sell= L < Ref(LLV(L,2),-1);
SellPrice=Min(Ref(LLV(L,2),-1),Open);

—Oscar Cagigas
www.onda4.com
oscar@onda4.com


BACK TO LIST

Return to January 2009 Contents