2015-03-12

The TA Developer toolbox integrates easily with other Matlab toolboxes. E.g. analyze data with the statistics toolbox or send trades directly to Interactive Brokers using the IB-Matlabtoolbox.

Trading GUI

Create and backtest trading strategies with a simple and easy to use graphical user interface (GUI). Configure backtesting parameters like capital and position size directly in the GUI.

Portfolio Backtesting

Perform backtests of trading algorithms on a portfolio of stocks. You can focus on the trading strategy development and do not need to worry about writing backtesting code.

Matlab Language

Use the power of the Matlab programming language to create trading strategies. Use advanced statistical features for trading which are not available in other trading software.

Technical Indicators

Use more than 70 standard technical indicators to perform technical analysis of stock and futures data. All technical indicators can be easily applied per drag&drop.

Performance Evaluation

Calculation of performance metrics like Annualized Return, Maximum Drawdown, Sharpe Ratio etc. If you need an unsupported metric, you can just code it yourself in Matlab.



PAIRS TRADING STRATEGY

I have been asked a couple of times how to create and backtest a pairs trading strategy in MATLAB. This is why I wrote a tutorial about pairs trading in MATLAB.

I was reading in another blog about the close relationship between the Australian and Canadian economies (National Arbitrage: Australia vs. Canada). Both countries are resource-rich and according to the blog post, both countries have an economic and statistical correlation.

I will use the close relationship between the economies to create a pairs trading strategy. The iShares MSCI Australia Index (EWA) is used as a proxy for the Australian economy and the iShares MSCI Canada Index (EWC) is used as a proxy for the Canadian economy.



THREE RED CANDLES TRADING STRATEGY

Starting from TA Develper build number 612 the toolbox includes a “Shift” operator for data series. The shift operator allows shifting a data series by a number of bars. For example Shift(Open,1) shifts the opening price by one bar:

We can have a look if the current bar is a ‘red candle’ which means that the close price is lower or equal to the opening price:

Another useful function available for data series is the ‘&’ operator. The ‘&’ operator can be used to combine technical indicators and signals. By using the ‘&’ operator we can combine signals to see if the previous three candles are red:

The following trading strategy gives an example of how to use the Shift and ‘&’ functions. The strategy enters a long position when three red candles occur and exits the position when three white candles occur. A red candle is defined by the closing price of a bar being equal to or smaller than the opening price. The position is closed when three white candles occur in a row. A white candle is defined by the closing price of a bar being greater than the opening price.

Please make sure you have TA Developer buid 612 or higher installed to use the Shift function. You can check your version by clicking on ‘About TA Developer’ in the help menu. If you have an older version installed, you need to update the toolbox to the latest version by getting the installer from the download page and running it again.



BACKTESTING TRADING STRATEGIES IN MATLAB

This blog is about creating and backtesting trading strategies in MATLAB. Over time I intend to build up a library of MATLAB trading strategies. If you give the TA Developer toolbox a try and come up with a strategy (and upload it to the MATLAB file exchange), I would like to hear from you. I will link your strategy from this website.

The first trading strategy in this series is a simple band trading strategy. The strategy consists of a so called trading band. The band consists of two lines that form the upper and lower boundaries of the band. The upper and lower boundaries are used to to enter and exit trades. For example, if prices fall below the lower boundary a buy signal is generated.

The full tutorial about creating and backtesting a band trading strategy can be found here: Creating an Algo Trading Strategy in MATLAB  The corresponding m-file can be downloaded from the MATLAB file exchange: Band Trading Strategy

What are your experiences with using MATLAB for trading strategy development? Please let me know in the comments section below.

CREATING AN ALGO TRADING STRATEGY IN MATLAB

This article describes how to develop an algorithmic trading strategy in MATLAB. The TA Developer toolbox is used to visualize stock data and perform a backtest over a portfolio of stocks. A band trading strategy is developed which enters long trades when prices fall below the lower band and short trades are entered when prices rise above the upper band. The strategy is backtested over 10 years of historical data. In particular, a portfolio backtest over the data of 11 technology stocks is performed. The execution results are displayed by the TA Developer toolbox in form of a statistics summary page, a detailed trade list, and an equity curve. The statistic summary shows statistics like the number of winning and losing trades as well as common trading metrics like the Sharpe and Sortino Ratios.

Requirements

MATLAB

Microsoft .NET 4.0 or higher

TA Developer Toolbox

It is assumed that you have read the following articles:

Toolbox Installation

Getting Started

Band Trading

