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. June 2006
TRADERS' TIPSYou 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:
TRADESTATION: BROWNIAN MODEL STRATEGY
WEALTH-LAB: BROWNIAN MODEL STRATEGY
AMIBROKER: BROWNIAN MODEL STRATEGY
eSIGNAL: BROWNIAN MODEL STRATEGY
AIQ: BROWNIAN MODEL STRATEGY
NEUROSHELL TRADER: BROWNIAN MODEL STRATEGY
NEOTICKER: BROWNIAN MODEL STRATEGY
TRADING SOLUTIONS: BROWNIAN MODEL STRATEGY
BIOCOMP DAKOTA: BROWNIAN MODEL STRATEGY
FINANCIAL DATA CALCULATOR: BROWNIAN MODEL STRATEGY
MULTICHARTS: BROWNIAN MODEL STRATEGY
TRADECISION: BROWNIAN MODEL STRATEGY
TRADE NAVIGATOR: BROWNIAN MODEL STRATEGY
VT TRADER: BROWNIAN MODEL STRATEGYor return to June 2006 Contents
TRADESTATION: BROWNIAN MODEL STRATEGY
In his article, "Harnessing The (Mis)Behavior Of Markets," Rick Martinelli describes a technique for trading when forecasted price change for the next day exceeds a standard deviation-based threshold. Martinelli uses an Excel spreadsheet to make calculations. These calculations can be implemented in EasyLanguage using the following code.
The "Martinelli Chart" indicator displays the fractional change result as a line. The "Martinelli RS" (RadarScreen) indicator presents the results in tabular form to match the table displayed in the article. The indicator has also been transformed into strategy code to allow for parameter optimization.
To download this TradeStation code, search for the file "Martinelli.eld" in the TradeStation and EasyLanguage support area of the Support Center at TradeStation.com.
Figure 1: TradeStation and RadarScreen. RadarScreen displays the S&P 100 components and Martinelli results. The chart's first subgraph displays General Motors' price history with trades based on Martinelli's indicators. The second subgraph reproduces Martinelli's fractional results as displayed in the article's Figure 6.Indicator: Martinelli Chart inputs: StdDevLen( 7 ), ForecastLen( 3 ), Cutoff( 1.04 ) ; variables: PriceChange( 0 ), PriceForecast( 0 ), W( 0 ), Omega( 0 ), Alpha( 0 ), Signal( 0 ), FractionalGain( 0 ), ThisTrade( 0 ) ; PriceChange = Close - Close[1] ; PriceForecast = LinearRegValue( Close, ForecastLen , -1 ) ; W = PriceForecast - Close ; Omega = StandardDev( PriceChange, StdDevLen, 2 ) ; if Omega > 0 then Alpha = ( PriceForecast - Close ) / Omega ; if Alpha[1] > Cutoff then Signal = 1 else if Alpha[1] < Neg( Cutoff ) then Signal = -1 else Signal = 0 ; if Close[1] > 0 then ThisTrade = Signal * PriceChange / Close[1] ; FractionalGain = FractionalGain + ThisTrade ; Plot1( FractionalGain, "FracGain" ) ; Indicator: Martinelli RS inputs: ForecastLen( 3 ), StdDevLen( 7 ), InitialCutoff ( 1.04 ), IncrementCutoff( 0.02 ) ; variables: SDate( 0 ), BuyHoldEntry( 0 ), PriceChange( 0 ), PriceForecast( 0 ), W( 0 ), Omega( 0 ), Alpha( 0 ), Counter( 0 ), Signal( 0 ), ThisTrade( 0 ), MaxFraction( 0 ), MaxCutoff( 0 ), MaxCounter( 0 ), SDateStr( "" ), EDateStr( "" ), BH( 0 ), Diff( 0 ), WLR( "" ) ; arrays: Cutoff[10]( 0 ), Wins[10]( 0 ), Losses[10]( 0 ), FractionalGain[10]( 0 ), BestPoint[10]( -9999999 ) ; if CurrentBar = 1 then begin SDate = Date ; BuyHoldEntry = Close ; end ; PriceChange = Close - Close[1] ; PriceForecast = LinearRegValue( Close, ForecastLen , -1 ) ; W = PriceForecast - Close ; Omega = StandardDev( PriceChange, StdDevLen, 2 ) ; if Omega > 0 then Alpha = ( PriceForecast - Close ) / Omega ; for Counter = 1 to 10 begin if CurrentBar = 1 then Cutoff[Counter] = InitialCutoff + ( Counter - 1 ) * IncrementCutoff ; if Alpha[1] > Cutoff[Counter] then Signal = 1 else if Alpha[1] < Neg( Cutoff[Counter] ) then Signal = -1 else Signal = 0 ; if Close[1] > 0 and Signal <> 0 then begin ThisTrade = ( ( Signal * PriceChange ) / Close[1] ) ; if ThisTrade > 0 then Wins[Counter] = Wins[Counter] + 1 else if ThisTrade < 0 then Losses[Counter] = Losses[Counter] +1 ; FractionalGain[Counter] = ThisTrade + FractionalGain[Counter] ; end ; if FractionalGain[Counter] > BestPoint[Counter] then BestPoint[Counter] = FractionalGain[Counter] ; end ; if LastBarOnChart then begin MaxFraction = FractionalGain[1] ; MaxCutoff = Cutoff[1] ; for Counter = 2 to 10 begin if MaxFraction < BestPoint[Counter] then begin MaxCounter = Counter ; MaxFraction = BestPoint[Counter] ; end ; end ; SDateStr = ELDateToString( SDate ) ; EDateStr = ELDateToString( Date ) ; if BuyHoldEntry <> 0 then begin BH = ( Close - BuyHoldEntry ) / BuyHoldEntry ; Diff = FractionalGain[MaxCounter] - ( Close - BuyHoldEntry ) / BuyHoldEntry ; end ; if Losses[MaxCounter] + Wins[MaxCounter] > 0 then WLR = NumToStr( Wins[MaxCounter] / ( Losses[MaxCounter] + Wins[MaxCounter] ), 2 ) else WLR = "No Losses" ; Plot1( SDateStr, "SDate" ) ; Plot2( EDateStr, "EDate" ) ; Plot3( Cutoff[MaxCounter], "Cutoff" ) ; Plot4( MaxFraction, "BestPoint" ) ; Plot5( BH, "B&H" ) ; Plot6( FractionalGain[MaxCounter], "LDF" ) ; Plot7( Diff, "Diff" ) ; Plot8( Wins[MaxCounter], "#W" ) ; Plot9( WLR, "WLR" ) ; end ; Strategy: Martinelli Strat inputs: StdDevLen( 7 ), ForecastLen( 3 ), Cutoff ( 1.04 ) ; variables: PriceChange( 0 ), PriceForecast( 0 ), W( 0 ), Omega( 0 ), Alpha( 0 ), TL_ID( -1 ), Signal( 0 ), FractionalGain( 0 ), ThisTrade( 0 ) ; PriceChange = Close - Close[1] ; PriceForecast = LinearRegValue( Close, ForecastLen, -1 ) ; W = PriceForecast - Close ; Omega = StandardDev( PriceChange, StdDevLen, 2 ) ; if Omega > 0 then Alpha = ( PriceForecast - Close ) / Omega ; { Entries } if Alpha > Cutoff then begin TL_ID = TL_New ( Date[1], Time[1], Close, Date, Time, Close ) ; Buy this bar Close ; end else if Alpha < Neg( Cutoff ) then begin TL_ID = TL_New ( Date[1], Time[1], Close, Date, Time, Close ) ; Sell short this bar at Close ; end ; { Exits } if Alpha[1] > Cutoff and Alpha < Cutoff and Alpha > Neg( Cutoff ) then Sell this bar at Close else if Alpha[1] < Neg( Cutoff ) and Alpha > Neg( Cutoff ) and Alpha < Cutoff then Buy to cover this bar Close ;
--Mark Mills
TradeStation Securities, Inc.
A subsidiary of TradeStation Group, Inc.
https://www.TradeStationWorld.com
WEALTH-LAB: BROWNIAN MODEL STRATEGY
We created a ChartScript based on the alpha indicator described in "Harnessing The (Mis)Behavior Of Markets" by Rick Martinelli in this issue. The alpha indicator is now part of the Wealth-Lab Code Library. Please note that the indicator accepts two parameters: the number of periods to determine the standard deviation, and the number of periods to calculate the forecast value.
As described in the article, the system compares the alpha value with the alpha cutoff. This constant is defined in the second line of the system. If the alpha value is higher than its cutoff, the variable A becomes 1 and a long order is generated. If the alpha value is lower than the negative cutoff value, a short order is generated. The system always exits the next day on the close. As an optimal cutoff for General Motors (GM), we used 1.04, the same value mentioned in Martinelli's article.
Figure 2: Wealth-Lab, alpha indicator. The upper pane shows the alpha indicator with two red horizontal lines indicating the cutoff value. In the lower pane, we see General Motors trading with volatility. As soon as the alpha indicator reaches the upper cutoff, a long signal is generated, and vice versa with the lower cutoff. From the five trades seen here from June to August 2005, four are profitable and only the last one is unprofitable.
WealthScript code:
{$I 'Alpha'} const C = 1.04; //Alpha Cutoff; to be optimized var Bar, A, Alpha1, AlphaPane: integer; //Graphics AlphaPane := CreatePane( 100, true, true ); Alpha1 := AlphaSeries(#Close, 7, 3 ); PlotSeriesLabel(Alpha1, AlphaPane, #blue, #thickhist, 'Alpha(#Close, 7, 3)' ); DrawHorzLine( C, AlphaPane, #red, #solid ); DrawHorzLine( C*(-1), AlphaPane, #red, #solid ); //Set A according to the Alpha Cutoff "C" for Bar := 7 to BarCount - 1 do begin If @Alpha1[ Bar ] > C then A := 1 else If @Alpha1[ Bar ] < C*(-1) then A:= -1 else A := 0; //Trading rules depending on A If not LastPositionActive then begin If A = 1 then BuyAtMarket( Bar + 1, 'Long entry' ); If A =-1 then ShortAtMarket( Bar + 1, 'Short entry' ); end else SellAtClose( Bar + 1, LastPosition, 'Exit on Close' ); end;
--José Cruset
https://www.wealth-lab.com
AMIBROKER: BROWNIAN MODEL STRATEGY
In "Harnessing The (Mis)Behavior Of Markets," Rick Martinelli presents properties of a system based on linear prediction of price data movement. The idea behind it is to trade whenever the predicted price change is greater than the standard deviation of the last movement.
The prediction method uses simple linear regression forecasting. Implementing the required calculations in AmiBroker Formula Language (AFL) is straightforward. Ready-to-use formulas for AmiBroker are shown here. The code can be used in backtesting, optimization, and exploration modes as well as an indicator.
AmiBroker code: // calculate PP (predicted price) using // linear regression (time series) forecast PP = TSF( Close, 3 ); // Predicted price change is: PPC = PP - Close; // calculate alpha alpha = PPC / StDev( Close, 7 ); // alpha cut-off (AC) is the parameter AC = Param("AlphaCutoff", 1, 1, 4, 0.01 ); // that we will optimize as well... AC = Optimize( "AlphaCutoff", AC, 1, 4, 0.01 ); // buy & short rules Buy = alpha > AC; Short = alpha < -AC; Cover = Sell = False; // exit one day after ApplyStop( stopTypeNBar, stopModeBars, 1, False ); // exit after one bar // set backtest settings according to article SetOption("CommissionAmount", 0 ); SetOption("MinShares", 0 ); SetOption("MinPosValue", 0 ); SetTradeDelays( 0, 0, 0, 0 ); RoundLotSize = 0; PositionSize = 1; // calculate equity line // this will be our Fortune Line indicator e = Equity() - GetOption("InitialEquity"); Plot( e, "FortuneLine", colorRed ); // Plot(alpha,"Alpha", colorBlue, styleHistogram | styleOwnScale, -2, 2 ); Filter=Status("lastbarintest"); AddColumn( Highest( e ), "MaxF" ); AddColumn( e, "LDF" );
This code is available in the members' zone of AmiBroker's website at www.amibroker.com/members/ and also at the STOCKS & COMMODITIES website at www.Traders.com.--Tomasz Janeczko, AmiBroker.com
www.amibroker.com
eSIGNAL: BROWNIAN MODEL STRATEGY
For Rick Martinelli's article in this issue, "Harnessing The (Mis)Behavior Of Markets," we have provided the following formulas: BrownianMotion.efs, Fortune.efs, TradingSystem.efs and WinLossRatio.efs. Each study has formula parameters that may be configured through the Edit Studies option in the Advanced Chart.
The Brownian motion study has parameters for the standard deviation periods and the number of periods for the mean of the price changes. The fortune study has one parameter to set the starting account value. The trading system and win/loss ratio studies have one parameter to set the alpha cutoff value, which is set to a default of 1.
The author performed an optimization routine using Excel to find an optimized value for this cutoff. That functionality does not currently exist in eSignal Formula Language; thus, the cutoff value will need to be manually adjusted.
To discuss these studies or download complete copies of the formulas, please visit the EFS Library Discussion Board forum under the Bulletin Boards link at https://www.esignalcentral.com. The eSignal formula scripts (EFS) are also available for copying and pasting from the STOCKS & COMMODITIES website at https://www.Traders.com.
Figure 3: eSignal, Martinelli system. Here is a demonstration of the system on General Motors.
--Jason Keck
eSignal, a division of Interactive Data Corp.
800 815-8256, www.esignalcentral.com
AIQ: BROWNIAN MODEL STRATEGY
In Figure 11 of the article "Harnessing The (Mis)Behavior Of Markets," author Rick Martinelli presents the results for a group of stocks that apply the trading system described in the article.
AIQ is very well-suited for testing portfolios of stocks. Using the same 26 stocks listed in Figure 11, I performed a variety of portfolio-level tests. The tests disclosed by the author in Figure 11 represent in-sample optimizations on a stock-by-stock basis. The in-sample periods used by the author mostly cover the year 2005. Consequently, I used 2005 as the in-sample test period. The author's method of optimization causes each stock to use a different parameter for the alpha cutoff. Generally, my preference is to use the same parameter to trade all stocks in the portfolio, because separate parameters for each stock can lead to an overly optimized situation that will not perform well in out-of-sample tests.
I used AIQ's EDS backtesting module to run an in-sample test (year 2005) and three out-of-sample tests, walking backwards one year at a time. The results of these tests are shown in Table 1. The in-sample performance is quite good with the average profit per trade of 0.51%, a reward-to-risk ratio of 1.96, and an annualized return on 198 trades of 137%.
I also ran years 2004, 2003, and 2002 separately using the same individually optimized parameters. For these years, the results are not consistent with the in-sample period, indicating overoptimization of parameters. I then optimized for the best single setting that showed some robustness and generated a reasonable number of trades per year (alpha cutoff = 1.25).
The results of this test are shown in Table 2. Although the in-sample period's returns (Table 2) are less than that of the individually optimized returns (Table 1), the out-of-sample results are more consistent with the in-sample results, and all of the out-of-sample results are better (Table 2) than the out-of-sample results of the first test (Table 1).
The results of these tests support my belief that the same parameter set should be used for all stocks in the portfolio.
The AIQ code for Martinelli's system can be downloaded from the AIQ website at https://www.aiqsystems.com/S&C1.htm.
TABLE 1: Comparison of in-sample and out-of-sample periods
Each stock uses a separately optimized cutoff
Description Long trades Short trades Combined In- or out-of-sample IN IN IN Start date 01/04/05 01/04/05 01/04/05 End date 12/30/05 12/30/05 12/30/05 No. of trades 125 73 198 Average % profit 0.54% 0.45% 0.51% Average SPX % profit 0.06% -0.01% 0.03% Annual ROI 148% 119% 137% Reward/Risk 2.06 1.80 1.96 In or out-of-sample OUT OUT OUT Start date 01/02/04 01/02/04 01/02/04 End date 12/31/04 12/31/04 12/31/04 No. of trades 90 99 189 Average % profit 0.00% 0.31% 0.16% Average SPX % profit -0.04% 0.06% 0.01% Annual ROI -1.3% 1.6% 0.21% Reward/Risk 0.99 1.56 1.29 In or out-of-sample OUT OUT OUT Start date 01/02/03 01/02/03 01/02/03 End date 12/31/03 12/31/03 12/31/03 No. of trades 119 65 184 Average % profit 0.60% -0.36% 0.26% Average SPX % profit 0.11% -0.20% 0.00% Annual ROI 161% -80% 76% Reward/Risk 1.72 0.65 1.34 In or out-of-sample OUT OUT OUT Start date 01/02/02 01/02/02 01/02/02 End date 12/31/02 12/31/02 12/31/02 No. of trades 78 100 178 Average % profit -0.64% -0.19% -0.39% Average SPX % profit 0.29% -0.09% 0.08% Annual ROI -152% -52% -96% Reward/Risk 0.57 0.87 0.74 TABLE 2: Comparison of in-sample and out-of-sample periods
All stocks use the same cutoff = 1.25
Description Long trades Short trades Combined In- or out-of-sample IN IN IN Start date 01/04/05
01/04/05
01/04/05
End date 12/30/05
12/30/05
12/30/05
No. of trades 61 102 163 Average % profit 0.60%
0.32%
0.42%
Average SPX % profit 0.01%
0.05%
0.04%
Annual ROI 149%
83%
108%
Reward/Risk 1.98 1.58 1.73 In or out-of-sample OUT OUT OUT Start date 01/02/04
01/02/04
01/02/04
End date 12/31/04
12/31/04
12/31/04
No. of trades 70 64 134 Average % profit 0.23%
0.42%
0.32%
Average SPX % profit -0.13%
0.14%
0.00%
Annual ROI 63%
100%
81%
Reward/Risk 1.47 1.78 1.62 In or out-of-sample OUT OUT OUT Start date 01/02/03
01/02/03
01/02/03
End date 12/31/03
12/31/03
12/31/03
No. of trades 95 46 141 Average % profit 0.85%
-0.10%
0.54%
Average SPX % profit 0.14%
-0.27%
0.01%
Annual ROI 228%
-21%
147%
Reward/Risk 2.03 0.88 1.65 In or out-of-sample OUT OUT OUT Start date 01/02/02
01/02/02
01/02/02
End date 12/31/02
12/31/02
12/31/02
No. of trades 52 76 128 Average % profit -0.34%
-0.15%
-0.23%
Average SPX % profit 0.08%
-0.20%
-0.09%
Annual ROI -83%
-39%
-57%
Reward/Risk 0.73 0.90 0.83 --Richard DenningGO BACK
AIQ Systems
richard.denning@earthlink.net
https://www.aiqsystems.com
NEUROSHELL TRADER: BROWNIAN MODEL STRATEGY
The trading system described in "Harnessing The (Mis)Behavior Of Markets" by Rick Martinelli in this issue can be easily implemented in NeuroShell Trader by combining a few of NeuroShell Trader's 800+ indicators. To recreate the trading system, select "New Trading Strategy ..." from the "Insert" menu and enter the following entry and exit conditions in the appropriate locations of the Trading Strategy Wizard:
Generate a buy long MARKET order if ALL of the following are true: A>B ( Divide ( LinTimeReg PredChange(Close,3,1), StndDev(Momentum(Close,1),7) ), 1.04 ) Generate a sell long MARKET CLOSE order if ALL of the following are true: A=B ( Close, Close ) Generate a sell short MARKET order if ALL of the following are true: A<B ( Divide ( LinTimeReg PredChange(Close,3,1), StndDev(Momentum(Close,1),7) ), -1.04 ) Generate a cover short MARKET CLOSE order if ALL of the following are true: A=B ( Close, Close )
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 trading system.
Figure 4: NeuroShell, alpha indicator. This NeuroShell Trader chart displays the trading signals generated by Rick Martinelli's alpha indicator.
--Marge Sherald, Ward Systems Group, Inc.
301 662-7950, sales@wardsystems.com
https://www.neuroshell.com
NEOTICKER: BROWNIAN MODEL STRATEGY
To implement the ideas presented by Rick Martinelli in "Harnessing The (Mis)Behavior Of Markets," we will build an indicator for alpha (Listing 1). This indicator accepts three parameters. The first parameter is an integer for the lookback period for price projection generation. The second parameter is an integer for the number of periods projected into the future. The third parameter is the number of periods that the standard deviation is based on.
Next, we'll use this alpha indicator to create trading signals. Using the power indicator Backtest EZ, enter the following long/short signal formulas (Listing 2) into the long entry and short entry fields. We choose to use Backtest EZ because there is no specific long and short exit rule provided in the article, and Backtest EZ will treat the system as stop and reverse by default. Exit rules can be easily added at the Backtest EZ parameter tab. Backtest EZ will plot an equity curve on a chart that shows the current system equity (Figure 5).
Figure 5: NeoTicker, alpha indicator. Backtest EZ will plot an equity curve on a chart that shows the current system equity.LISTING 1: plot1 := (linreg(c, param1, param2)-c)/stddev(mo(c,1), param3); LISTING 2: Long Entry: TASC_ALPHA(data1, 3, 1, 7)> 1.04 Short Entry: TASC_ALPHA(data1, 3, 1, 7)< -1.04
A downloadable version of this code will be available at NeoTicker blog site (https://blog.neoticker.com).
--Kenneth Yuen
TickQuest Inc.
https://www.tickquest.com
TRADING SOLUTIONS: BROWNIAN MODEL STRATEGY
In "Harnessing The (Mis)Behavior Of Markets," Rick Martinelli introduces a trading algorithm based on forecasted changes relative to the standard deviation.
This algorithm can be entered into TradingSolutions as described here. These functions are also available as a function file that can be downloaded from the TradingSolutions website (www.tradingsolutions.com) in the Solution Library section.
The inputs to the entry/exit system can be optimized based on profit, Sharpe ratio, or other values. This includes not only the alpha cutoff, but the lookback periods as well. To emulate the original behavior of betting individual days, the system exits on any day that does not generate an entry signal.Function Name: Forecast Short Name: Forecast Inputs: Data, Period, Bars In Future Add (Intercept (Data, Period), Mult (Slope (Data, Period), Add (Bar# (), Bars In Future))) Function Name: Martinelli Alpha Short Name: MAlpha Inputs: Data, Forecast Lookback Period, Standard Deviation Period Div (Sub(Forecast(Data, Forecast Lookback Period, 1), Data), StDev(Data,Standard Deviation Period)) Entry/Exit System Name: Martinelli System Inputs: Data, Forecast Lookback Period, Standard Deviation Period, Alpha Cutoff Enter Long: GT (MAlpha (Data, Forecast Lookback Period, Standard Deviation Period), Alpha Cutoff) Enter Short: LT(MAlpha(Data,Forecast Lookback Period,Standard Deviation Period),Negate (AlphaCutoff)) Exit Long: System_IsLong( ) Exit Short: System_IsShort( )
--Gary Geniesse , NeuroDimension, Inc.
800 634-3327, 352 377-5144
https://www.tradingsolutions.com
BIOCOMP DAKOTA: BROWNIAN MODEL STRATEGY
In "Harnessing The (Mis)Behavior Of Markets," Rick Martinelli creates a trading system based on his fortune indicator. You can easily create a swarm of adaptive fortune indicator trading systems in BioComp Dakota, enabling you to trade using multiple fortune indicator systems that collaborate to seek higher equity performance as you walk forward through time, and achieve higher performance than Martinelli's "optimal."
Dakota's VB Script code for Martinelli's trading system is rather simple:
Running a swarm of 25 of these trading "bots" on GM during a similar period as the author uses, we achieve 52% winning trades, where winners beat losers by 2 to 1. We gain $25 per share where GM loses about $24.60, all while being in the market only 48% of the time -- a nice gain-to-exposure ratio. As we see in the screenshot in Figure 6, once the swarm gets up to speed, it generates a nice straight equity curve.Function Script_CreateSignal(Prices()) Dim Signal Dim TomorrowsPrice Dim Sigma Dim Alpha Dim LookBackPeriod Dim AlphaCutOff Dim TodaysPrice TodaysPrice = Prices(2) LookBackPeriod = ParameterValue(1) '<== Adaptive Lookback AlphaCutOff = ParameterValue(2) '<== Adaptive Alpha Cutoff PriceCtr = PriceCtr + 1 Redim Preserve PriceHistory(PriceCtr) PriceHistory(PriceCtr) = TodaysPrice Sigma = Dakota.StdDev(PriceHistory, LookBackPeriod) Dakota.PolynomialRegression 2, LookBackPeriod, PriceHistory '<= 2nd Order Forecast TomorrowsPrice = Dakota.PolyEstimate(PriceCtr+1) if Sigma <> 0 then Alpha = (TomorrowsPrice - TodaysPrice)/Sigma End if if Alpha > AlphaCutOff then Signal = 1 Elseif Alpha < -AlphaCutOff then Signal = -1 End if Script_CreateSignal = Signal End FunctionDakota users can download this bot from the Downloads page of the private BioComp Dakota website at www.biocompsystems.com/products/Dakota/.
Figure 6: BioComp Dakota, fortune indicator. Here is a sample chart showing price, signal, and equity curve for a swarm of fortune indicator bots on GM.
--Carl Cook
BioComp Systems, Inc.
952 746-5761
https://www.biocompsystems.com
FINANCIAL DATA CALCULATOR: BROWNIAN MODEL STRATEGY
The article "Harnessing The (Mis)Behavior Of Markets" by Rick Martinelli computes one-day buy or sell (or exit) signals using a quantity he calls alpha, and a cutoff threshold for values of alpha. The following macro, "alphasignal," for FDC will compute on each day a 1 for "buy on close," a -1 for "sell on close," or a zero to do nothing. It takes as a parameter the cutoff value C.
For "alphasignal," open the macro wizard, choose "New macro," and copy the following code into the definition window:
This macro is used, for example, as: 1.04 alphasignal GM (for General Motors).price: cl #r C: #l changeestimate: (3 1 movtrend price) - price alpha: changeestimate/(7 movstdv change price) (alpha > C) - (alpha < -C)
--Robert C. BusbyGO BACK
Mathematical Investment Decisions, Inc.
856 857-9088
rbusby@mathinvestdecisions.com
https://www.financialdatacalculator.com
MULTICHARTS: BROWNIAN MODEL STRATEGY
Rick Martinelli's article "Harnessing The (Mis)Behavior Of Markets" describes a thought-provoking approach to price movement analysis that is based on predicting future market values relative to their past values. The author suggests that price changes according to the Brownian model and forecasts its future values using the mathematical methods of linear regression and standard deviation.
Although the idea is very original, Martinelli doesn't reveal all his secrets and many issues remain open. That's why we bring to your attention a simplified reversal strategy with a single input, and we offer you the opportunity to discuss possible ways for improving this method on our user forum at https://forum.tssupport.com.
inputs: AlphaCutoff(1); var: Alpha(0); if StdDev(close - close[1], 7) <> 0 then Alpha = (LinearRegValue(close, 3, -1) - close) / StdDev(close - close[1], 7) else Alpha = Alpha[1]; if Alpha > AlphaCutoff then buy next bar at market; if Alpha < - AlphaCutoff then sell short next bar at market;
A sample chart is shown in Figure 7.
Figure 7: Multicharts, Brownian model indicator. Here is a sample chart of Apple Computer (AAPL) demonstrating the Brownian model indicator in the bottom pane and the system buy and sell signals in the chart pane.--Stanley MillerGO BACK
TS SUPPORT, LLC
https://www.tssupport.com
TRADECISION: BROWNIAN MODEL STRATEGY
In "Harnessing The (Mis)Behavior Of Markets," author Rick Martinelli illustrates how to develop a profitable trading strategy based on the idea that a signal occurs when the predicted price change exceeds the average of the most recent changes.
Figure 8: Tradecision, Brownian model system. Using the Tradecision Simulation Manager on a daily chart of Yahoo (YHOO), we can analyze the net profit by period for this strategy. The return on capital for the strategy is 8.95%.
The described strategy strongly depends on coefficient selection, and thus you can choose from two ways for applying the technique in Tradecision:
1. Enter thestrategy rules using the Strategy Builder. In the "Optimize strategy" dialog, select a symbol and then optimize the CoLong and CoShort parameters in a range from zero to 1, with step 0.1. After that, register the best strategy. Enter long: var al:= (LRL(C,3,0)-C) / StdDev(C,7); CoLong:=#; end_var return Al > CoLong; Enter short: var al:= (LRL(C,3,0)-C) / StdDev(C,7); CoShort:=#; end_var return Al < -CoShort; 2. Create the same strategy, but replace the optimization character "#" with coefficients. For example, for a Yhoo daily chart, this is 0.6: CoLong:=0.6; CoShort:=0.6.
--Alex Grechanowski, Alyuda Research, Inc.
alex@alyuda.com, 347 416-6083
https://www.alyuda.com
https://www.tradecision.com
TRADE NAVIGATOR: BROWNIAN MODEL STRATEGY
In Trade Navigator Gold and Platinum versions, you can create custom functions to display on the chart as indicators. Many of the functions needed to recreate Rick Martinelli's indicators presented in "Harnessing The (Mis)Behavior Of Markets" are already provided for you in Trade Navigator. Some functions depend on other functions to be written first; therefore, we recommend that you create the functions in the order shown here.
To create the indicators for "Harnessing The (Mis)Behavior Of Markets" in Trade Navigator, follow these steps:
Price Change
(1) Go to the Trader's Toolbox Functions tab.
(2) Click on the New button.
(3) Type the formula Close - Close.1 into the Function window.
(4) Click on the Verify button.
(5) Click on the Save button, type in Price Change as the name for the function and then click the Ok button.Forecasting Function
(1) Go to the Trader's Toolbox Functions tab.
(2) Click on the New button.
(3) Type the formula Regression Value (Price Change , Forecast Lag , (Forecast lag + 1) * -1) into the Function window. (FIGURE 9).
(4) Click on the Verify button.
(5) An Add Inputs window will pop up saying that Forecast Lag is unrecognized, Click the Add button and change the Default Value to 3.
(6) Click on the Save button, type in Forecasting Function as the name for the function and then click the Ok button.std Dev Price Change
(1) Go to the Trader's Toolbox Functions tab.
(2) Click on the New button.
(3) Type the formula MovingAvgX (High , 13) + 2 * Avg True Range (10) into the Function window.
(4) Click on the Verify button.
(5) An Add Inputs window will pop up saying that Number Bars is unrecognized, Click the Add button and change the Default Value to 7.
(6) Click on the Save button, type in std Dev Price Change as the name for the function and then click the Ok button.Estimated Price Change
(1) Go to the Edit menu and click on Functions. This will bring up the Trader's Toolbox already set to the Functions tab.
(2) Click on the New button.
(3) Type the formula Forecasting Function (forecast lag) - Price Change into the Function window.
(4) Click on the Verify button.
(5) An Add Inputs window will pop up saying that forecast lag is unrecognized, Click the Add button and change the Default Value to 3.
(6) Click on the Save button, type in Estimated Price Change as the name for the function and then click the Ok button.Alpha
(1) Go to the Trader's Toolbox Functions tab.
(2) Click on the New button.
(3) Type the formula Estimated Price Change (forecast lag) / std Dev Price Change (number bars) into the Function window.
(4) Click on the Verify button.
(5) An Add Inputs window will pop up saying that forecast lag and number bars are unrecognized, Click the Add button and change the Default Value for forecast lag to 3 and the Default Value for number bars to 7.
(6) Click on the Save button, type in Alpha as the name for the function and then click the Ok button.To add your new indicators your chart:
(1) Click on the chart to be sure that it is the active window.
(2) Type the letter A.
(3) Click on the Indicators tab to add an indicator.
(4) Double click on the name of the indicator or highlight bar you wish to add.If you desire to change the values to use for the alpha indicator, simply click on the chart that you have added it to, type the letter "E" on your keyboard, select the indicator from the list, click the Value field next to number bars or forecast lag on the right side of the window and type the new value to use.
FIGURE 9: TRADE NAVIGATOR, BROWNIAN MODEL INDICATOR. Enter the formula in the Trader's Toolbox Function tab.Genesis Financial Technologies has created a special file that users can download through Trade Navigator that will add the Martinelli indicators to Trade Navigator for you. Simply download the free special file "scjune06" from within Trade Navigator and follow the upgrade prompts.
--Michael Herman
Genesis Financial Technologies
https://www.GenesisFT.com
VT TRADER: BROWNIAN MODEL STRATEGY
Rick Martinelli's article in this issue, "Harnessing the (Mis)Behavior Of The Markets," discusses the relevancy of the Brownian model as it applies to financial markets. Martinelli attempts to take advantage of situations when market prices violate one or more of the critical assumptions made within the Brownian model by looking for correlations between current price movements and previous price movements using a linear predictor and statistical data.
We'll be offering a trading system based on Martinelli's algorithm for download in our user forums. The VT Trader code and instructions for creating the trading system is as follows (each input variable has been parameterized to allow customization):
1. Navigator Window>Tools>Trading Systems Builder>[New] button 2. In the Indicator Bookmark, type the following text for each field: Name: Harnessing the (Mis)Behavior of the Markets Short Name: vt_HMBM Label Mask: Harnessing the (Mis)Behavior of the Markets (%price%, %TSFP%, %StDevP%, %_C%) 3. In the Input Bookmark, create the following variables: [New] button... Name: _Spread , Display Name: Currency Spread (In Pips) , Type: float , Default: 0.0003 [New] button... Name: Price , Display Name: Price Type , Type: price , Default: close [New] button... Name: TSFP , Display Name: Alpha Forecast Lag Periods , Type: integer , Default: 3 [New] button... Name: StDevP , Display Name: Alpha StDev Periods , Type: integer , Default: 7 [New] button... Name: _C , Display Name: Alpha CutOff Value , Type: float , Default: 1.2500 4. In the Formula Bookmark, copy and paste the following formula: {Provided By: Visual Trading Systems, LLC (c) Copyright 2006} {Description: Harnessing the (Mis)Behavior of the Markets - Trading System} {Notes: June 2006 Issue - Harnessing the (Mis)Behavior of the Markets by Rick Martinelli} {vt_HMBM Version 1.0} {Time Series Forecast} {TSF predicts next bar's value and plots the prediction on the current bar} _TSF:= linreg(Price,TSFP) + linregslope(Price,TSFP); {Alpha Calculation} PriceChange:= Price - ref(Price,-1); PredictedChange:= _TSF - Price; Alpha:= (_TSF - Price) / stdev(PriceChange,StDevP); CutOff:= _C; {Fortune Indicator} An:= if(Alpha>CutOff,1,if(Alpha<-CutOff,-1,0)); Sum_AnWn:= if(Ref(An,-1)*PriceChange,prev+(Ref(An,-1)*PriceChange),prev); Fortune:= Sum_AnWn/ref(Price,-1); {Basic Entry Conditions for Trades} A_Long:= Alpha > CutOff; A_Long_Exit:= not A_Long; A_Short:= Alpha < -CutOff; A_Short_Exit:= not A_Short; {Enter Long at the close of any bar when Alpha > CutOff} LongEntrySignal:= (LongTrade=0 and ShortTrade=0 and A_Long) or (LongTrade=0 and cross(0.5,ShortTrade) and A_Short); {Exit Long at the close of the next bar following Long entry when Alpha < CutOff} LongExitSignal:= LongTrade=1 and A_Long_Exit; {Enter Short at the close of any bar when Alpha < -CutOff} ShortEntrySignal:= (ShortTrade=0 and LongTrade=0 and A_Short) or (ShortTrade=0 and cross(0.5,LongTrade) and A_Short); {Exit Short at the close of the next bar following Short entry when Alpha > -CutOff} ShortExitSignal:= ShortTrade=1 and A_Short_Exit; {Determine Trade Direction and Condition} LongTrade:= if(LongEntrySignal,1,if(LongExitSignal,0,prev)); ShortTrade:= if(ShortEntrySignal,1,if(ShortExitSignal,0,prev)); {Automated Trading Actions} OpenBuy:= LongEntrySignal and (eventCount('OpenBuy') = eventCount('CloseBuy')); CloseBuy:= LongExitSignal and (eventCount('OpenBuy') > eventCount('CloseBuy')); OpenSell:= ShortEntrySignal and (eventCount('OpenSell') = eventCount('CloseSell')); CloseSell:= ShortExitSignal and (eventCount('OpenSell') > eventCount('CloseSell')); {Determine Trade Entry and Exit Prices} LongEntryPrice:= valuewhen(1,LongEntrySignal,C); LongExitPrice:= valuewhen(1,LongExitSignal,C); ShortEntryPrice:= valuewhen(1,ShortEntrySignal,C); ShortExitPrice:= valuewhen(1,ShortExitSignal,C); {Calculate Simulated NET Profit/Loss In Pips For Each Trade; Assumes the user is viewing a BID chart of currency prices} TradeProfitInPips:= If(LongExitSignal=1,LongExitPrice - (LongEntryPrice + _Spread), If(ShortExitSignal=1,ShortEntryPrice - (ShortExitPrice + _Spread), 0)); {Calculate Simulated NET Profit/Loss Total In Pips For All Trades} TotalProfitInPips:= cum(TradeProfitInPips); {Calculate Number of Trades and Win/Loss Ratio} LosingTrades:= cum(If(TradeProfitInPips < 0,1,0)); WinningTrades:= cum(If(TradeProfitInPips > 0,1,0)); BreakEvenTrades:= if((LongExitSignal=1 or ShortExitSignal=1) and TradeProfitInPips=0, PREV+1, PREV); TotalTrades:= cum(LongExitSignal) + cum(ShortExitSignal); WLRatio:= WinningTrades / TotalTrades; 5. In the Output Bookmark, create the following variables: [New] button... Var Name: _TSF Name: Predicted Forecast Price Description: Predicted Forecast Price * Checkmark: Indicator Output Select Indicator Output Bookmark Color: dark green Line Width: slightly thicker Line Style: solid Placement: Price Frame [OK] button... [New] button... Var Name: Alpha Name: Alpha Description: Alpha * Checkmark: Indicator Output Select Indicator Output Bookmark Color: dark pink Line Width: slightly thicker Line Style: histgram Placement: Additional Frame 1 [OK] button... [New] button... Var Name: Fortune Name: Fortune Description: Fortune Indicator * Checkmark: Indicator Output Select Indicator Output Bookmark Color: dark blue Line Width: slightly thicker Line Style: solid line Placement: Additional Frame 2 [OK] button... [New] button... Var Name: LongEntrySignal Name: LongEntrySignal Description: Long Entry Signal Alert * Checkmark: Graphic Enabled * Checkmark: Alerts Enabled Select Graphic Bookmark Font [É]: Up Arrow Size: Medium Color: Blue Symbol Position: Below price plot Select Alerts Bookmark Alerts Message: Long Entry Signal! Choose sound for audible alert [OK] button... [New] button... Var Name: LongExitSignal Name: LongExitSignal Description: Long Exit Signal Alert * Checkmark: Graphic Enabled * Checkmark: Alerts Enabled Select Graphic Bookmark Font [É]: Exit Sign Size: Medium Color: Blue Symbol Position: Above price plot Select Alerts Bookmark Alerts Message: Long Exit Signal! Choose sound for audible alert [OK] button... [New] button... Var Name: ShortEntrySignal Name: ShortEntrySignal Description: Short Entry Signal Alert * Checkmark: Graphic Enabled * Checkmark: Alerts Enabled Select Graphic Bookmark Font [É]: Down Arrow Size: Medium Color: Red Symbol Position: Above price plot Select Alerts Bookmark Alerts Message: Short Entry Signal! Choose sound for audible alert [OK] button... [New] button... Var Name: ShortExitSignal Name: ShortExitSignal Description: Short Exit Signal Alert * Checkmark: Graphic Enabled * Checkmark: Alerts Enabled Select Graphic Bookmark Font [É]: Exit Sign Size: Medium Color: Red Symbol Position: Below price plot Select Alerts Bookmark Alerts Message: Short Exit Signal! Choose sound for audible alert [OK] button... [New] button... Var Name: WLRatio Name: Win/Loss Ratio Description: Win/Loss Ratio * Checkmark: Indicator Output Select Indicator Output Bookmark Color: burgundy Line Width: thin Line Style: solid line Placement: Additional Frame 4 [OK] button... [New] button... Var Name: TotalProfitInPips Name: Total Profit In Pips Description: Total Profit In Pips * Checkmark: Indicator Output Select Indicator Output Bookmark Color: light blue Line Width: slightly thicker Line Style: solid line Placement: Additional Frame 5 [OK] button... [New] button... Var Name: OpenBuy Name: OpenBuy Description: Automated Open Buy Trade Command * Checkmark: Trading Enabled Select Trading Bookmark Trade Action: Buy Traders Range: 5 Hedge: no checkmark EachTick Count: 1 [OK] button... [New] button... Var Name: CloseBuy Name: CloseBuy Description: Automated Close Buy Trade Command * Checkmark: Trading Enabled Select Trading Bookmark Trade Action: Sell Traders Range: 5 Hedge: no checkmark EachTick Count: 1 [OK] button... [New] button... Var Name: OpenSell Name: OpenSell Description: Automated Open Sell Trade Command * Checkmark: Trading Enabled Select Trading Bookmark Trade Action: Sell Traders Range: 5 Hedge: no checkmark EachTick Count: 1 [OK] button... [New] button... Var Name: CloseSell Name: CloseSell Description: Automated Close Sell Trade Command * Checkmark: Trading Enabled Select Trading Bookmark Trade Action: Buy Traders Range: 5 Hedge: no checkmark EachTick Count: 1 [OK] button... 6. Click the "Save" icon to finish building the HMBM trading system.
To attach the HMBM trading system to a chart right-click with the mouse within the chart window, select "Add Trading System" -> "Harnessing the (Mis)Behavior of the Markets" from the list. Users will have the ability to customize the parameters at this time. Once attached to the chart the parameters can be customized by right-clicking with the mouse over the displayed trading system label and selecting "Edit Trading Systems Properties." A sample chart of Martinelli's system is shown in Figure 10.To download CMS Forex's free VT Trader software, please visit https://www.cmsfx.com/en/platform/download.
Figure 10: VT Trader, alpha, fortune, win/loss ratio, and net P/L indicators. Here is a sample UR/USD daily candlestick chart with the HMBM trading system. Long and short trade entries and exits are shown on the chart as arrow and exit-sign graphics.
--Chris Skidmore & Vadim Sologubov
Visual Trading Systems, LLC (courtesy of CMS Forex)
866 51-CMSFX, trading@cmsfx.com
https://www.cmsfx.com
GO BACK
Return to June 2006 Contents
Originally published in the June 2006 issue of Technical Analysis of STOCKS & COMMODITIES magazine.
All rights reserved. © Copyright 2006, Technical Analysis, Inc.