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