The trading strategy we are going to create will use a trading band. A band consists of two lines that form the upper and lower boundaries of the band. The upper and lower boundaries can be used to enter and exit trades. For example, if prices fall below the lower boundary a buy signal is generated. When prices return to the area within the band a sell signal is generated. There are a number of different ways how to construct these bands. In general, bands are used to detect short term breakouts and are used in mean reversion systems. Mean reversion means that it is assumed that the breakout is a short term anomaly and that prices will return to the mean in the long term.

MATLAB BAND TRADING STRATEGY

Creating a new strategy m-file

A trading strategy consists of a MATLAB function with a single parameter called sys. The sys parameter contains trading system data like the open, high, low and close prices of a stock or a future.

Start by creating a MATLAB function with the name BandTrader.m

The function should look like this:

This empty function will serve as starting point for our band trading strategy.

Creating the Bands

In order to create the bands, two variables are needed: a centerline and a distance from the centerline. Dr R Koch describes in his article “Creating Your Own Trading System” [1] a variation of techniques that can be used to create these variables. The following sections give a brief summary of these techniques. Please refer to the original article for a detailed discussion.

THE CENTER LINE

There are a number of ways to calculate the center line.

Average Price: Avg = (High + Low) / 2

Average of high, low, and close: AvgC = (High + Low + Close) / 3

A weighted mean of open, high, low, and close: AvgP = (w1*Open + w2 *High + w3*Low + w4*Close) / (w1+w2+w3+w4)

These averages can be very noisy so it is recommended to smooth the center line using a moving average. The TA Developer toolbox has the following moving averages built in:

Sma: Simple Moving Average

Ema: Exponential Moving Average

Wma: Weighted Moving Average

The following code example creates a center line using the average price. This average price is smoothed by an exponential moving average using a lookback period of 10 bars. In addition, the centerline is plotted to the price chart using the PlotDataSeries function.

For more information about the PlotDataSeries function type ‘help PlotDataSeries’ in the MATLAB command prompt.

DISTANCE

Similar to the center line there are a number of ways to determine the distance of the bands. A simple way to create the bands is the use a constant distance from the center line. More advanced approaches are based on price volatility so that the bands get wider during volatile times and more narrow during less volatile times. The following techniques can be used as an estimate for volatility:

Moving average of the Range (High-Low)

Moving average of the True Range (The True Range uses the previous Close if outside the High or Low price for the range calculation)

Standard deviation of the Close

In our example we use the built in Atr (Average True Range) indicator to determine the distance of the bands.

A popular variation of the technique is the Bollinger Band. The Bollinger Bands use a 20 period simple moving average (SMA) as the centerline and the distance is a multiple of the standard deviation. The TA Developer toobox has the following Bollinger Band technical indicator built in: BBandLower, BBandMiddle, BBandUpper. To see how these indicators work, you can type e.g. ‘help BBandMiddle’ into the MATLAB command prompt or drag&drop the indicator from the indicator window into the price chart area.

Entry and Exit Rules

After constructing the bands we can use the upper and lower boundaries to create trading signals. We want to create a long entry signal when the close price falls below the lower band and we want to create a short entry signal when the close price rises above the upper band.

The AddLongSignal and AddShortSignal functions use the information of the LongSignal and ShortSignal time series to create trade entries and exits. For example, LongSignal contains zeros (representing ‘false’) if the close price is greater or equal than the LowerBand. LongSignal contains ones (representing ‘true’) when the close price is smaller than the lower band. If the signal is one (or ‘true’) the TA Developer toolbox creates an trade entry and if the signal is zero (or ‘false’) the toolbox creates a trade exit. Trades are executed at the open price of the next bar to avoid a look ahead bias. E.g. if the close price falls below the lower band on the 1st of March, the trade is entered on the 2nd of March using the open price.

In our example the same signal time series is used for trade entries and exits i.e. enter when the close falls below the lower band and exit when the close price rises above the lower band. It is also possible to specify separate entry and exit signals. For example you could enter a long trade when the price falls below the lower band and hold the position until the price rises above the center line (instead of the lower band used before).

Using Strategy Trading Parameters

When a strategy backtest is performed on the MATLAB command prompt, trading parameters can be passed to the strategy. This way parameter optimizations can be performed easily. The trading parameters are stored MATLAB variable of type ‘containers.Map’. This map contains key value pairs with the parameter name as a key and a value of type double. In our strategy example above, we have hardcoded the period of the center line and average true range moving averages to 10 and the band width to 2. In order to optimize these parameters later (see section parameter optimization) we need to read the parameter values before the strategy is executed. First it is checked if the parameter is set in the map using the ‘isKey’ function. If the parameter is not set, we use a default value of 10 for the moving average and 2 for the band width.

