FUNCTION: BACKTEST(expression)

STUB: BACKTEST(CLOSE(i))


Function BACKTEST starts processing the rules that were defined previously inside the formula and were prefaced with the string "BACKTEST:".


The expression needed as an argument to the function must evaluate to what the system should consider as the current price.

The "BACKTEST:" rules are in the form of

BACKTEST: BUYWHEN(shares_to_buy,expression_to_calculate,Comment to add to the back testing log)

or

BACKTEST: SELLWHEN(shares_to_sell,expression_to_calculate,Comment to add to the back testing log)

or

BACKTEST: EVALUATE_ALL

THe "shares_to_buy" and "shares_to_sell" can also be an expression to be evaluated. This allows for more flexible scenarios, such as using half of your cash to buy whatever shares that money can buy.

Here is a simple example that puts everything into perspective:

 

 
//
// Simple example of back testing
// We calculate a short term moving average (10 days)
// and a long term moving average (60 days)
// When the short term crosses over the long term moving average
// we buy shares (because, the theory goes, the newly arrived
// investors are more bullish), and vice-versa.
//

RANGE(-2060,_LASTDATE)

CLOSE=LOAD(_TICKER,CLOSE)

VOLUME=LOAD(_TICKER,VOLUME)

STOPIF(CLOSE,2)
 
ICLOSE = INTERPOLATE(CLOSE)

MA10 = MOVAVG(ICLOSE,10)

MA60 = MOVAVG(ICLOSE,60)

RANGE(-2000,_LASTDATE)

BACKTEST: SELLWHEN(SHARES,(MA10(i)>MA60(i)),"Sell all shares")

BACKTEST: BUYWHEN((CASH/CLOSE(i)),(MA10(i)<MA60(i)),"Use all cash")

BACKTEST(CLOSE(i))

 
GRAPHAREA(75,25,0,0,0,0)

GRAPHLINE(Axis1,CLOSE,RED)

GRAPHLINE(Axis1,MA10,BLUE)

GRAPHLINE(Axis1,MA60,GREEN)

GRAPHBAR(Axis2,VOLUME,GREEN)

GRAPHLABEL(Axis1,Price)

GRAPHLABEL(Axis2,Volume)

GRAPHTITLE(_TICKER)

GRAPHSUBTITLE(Back testing results)

GRAPHTRADES()
 

------------------

Please note that  in your expressions you can use the variables

CASH, SHARES, PRICE and PROFIT

These four variables keep track of how much cash and/or shares you have at any given time. The PROFIT is a percentage. For example, a value of 3 for PROFIT means 3%.

The system starts with a 10,000 original amount. Also, a commission of $10 is assumed.