Hi, today I am gonna show you how easy it is to construct a simple backtesting for testing a trading strategy in just 8 lines of MATLAB code.
Here are the steps. First, we are going to bring in market prices and convert them into returns.
Next is to generate trading signals and calculate portfolio returns.
And the last step is to analyze portfolio performance using Sharpe ratio, maximum drawdown, and equity curve.
Again all of these can be done in just 8 lines of MATLAB code. Now, let’s switch to MATLAB
Since there are not many lines of code, we are going to do a step-by-step expiation here.
The very first thing that I would like to do is to show you the data. So I am going open “dowPortfolio.xls”.
This dataset contains daily prices of the Dow Jones Industrial Average and its members for the period of one year.
Now, we can actually perform backtesting.
First, import data into MATLAB using xlsread.
Then we can use the tick2ret function to convert the index levels into index returns.
Next is to generate trading signals based on Relative Strength Index (or RSI) , which consists of two components.
The first component is to create a buy signal when RSI is lower than 40.
And the second component is to create a sell signal when RSI is higher than 70. Now, we can calculate the portfolio return
By using the same amount of money to invest, the portfolio return is the index return multiplied by the vector of trading signals.
Here, we exclude the last signal because we can’t trade on it.
We can easily calculate the Sharpe ratio using the built-in function in the Financial Toolbox™ and annualize it.
Then we can convert the portfolio returns back to portfolio value using ret2tick function.
Then calculate the maximum drawdown in just one line of MATLAB code.
And, plot the equity curve in just one line of MATLAB code each. To save these commands for future usage, we can easily copy the command lines and paste into live editor
Here you can easily adjust the chart using our interactive tools.
Once you finish adjusting the chart, you can generate code back to your script in just one click.
What you have just seen is a simple backtesting. In fact, there are a lot of things you can do using MATLAB.
For example, instead of reading data from excel, you can use Datafeed Toolbox™ to retrieve market data directly from various data providers.
Also you can generate trading signals based on econometrics models or machine learning algorithms
Or if you want to use MATLAB to automatically execute your strategies, you can do so using Trading Toolbox™.
In case that you need more information, you can watch more videos in this page. Or you can request a trial on MATLAB to start a trial immediately.
Thank you very much for watching this video presentation.