Putting It All Together

In the previous sections we have explored the steps needed to create a band trading strategy. The following function combines all steps into a trading strategy.

Backtesting the Strategy

Type ‘tadeveloper’ into the MATLAB command prompt to open up the TA Developer graphical user interface. Click File>Open from the menu and browse to the location where you saved the BandTrader.m strategy and open the file.

Before executing the strategy, we need to set a few parameters first. In the bottom right corner is a window called Properties. This window contains important execution parameters. We will set the starting capital for the simulation to 100000. The position type is set to ‘Percent’ and the position amount is set to 10 which means that 10% of the available capital is used per trade. Raw Profit Mode is set to false. If Raw Profit Mode was set to true, the amount of available capital would be ignored. With Raw Profit Mode set to false, trades will NOT be entered in our simulation if not enough capital is available to enter the trade.

PROPERTIES WINDOW

Make sure the watchlist root node (called TechnologyStocks from our previous example in the ‘Getting Started Guide’) is selected in the Symbols window. You should see the backtest panel. Press the green Play button the start the simulation.

Strategy Performance Evaluation

When the strategy has executed successfully, the ‘Statistics’ tab becomes available. It shows various trading metrics like the Annualized Return, Sharpe Ratio, Sortino Ratio, Ulcer Index, Number of Trades and many more. These metrics are divided into ‘All’ (for all simulated trades), ‘Long’ (long trades only) and ‘Short’ (short trades only). In addition, the metrics for the Buy&Hold strategy are shown to allow an easy comparison.

BACKTEST RESULTS

Running the Strategy from the Command Line

It is also possible to run the strategy simulation from the MATLAB command prompt. This is for example useful if you want to automate the simulation or want to perform a parameter optimization. In order to execute the strategy, you need to set the trading parameters first. By selecting ‘Generate Code’ in the File menu all the necessary code is generated. After clicking ‘Generate Code’ copy the generated source code into a file called ‘runBandTrader.m’. The file contents should look similar to this:

In order to execute the strategy just run the generated ‘runBandTrader’ function. All metrics are available in the systemStatistics object. Use the name as displayed in the ‘Performance Evaluation’ section above the access the values.

Parameter Optimization

Earlier we created trading parameters called ‘movingAverage’ and ‘bandWidth’ in the trading strategy. The movingAverage parameter is used as the lookback period to smoothen the moving averages and the band width parameter is used as a multiplier in calculation of the distance between the center line and the bands. So for we used default values of 10 for the moving average and 2 for the band width. The default values have been chosen more or less arbitrarily. In order to see if increasing or decreasing these values improves the trading strategy, you could simply change these values and re-run the strategy. The following script automates this task by setting the parameters ‘movingAverage’ and ‘bandWidth’ to a range of different combinations to see which parameter settings work best. In this example the Sharpe Ratio metric is used to evaluate how a strategy performed. This can be changed to any metric you are interest in.

By running the script all parameter combinations are executed and at the end the parameters which lead to the highest Sharpe Ratio are shown. In our example a moving average of 7 and a band width of 1.9 lead to the highest Sharpe Ratio. In addition a surface plot is created which shows the distribution of Sharpe Ratios in relation to the trading parameters.

TRADING PARAMETER OPTIMIZATION

Commission and Slippage

The simulation we performed so far did not consider trading costs or slippage. Trading costs are for example transaction fees you need to pay your broker and slippage is the difference in price between your desired trade price and the price you actually pay in the market. For example at market open you might not be able to enter a trade at the exact (historical) opening price.

Broker commissions can be simulated by the TA Developer toolbox by setting the commission fields. Possible commission types are:

Percent: Commission amount is interpreted as percentage e.g. 1 means 1 percent of the trade value

PerShare: Commission amount is interpreted as dollar per share e.g. 1 means 1 dollar per share

PerTrade: Commission amount is interpreted as dollar per trade e.g. 1 means 1 dollar per trade

The slippage type can have the following settings:

Percent: Slippage amount is interpreted as percentage e.g. 0.1 means the trade entry price is adversily adjusted by 0.1% of the trade value

Tick: Commission amount is interpreted as number of ticks e.g. 1 means to adjust the entry price by $0.01 (assuming the tick size for the product is $0.01)

Commission and Slippage can be set in the properties window and can be used to simulate costs incurred during trading. It is recommended to set these parameters to sensible values to make the backtest more realistic.

Backtesting Pittfalls

