- Joined
- 24 October 2005
- Posts
- 1,302
- Reactions
- 834
I'm not sure if it's causing issues with the TT code but it's good practice not to use it unless necessary as I've seen problems occur with some code.Generally speaking you don't need to use ExRem at all, because the backtester handles signals even if there are redundant ones.
The Amibroker backtest report includes both closed and open trades so it's not an issue.
I'd also remove the exrem statements from the backtest version as the backtester handles trade processing and it's incorrect to use exrem in a backtest. TJ has posted about this issue, I'll see if I can dig it up.
Thanks Capt.
I removed the exrem but left the binary flip
OK I will look at position score. Its a learning experience for me so thank you for bring that up
Were my other backtest settings ok?
Results are better
Annual Return 18.71%
Max Sys DD 37%
61 Trade 3.77% Win
Exp 85.04%
Thank you
Thanks Capt
"Personally I set bar delay to 1 and buy at tomorrows open"
Thats what Im doing here too. Buy & Sell on open the following day. Do I still have to set positionsize to previous bar equity.
http://www.amibroker.com/guide/w_settings.htmlUse previous bar equity for position sizing
Affects how percent of current equity position sizing is performed.
Unchecked (default value) means: use current (intraday) equity to perform position sizing, checked means: use previous bar closing equity to perform position sizing.
I calculate my position sizing from closing equity the day before so I have that option set to true in my formulas.
Here's how it's calculated:
http://www.amibroker.com/guide/w_settings.html
I added this to the afl.
SetOption("UsePrevBarEquityForPosSizing", True ); // Use last known bar of position sizing
Limit trade size to % of entry bar volume is set at 10
Can someone please confirm that these are correct and if possible run a backtest for me on the asx200 for the following formula for the above dates to confirm my results
_SECTION_BEGIN("AFL Example");
/*
This is an attempt to provide a basic trading system AFL. The system is purely imaginary
AND NOT provided as one that would make money. This is just to provide a guide to learners
on the common components of writing AFL.
Prepared by Graham Kavanagh 12 Aug 2005
AB Write http://e-wire.net.au/~eb_kavan/ab_write.htm
When you copy/paste ensure the existing continuous lines have not been wrapped. This wrapping
can create error signals when you try to use the code. Click on the check afl button in the
editor before trying to apply or scan.
I have used slash-asterisk /* */ /* for my comments to get around the problem of wrapping,
which could happen if you used double slash //
I hope this helps the beginners in creating AFL code
*/
/*firstly some basics common*/
SetBarsRequired(10000,10000); /* this ensures that the charts include all bars AND NOT just those on screen */
SetFormulaName("Sample System"); /*name it for backtest report identification */
SetTradeDelays( 1, 1, 1, 1 ); /* delay entry/exit by one bar */
SetOption( "initialequity", 100000 ); /* starting capital */
PositionSize = -10; /* trade size will be 10% of available equty */
SetOption( "MaxOpenPositions", 6 ); /* I don't want to comit more than 60% of Equity at any one time */
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's price range */
SetOption( "CommissionMode", 2 ); /* set commissions AND costs as $ per trade */
SetOption( "CommissionAmount", 32.95 ); /* commissions AND cost */
SetOption( "UsePrevBarEquityForPosSizing", 1 ); /*set the use of last bars equity for trade size*/
PositionScore = 100/C; /*Set the order for which stock trades when get mulitple signals in one bar in backtesting */
//Trade system
/*
Buy when exp mov avg crosses and the high is highest for 50 bars
Sell when exp mov avg crosses back
Cross is first variable moves to above the second variable
*/
LongPer = Param("Long Period", 50, 30, 100, 5 ); /* select periods with parameter window */
ShortPer = Param("Short Period", 5, 3, 10, 1 );
LongMA = EMA( C, LongPer );
ShortMA = EMA( C, ShortPer );
LastHigh = HHV( H, LongPer );
Buy = Cross( ShortMA, LongMA ) AND H > Ref( LastHigh, -1 );
/* ref,-1 is used for the high to have todays high greater than the previous 50 bar high.
To just use H==LastHigh couold mean a previous high was equal to current high */
Sell = Cross( LongMA, ShortMA );
/* exrem is one method to remove surplus strade signals*/
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
/* Now for exploration results.
Will restrict results of exploration to when the Buy AND Sell signals occur
You can use Filter=1; to display every bar result */
Filter = Buy OR Sell;
AddTextColumn( FullName(), "Company Name" );
AddColumn( Buy, "Buy", 1 );
AddColumn( Sell, "Sell", 1 );
AddColumn( C, "Close", 1.3 );
AddColumn( H, "High", 1.3 );
AddColumn( LastHigh, "HHV", 1.3 );
AddColumn( LongMA, "Long MA", 1,3 );
AddColumn( ShortMA, "Short MA", 1,3 );
/* Now to show this on a chart */
/* I use WriteVal to limit the values to the wanted number of decimal places,
seeing a value of 5 decimal places can be frustrating.
I have included additional information in the plot title sections to add some
information to the title block */
GraphXSpace = 10; /* create empty space of 10% top and bottom of chart */
Plot( C, " Close Price", colorGrey50, styleBar );
Plot( LongMA, " EMA(C,"+WriteVal(LongPer,1)+")", colorRed, styleLine|styleNoRescale );
Plot( ShortMA, " EMA(C,"+WriteVal(ShortPer,1)+")", colorGreen, styleLine|styleNoRescale );
Plot( Ref(Lasthigh,-1), " HHV(H,"+WriteVal(LongPer,1)+")", colorBlue, styleNoLine|styleDots|styleNoRescale );
/* styleNoRescale in the plots stops the added plots from compressing the original bar chart to the middle of the pane */
PlotShapes( shapeUpArrow*Buy, colorGreen, 0, L, -10 );
PlotShapes( shapeDownArrow*Sell, colorRed, 0, H, -10 );
Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+_DEFAULT_NAME()+" Chart values : {{VALUES}} ";
/* _DEFAULT_NAME() shows the section name or, if not present, the file name
the items in {{}} are short cuts for the title block. It can be done long hand
Title = Name() +" "+ Date() +" "+ "{{INTERVAL}}"+_DEFAULT_NAME()+" Chart values : " +
" Close Price = " + C +
" EMA(C,"+WriteVal(LongPer,1)+") = "+WriteVal(LongMA,1.3) +
" EMA(C,"+WriteVal(ShortPer,1)+") = "+WriteVal(ShortMA,1.3) +
" HHV(H,"+WriteVal(LongPer,1)+") = "+WriteVal(Ref(LastHigh,-1),1.3) ;
*/
_SECTION_END();
Was this the system Template?
Im not sure what this means
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's price range */
Im not sure what this means
SetOption( "PriceBoundChecking", 1 ); /* trade only within the chart bar's price range */
//--------------------------------------------------------------------------------------------------
//
// BoilerPlate - Version 2
// - BruceR
// - updated - 10/1/08 - cleanup and added more comments
//
// The purpose of this include file is to initialize all backtesting/optimization "factors"
// to a default value. It also serves as a reference check to make sure that all of the
// factors have been accounted for.
//
// These factors fall into 3 categories -
//
// 1. Factors that are in the AA Backtester Settings
// 2. Factors that are NOT in Settings
// 3. Factors that in Settings but can NOT be set programmatically
//
// SO, the bottom line is that there is not a way to guarantee in one place that all
// factors are accounted for. Theoretically, to cover all options, a Settings file AND
// AFL settings should be used.
//
// Experience has also shown that users are reluctant to utilize a distributed Settings file.
// The best trade-off seems to be to set as many as possible programmatically, and to check
// the ones that can only be set in settings.
//
//--------------------------------------------------------------------------------------------------
// Initialize the trading parameters
//EnableRotationalTrading();
BuyPrice = SellPrice = ShortPrice = CoverPrice = Open;
SetTradeDelays( 1, 1, 1, 1 );
//SetFormulaName( "TEST" );
SetOption( "InitialEquity", 1000 );
SetOption( "MinShares", 0.0001 );
SetOption( "MinPosValue", 0 );
SetOption( "FuturesMode", False );
SetOption( "AllowPositionShrinking", True );
SetOption( "ActivateStopsImmediately", False );
SetOption( "ReverseSignalForcesExit", True );
SetOption( "AllowSameBarExit", True );
SetOption( "CommissionMode", 2 );
SetOption( "CommissionAmount", 0 );
SetOption( "InterestRate", 0 );
SetOption( "MarginRequirement", 100 );
SetOption( "PortfolioReportMode", 0 );
SetOption( "MaxOpenPositions", 1 );
SetOption( "WorstRankHeld", 1 ); // Not in settings
SetOption( "PriceBoundChecking", False ); // Not in settings
SetOption( "UsePrevBarEquityForPosSizing", True );
SetOption( "UseCustomBacktestProc", False );
SetOption( "DisableRuinStop", False ); // Not in settings
SetOption( "EveryBarNullCheck", False ); // Not in settings
SetOption( "HoldMinBars", 0 ); // Not in settings
SetOption( "HoldMinDays", 0 ); // Not in settings
SetOption( "EarlyExitBars", 0 ); // Not in settings
SetOption( "EarlyExitDays", 0 ); // Not in settings
SetOption( "EarlyExitFee", 0 ); // Not in settings
SetOption( "SeparateLongShortRank", False ); // Not in settings
SetOption( "MaxOpenLong", 0 ); // Not in settings
SetOption( "MaxOpenShort", 0 ); // Not in settings
MaxPos = 100 * 100 / GetOption("MarginRequirement");
PositionSize = -MaxPos / GetOption("MaxOpenPositions");
RoundLotSize = 0; // 0 for Funds, 100 for Stocks
TickSize = 0; // 0 for no min. size
MarginDeposit = 0;
PointValue = 1; // For futures
ExitAtTradePrice = 0;
ExitAtStop = 1;
ExitNextBar = 2;
ReEntryDelay = 0;
ApplyStop( stopTypeLoss, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeProfit, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeTrailing, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeNBar, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
// THE FOLLOWING CANNOT BE SET PROGRAMMATICALLY AND SHOULD BE CHECKED
// Pad and align
// Reference symbol
// Risk-free rate Sharpe
// Risk-free rate UPI
// Add artificial future bar
// Limit trade size %
// Disable trade size limit
// Walk forward mode and data parameters
// Optimization target
//--------------------------------------------------------------------------------------------------
// ALL CUSTOM SETTING SHOULD BE DONE AFTER THIS
This is a SetOption template by Bruce Robinson and it can be found at amibrokeru.com (Amibroker University).
/* create AB object */
AB = new ActiveXObject("Broker.Application");
/* retrieve automatic analysis object */
AA = AB.Analysis;
/* load formula from external file */
AA.LoadFormula("C:\\Program Files\\AmiBroker\\Formulas\\Custom\\yourAFl.afl");
/* optional: load settings */
AA.LoadSettings("C:\\Program Files\\AmiBroker\\AASettings.abs");
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object
try
{
NewA = AB.AnalysisDocs.Open( "C:\\analysis1.apx" ); // opens previously saved analysis project file
// NewA represents the instance of New Analysis document/window
if ( NewA )
{
NewA.Run( 2 ); // starts analysis (asynchronous - returns immediatelly
// (0-scan, 1- exploration, 2- portfolio backtest, 3- Individual Backtest, 4- optimization, 5- Individual Optimization (not supported yet), 6-walk forward)
while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5 second
NewA.Export( "test.html" ); // export result list to HTML file
WScript.echo( "Completed" );
//NewA.Close(); // close new Analysis
}
}
catch ( err )
{
WScript.echo( "Exception: " + err.message ); // display error that may occur
}
Nice find
Thanks for posting it here.
//--------------------------------------------------------------------------------------------------
//
// BoilerPlate - Version 3
// - BruceR
// - updated - 10/1/08 - cleanup and added more comments
// - updated by trash - May 2012 - added additional comments and options
//
// The purpose of this include file is to initialize all backtesting/optimization "factors"
// to a default value. It also serves as a reference check to make sure that all of the
// factors have been accounted for.
//
// These factors fall into 3 categories -
//
// 1. Factors that are in the AA Backtester Settings
// 2. Factors that are NOT in Settings
// 3. Factors that in Settings but can NOT be set programmatically
//
// SO, the bottom line is that there is not a way to guarantee in one place that all
// factors are accounted for. Theoretically, to cover all options, a Settings file AND
// AFL settings should be used.
//
// Experience has also shown that users are reluctant to utilize a distributed Settings file.
// The best trade-off seems to be to set as many as possible programmatically, and to check
// the ones that can only be set in settings.
//
//--------------------------------------------------------------------------------------------------
// Initialize the trading parameters
//EnableRotationalTrading();
BuyPrice = SellPrice = ShortPrice = CoverPrice = Open;
SetTradeDelays( 1, 1, 1, 1 ); // SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay )
/* applies the following
Buy = Ref( Buy, -buydelay );
Sell = Ref( Sell, -selldelay );
Short = Ref( Short, -shortdelay );
Cover = Ref( Cover, -coverdelay ); */
//SetBarsRequired(sbrAll, sbrAll); // set number of previous and future bars needed, sbrAll turns OFF quickAFL and uses all bars
//SetFormulaName( "TEST" ); // Allows to programatically change the name of the formula that is displayed in the backtest result explorer.
//:::::::::::::::::::::::::::::::::::::::::::: Backtest Mode Selection :::::::::::::::::::::::::::::::::::::::::::::::::::
// default, as in 4.90, regular, signal-based backtest, redundant signals are removed
//SetBacktestMode( backtestRegular );
// signal-based backtest, redundant (raw) signals are NOT removed, only one position per symbol allowed
//SetBacktestMode( backtestRegularRaw );
// signal-based backtest, redundant (raw) signals are NOT removed,
// MULTIPLE positions per symbol will be open if BUY/SHORT signal is "true" for more than one bar and there are free funds
// Sell/Cover exit all open positions on given symbol, Scale-In/Out work on all open positions of given symbol at once.
//SetBacktestMode( backtestRegularRawMulti );
// rotational trading mode - equivalent of EnableRotationalTrading() call
//SetBacktestMode( backtestRotational );
//:::::::::::::::::::::::::::::::::::::::::::: Backtest Mode Selection :::::::::::::::::::::::::::::::::::::::::::::::::::
SetOption( "InitialEquity", 10000 );
//Setoption("AccountMargin", 100 ); // 100 = no margin for shares; 50 = for 50% margin
// NOT the same as MarginDeposit for futures.
SetOption( "MinShares", 0.0001 ); // defines minimal shares to be bought
SetOption( "MinPosValue", 0 );
SetOption( "FuturesMode", False ); // False for Shares, True for FX or for Futures of course
SetOption( "AllowPositionShrinking", True ); // in case there is not enough cash set to True
SetOption( "ActivateStopsImmediately", False ); // True if you enter at Open. False if you enter at Close
SetOption( "ReverseSignalForcesExit", True ); // True for stop and reverse systems
SetOption( "AllowSameBarExit", True );
SetOption( "CommissionMode", 2 ); // overrides SETTINGS, 0 = Commision Table; 1 = percent; 2 = $ per trade; 3 = $ per share/contract
SetOption( "CommissionAmount", 0 );
SetOption( "InterestRate", 0 );
SetOption( "MarginRequirement", 100 );
//Reports, (deactivate reports generation during optimization,
//if you don't wanna have generated reports for every optimization process because it slows it down quite a bit!)
SetOption("GenerateReport", 0 ); // force generation of full report, slow
// ( 0 ) suppress generation of report
// ( 1 ) force generation of full report
// ( 2 ) only one-line report is generated (in results.rlst file)
SetOption( "PortfolioReportMode", 0 ); // 0-Trade list, 1- Detailed Log, 2- Summary, 3- No output
//SetOption("ExtraColumnsLocation", 14 ); // define column where you wanna have custom backtester columns in AA being located
SetOption( "MaxOpenPositions", 1 ); // Must be used with PositionSize.
// only works for Portfolio level testing with > 1 symbol
SetOption( "WorstRankHeld", 1 ); // Not in settings
SetOption( "PriceBoundChecking", False ); // Not in settings, set to False if you wanna include slippage/spreads into backtesting
// because trading prices would go outside H-L range of the bar - then you can disable automatic adjustment for trading prices by setting to False.
SetOption( "UsePrevBarEquityForPosSizing", True ); // set to False if you wanna use current equity for Pos Sizing
SetOption( "UseCustomBacktestProc", False ); // allows to turn on/off custom backtest procedure
SetOption( "DisableRuinStop", False ); // Not in settings
SetOption( "EveryBarNullCheck", False ); // Not in settings
SetOption( "HoldMinBars", 0 ); // Not in settings disables exits for this number of bars
SetOption( "HoldMinDays", 0 ); // Not in settings disables exits for this number of days
SetOption( "EarlyExitBars", 0 ); // Not in settings
SetOption( "EarlyExitDays", 0 ); // Not in settings
SetOption( "EarlyExitFee", 0 ); // Not in settings
SetOption( "SeparateLongShortRank", False ); // Not in settings
SetOption( "MaxOpenLong", 0 ); // Not in settings
SetOption( "MaxOpenShort", 0 ); // Not in settings
MaxPos = 100 * 100 / GetOption("MarginRequirement");
//PositionSize = -MaxPos / GetOption("MaxOpenPositions");
SetPositionSize( MaxPos / GetOption("MaxOpenPositions"), spsPercentOfEquity);
/*
spsValue (=1) - dollar value of size (as in previous versions)
spsPercentOfEquity (=2) - size expressed as percent of portfolio-level Equity (size must be from ..100 (for regular accounts) OR .1000 for margin accounts)
spsShares (=4) - size expressed in shares/contracts (size must be > 0 )
spsPercentOfPosition (=3) - size expressed as percent of currently Open position (for SCALING IN AND SCALING OUT ONLY)
spsNoChange (=0) - don't change previously set size for given bar
New SetPositionSize function automatically encodes new methods of expressing position size into old "positionsize" variable as follows:
values below -2000 encode share count,
values between -2000 and -1000 encode % of current position
values between -1000 and 0 encode % of portfolio equity
values above 0 encode dollar value
Although it is possible to assign these values directly to old-style PositionSize variable, new code should use SetPositionSize function for clarity.
*/
RoundLotSize = 0; // As per help files use 1 for shares and futures, or use fractions ( =0 ) for mutual funds.
// Per symbol information setting overrides global values in SETTINGS GUI
// AFL overrides SETTINGS.
// 1 is needed for shares to ensure we do not buy fractional shares.
// if we want to buy shares in parcels of multiples of 10, set this 10.
// if we want to buy shares in multiples of 100, we set this 100 and so on.
// if we set this 0 (zero) backtester will buy fractions of shares.
TickSize = 0; // 0 for no min. size
// TickSize is a special case. Settings can be made Globally (in SETTINGS) or per symbol, but do not override
// the BuyPrice or SellPrice arrays. Mainly of use therefore in conjunction with Applystops to make sure
// entries and exits take place at allowed true prices and not fictitious calculated levels. If we do not use
// Applystops, we should not need to specify TickSize.
// TickSize and Forex is a another special case
MarginDeposit = 0;
PointValue = 1; // For futures & Forex
ExitAtTradePrice = 0;
ExitAtStop = 1;
ExitNextBar = 2;
ReEntryDelay = 0;
ApplyStop( stopTypeLoss, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeProfit, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeTrailing, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
ApplyStop( stopTypeNBar, stopModeDisable, 0, ExitAtTradePrice, ReEntryDelay );
// THE FOLLOWING CANNOT BE SET PROGRAMMATICALLY AND SHOULD BE CHECKED
// Pad and align
// Reference symbol
// Risk-free rate Sharpe
// Risk-free rate UPI
// Add artificial future bar
// Limit trade size %
// Disable trade size limit
// Walk forward mode and data parameters
// Optimization target
//--------------------------------------------------------------------------------------------------
// ALL CUSTOM SETTING SHOULD BE DONE AFTER THIS
//--------------------------------------------------------------------------------------------------
Thanks trash, good work
I occasionally have thoughts of starting an Amibroker resource thread as a place to post code, links, documents etc.
One day
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?