Matlab for Amibroker Users – Backtesting Functions for Matlab

The point of this post is to provide some basic functions to non professional Matlab users that may help backtest a simple long only system the way Amibroker (and  most other software) backtest.

If you are an Amibroker user you are used to something this easy:

sma9=ma(close,9);
sma21=ma(close,21);
buy=Cross(sma9,sma21);  
sell=Cross(sma21,sma9); 
Wish you could do that in Matlab?
Here’s the Matlab Code for a simple Moving Average Crossover system using some custom functions

%START CODE
%You need these files in the “Path”  for the code to work
%sma.m, iif.m, Cross.m, backtestlongAmount.m, GetTickerV.m, stock.m
%Download SPY from Yahoo, 5 years history, daily bars. We get a “fints” object
% Function TickerV() is similar to function stock() except that 
%it adjusts for OHLC to Adjusted Close Data.

ticker_fints=GetTickerV(‘SPY’,’5y’,’d’);
%%Get the close price from fints and make it a vector
close=fts2mat(ticker_fints.close);
open=fts2mat(ticker_fints.open);
sma9=sma(close,9);
sma21=sma(close,21);
buy=Cross(sma9,sma21);  % custom function, NOT Matlab’s native cross( ) 
sell=Cross(sma21,sma9); 
%Signal should be 1 for Buy, -1 for Sell and 0 for noAction (or Hold)
signal= iif(buy==1,1,iif(sell==1,-1,0));
% Buy and Sell on next bar Open 
 [pnl,pnlvector, sh]= backtestlongAmount(close,signal,open,1,100000);
% [pnl,pnlvector, sh]= backtestlongAmount(close,signal,close,0,100000);
plot(pnl,’DisplayName’,’pnl’,’YDataSource’,’pnl’);figure(gcf)
%END CODE

You are free to copy the code and download the functions. I am not a professional coder. Most functions include pre-existing code that I combined and edited. It’s very probable that mistakes exist.
I am sharing these m files in hope others will check and improve them.

Disclaimer: This code may not provide accurate results. You will have to check yourself to make sure the code works as it should.

The function are:
sma.m
iif.m
Cross.m
backtestlongAmount.m
GetTickerV.m
stock.m

here’s the link:
Custom Functions


Basic Backtest Function for Matlab

[pnl,pnlvector, sh]= backtestlongAmount(data,signal,buyprice,delay,amount$$);

This is a very basic function for backtesting a strategy in Matlab.
All you need is a vector with 1s for Buy, -1’s for Sell and 0’s for Hold.

To use it we need
1. A vector of prices,i.e. SPY close prices
2. Signal: A vector of  1 for BUY, -1 for SELL and 0 for HOLD
3. Buyprice: A vector of Close prices if we buy at close or Open prices if we buy at Open
4. Delay: 0 if we buy “Today” – 1 if we buy tomorrow. So to Buy Tomorrow on Open:
backtestlongAmount(data,signal,open,1,amount$$);
4. Amount :i.e., 100,000

backtestlongAmount.m

Please report any bugs or inaccuracies you find. Improvements are welcome.