This article showed how to create and backtest an algorithmic trading strategy. To keep the data acquisition simple data of 11 highly successful technology stocks was used. These stocks were selected with the benefit of hindsight. 10 years ago it would be very hard to predict the success of these stocks. To create a more realistic backtest you need to add all the components of a stock index (e.g. S&P 500) to the backtest. In the TA Developer toolbox this simply means adding more stocks to the watchlist.

In order to avoid survivorship bias you should even include data of stocks that have been delisted during the simulation period. Alternatively you can focus your backtest on more recent data to reduce the impact of delisted stocks. For a detailed discussion of survivorship bias and other backtesting pitfalls please refer to Dr E P Chan’s book ‘Quantitative Trading: How to Build Your Own Algorithmic Trading Business’ [2].

GETTING STARTED

This guide gives an overview of the steps necessary to import stock data into the TA Developer toolbox in order to be able to backtest a trading strategy in MATLAB. It describes how to download stock data from Yahoo! Finance and save the data to CSV files. Yahoo! Finance is used as an example in this article, but any stock data in CSV format can be used. It is shown how to import CSV data into the TA Developer toolbox using the CSV setup wizard. The data can be displayed in form of a candle stick chart and technical indicators can be applied by drap&drop.

Requirements

MATLAB

Microsoft .NET 4.0 or higher

TA Developer Toolbox

It is assumed that you have read the following article:

Toolbox Installation

Getting Data From Yahoo! Finance

We will start by downloading the data of 11 technology stocks from Yahoo! Finance. We use the script called “getyahoo10.m” from the MATLAB file exchange (Yahoo Data Download Script) to download 10 years worth of stock data for these companies. Once you downloaded the script, please execute it as shown in the following example. For more information about this script please type ‘help getyahoo10′ into the command prompt.

Importing CSV Data

Type “tadeveloper” into the command prompt to start the TA Developer graphical user interface.

The user interface consists of the main charting area and several toolbox windows. One of the toolbox windows is the Symbols box located on the top left corner of the screen. In order to import CSV data into the toolbox, open the Data Source Manager by selecting the link called ‘Data Sources’ located at the bottom of the Symbols window.

Click the Add button in the Data Manager to add a new data source.

Follow the CSV wizard steps to setup the data source:

1. Enter a Watchlist Name e.g. TechnologyStocks

2. Select the directory in which you saved the data files earlier e.g. C:\StockData.

3. Select the scale of the data. Choose “Daily” since we downloaded daily data from Yahoo! Finance.

4. Choose the data format. Enter “yyyy-MM-dd” in the text box labelled Date Format. The other boxed can remain with it’s prefilled values. (See screenshot below) Then click on the ‘Next’ button.

5. If all the information has been entered correctly in the previous screen, a confirmation screen will be displayed showing Open, High, Low, Close and Volume information. Click “Finish” to create the data source.

Click “Close” to close the data manager. The newly created watchlist should now be available in the symbols box. Doubleclick on one of the symbol names to see a candle stick chart of the imported data. The chart area allows scrolling through and zooming in and out of the data.

Applying Technical Indicators per Drag&Drop

The TA Developer toolbox has a number of built in technical indicators. These indicators can be applied to the chart area by drag&drop. Simply select one of the technical indicators from the indicators window (window on the bottom left) and drag the indicator onto the charting area. A dialog will pop up asking about indicator parameters like the lookback period for the simple moving average in the example below. In addition the line style, line color, and line width can be selected.

After clicking the Ok button, the indicator should be drawn in the charting area like shown in the screenshot below. To remove the indicator again, right click on the indicator line and select ‘Delete Indicator’ from the context menu.

MATLAB PAIRS TRADING

This article shows how to use MATLAB and the Technical Analysis (TA) Developer Toolbox to create and test a pairs trading strategy. The TA Developer toolbox complements the existing computational finance toolboxes by adding advanced backtesting functionalities like portfolio backtesting, calculation of standard trading metrics and an interactive graphical user interface that allows applying technical indicators via drap&drop.

Example: Australia – Canada spread

This first step in creating a pairs trading strategy is choosing two financial instruments that are historically correlated. The pairs trading strategy takes advantage of short term divergence by entering a short position in one instrument and a long position in the other. The strategy assumes that the pair will converge in the long term. By being short in one instrument and long in the correlated instrument this strategy is market neutral. For example if the stock market crashes profits from shorting one instrument should offset the losses from the long position. In this demo we use the fact that Australia and Canada are two resource-rich countries which have an economic and statistical correlation as explained here:

National Arbitrage Australia vs Canada

SCREENSHOT: PAIRS TRADING STRATEGY

Downloading the data

For the pairs trading strategy we use the iShares MSCI Australia Index (EWA) as a proxy for the Australian economy and the iShares MSCI Canada Index (EWC) as a proxy for the Canadian economy. The data can be downloaded from Yahoo finance by using the getyahoo10.m script from the MATLAB file exchange. getyahoo10.mdownloads 10 years of daily data from Yahoo finance and saves the downloaded files in the specified directory.

The downloaded data can then be imported into the TA Developer Toolbox as described here:

Importing trading data into the TA Developer Toolbox

Creating a new strategy m-file

A trading strategy consists of a MATLAB function with a single parameter called sys. The sys parameter contains trading system data like the open, high, low and close prices of a stock or a future. We will add entry and exit trading rules to this trading strategy m-file. No additional writing of backtesting code is required. The backting and performance evaluation is all handled by the Technical Analysis (TA) Developer Toolbox. The empty trading strategy should look similar this and servers as a starting point for every trading strategy.

Defining the primary and secondary symbols

In our trading strategy we start with defining the symbol names of the primary and secondary instruments, as well as the watchlist name that has been selected during the data import. Putting these values in variables allows easily adjusting the strategy to other pairs later.

Trading parameters

Trading parameters can be used in a parameter sweep. If we are not running a parameter sweep, these parameters will default to the second parameter passed to the ‘GetTradingParameter’ function.

Calculating and plotting the ratio, average, standard deviation and z-score

Ratio between primary (EWA) and secondary (EWC)

Standard deviation

Calculate the z-score and plot the thresholds. The z-score indicates how many standard deviations an observation is above or below the mean.

Z-SCORE PLOT AND TRADING THRESHOLDS

Primary entry and exit signals

ZScoreUpper defaults to 1.5 and ZScoreLower defaults to 1. So we enter a short position in the primary (EWA) when the z-score exceeds 1.5 standard deviations (upper red line) and exit the short position when the z-score falls below 1 standard deviation (upper green line).

Add long position when the z-score falls below -1.5 standard deviations (lower red line) and exit long position when the z-score rises above -1 standard deviations (lower green line).

Secondary entry and exit signals

Switch to the secondary context (EWC). All functions called after ‘SwitchSymbol’ are executed on the secordary symbol until ‘RestoreSymbol’ is called.

Backtesting the strategy

Type ‘tadeveloper’ into the MATLAB command prompt to open up the TA Developer graphical user interface. Click File>Open from the menu and browse to the location where you saved the PairsTradingStrategy.m strategy and open the file.

Before executing the strategy, we need to set a few parameters first. In the bottom right corner is a window called Properties. This window contains important execution parameters. We will set the starting capital for the simulation to 100000. The position type is set to ‘Percent’ and the position amount is set to 50 which means that 50% of the available capital is used per trade.

TRADING PARAMETERS

Make sure the watchlist root node is selected in the Symbols window. You should see the backtest panel. Press the green Play button the start the simulation.

BACKTEST PANEL

Performance evaluation

When the strategy has executed successfully, the ‘Statistics’ tab becomes available. It shows various trading metrics like the Annualized Return, Sharpe Ratio, Sortino Ratio, Ulcer Index, Number of Trades and many more. These metrics are divided into ‘All’ (for all simulated trades), ‘Long’ (long trades only) and ‘Short’ (short trades only). In addition to the metrics page, a list of all executed trades and an equity curve are calculated and displayed.

TRADING METRICS

Parameter sweep

So far we used 1.5 as an upper threshold and 1 as an lower threshold for the z-score to enter and exit our spread position. MATLAB makes it easy to perform a parameter sweep to run through a number of values to determine the optimal parameter values. The steps involved in running a parameter sweep are explained hereMATLAB Algo Trading under the subheading ‘Parmeter Optimization’.

We ran a parameter sweep and set the range for the lower boundary threshold from 0 to 1 and the range for the upper boundary threshold from 1 to 2. As the variable to optimize we chose the Sharpe Ratio, but any other metric (e.g. Total Profit, Sortino Ratio etc.) could be used. The result can be seen in the Surface/Contour plot below.

SHARPE RATIO PLOT

Trade Execution

For information about sending trades directly from MATLAB to Interactive Brokers please see the IB-Matlab toolbox.

Full strategy code of PairsTradingStrategy.m

Please make sure you have TA Developer buid 614 or higher installed to use the the strategy below. You can check your version by clicking on ‘About TA Developer’ in the help menu. If you have an older version installed, you need to update the toolbox to the latest version by getting the installer from the download page and running it again.

The post TA Developer appeared first on Software Sales.

Show more