Algorithmic Trading Using AI – From Backtesting to Execution

This algorithmic trading software article was written by Erica McGillicuddy, Analyst at I Know First.

algorithmic trading
(Source: Security Magazine)

Summary

  • Algorithmic trading platforms such as Quantopian offer modules that ease the coding process
  • Backtesting is an essential part of the algorithmic trading process that allows for tweaks to your code that improve its success
  • Backtesting offers a variety of performance metrics including alpha, beta, the Sharpe ratio, net exposure, and drawdown

Algorithmic Trading Basics

Algorithmic trading software implements the rules of an algorithm to make trades that suit the trader’s preferences such as risk level and target quantity. This method of trading reduces daily time commitment, risk of manual error, and the emotional factor. The diagram below outlines the basic steps to algorithmic trading.

Combining traditional algorithmic trading strategies with strategies based on I Know First’s daily forecasts allows for the most complete base of information in making trading decisions. Algorithmic trading basics and how I Know First forecasts can be implemented were further discussed in this article. Now I will go into more detail regarding the code behind algorithmic trading, and how it is evaluated in backtesting prior to the live market.

Code Logistics

In the creation of the code for your algorithm, it is important to take all factors into account so that it is best customized to how you want to invest. This includes how frequently you want trades to be made, the time of day you would like to make trades, asset diversity, trading position, and more. These customizations can be achieved through use of constraints. For example, constraints can limit the amount of money spent on any one position or type of asset.

why is coding important?
(Source: Spaces)

This algorithm development is enabled by algorithmic trading platforms such as Quantopian. There are many other platforms that provide similar offerings, however Quantopian offers the most educational and research tools. On Quantopian there are some essential modules that make the coding experience much easier. Two of the main ones are quantopian.pipeline and quantopian.optimize.

Quantopian Modules

Quantopian.pipeline gives users easy access to Quantopian’s pipeline of relevant information and premade functions. Quantopian states that, “Pipeline terms are implemented via factors, filters, and classifiers.” A factor is a function that computes a numerical value for a specific asset at a given moment in time (f(asset, timestamp) –> numerical value). For example, SimpleMovingAverage takes in an asset and a duration of time, and returns the corresponding simple moving average as a numerical value. A filter is a function which accepts the same inputs but returns a Boolean (f(asset, timestamp) –> Boolean). For instance, a function which returns whether or not the closing price of an asset was greater than a set value. A combination of utilizing factors and filters is demonstrated below. Finally, a classifier returns a categorial output such as a string or integer label (f(asset, timestamp) –> category). Classifiers are often used to sort data, such as in the case of a function that determines the most recent exchange that an asset has been traded on.

algorithmic trading
(Source: Quantopian)

Quantopian.optimize provides tools to allow easy optimization of select factors. It takes in an objective and a constraint, and it optimizes your portfolio based on them. This module hides the complex math which lets the user focus on maximizing returns and constraining exposure on a more simplistic level without getting into the nitty-gritty.

The two available objectives are quantopian.optimize.TargetWeights and quantopian.optimize.MaximizeAlpha. TargetWeights is used to construct a target portfolio (eg. long and short stocks) that is either equally weighted or weighted by a customizable factor. MaximizeAlpha is utilized to attempt to predict future returns based on historic results, and maximizes the sum of each asset in the portfolio’s weight times its alpha value. Constraints are also crucial in optimization in order for the objectives to be met. Some of the most common constraints in Quantopian which are somewhat self explanatory are MaxGrossExposure, NetExposure, PositionConcentration, NetGroupExposure, and FactorExposure.  These constrain the total value of investments, the value of a specific asset, exposure to a sector, and exposure to risk factors.

algorithmic trading
(Source: Quantopian)

More information regarding algorithm development can be found in this I Know First article. It describes how to get started with another algorithmic trading platform called QuantConnect, and how to implement an algorithmic trading strategy based on I Know First forecasts.

Backtesting

In algorithmic trading, backtesting is an essential step. After building your code based off of your trading preferences, backtesting gives you a chance to test the possible performance of a strategy based on historical data, and allows you to play with the specifics and values to increase the success. Changes can be made to improve return or to adjust the risk level. This article will go into the different metrics that backtesting measures, however if you would like more detail on how to get the most out of backtesting, check out this I Know First article.

Cover image for Algorithmic Trading: backtesting your algorithm
(Source: DEV)

The alpha value of an asset compares its return to the amount returned by a broad benchmark index such as the S&P 500. For example, if over a set time period a stock increases in value by 15% while the S&P 500 earns 5%, the alpha for that stock is 10. A higher value of alpha is always better, however it is a historical measurement and does not predict future trends.

Volatility Metrics in Backtesting

One of the most common measurements of volatility is the beta value. This value measures the volatility of an asset in comparison to the market.  The equation for beta is the covariance of an asset’s return with the market’s return divided by the variance of the market’s return. The baseline beta value is 1, which indicates that the asset’s price fluctuates the same amount as the market. A beta value less than 1 means the asset is less volatile than the market, and a value greater than 1 indicates that it is more volatile than the market. Ideal beta values depend on the type of investor you are. A high beta value is good for investors in growth stocks, while lower beta values are preferable for lower risk investors looking for consistent returns.

Historical volatility varies greatly in this scenario, used in algorithmic trading
(Source: Options Playbook)

The Sharpe ratio is also provided in Quantopian backtesting, and indicates the return on investment in comparison to risk (risk adjusted return).  It is calculated by subtracting the risk-free rate from the return on portfolio, and dividing that by the standard deviation. A higher Sharpe ratio is more appealing as you get more return for your risk. The Sharpe ratio is often used to analyze how an added investment affects a portfolio, however it is criticized for taking all volatility into account, including positive fluctuations.

(Source: Quantopian)

Net exposure is another feature of backtesting on Quantopian. This value is indicated as a percentage, and represents the weighting of the portfolio’s long and short positions. For example, if a portfolio is 70% long position and 30% short position, the net exposure will be 40%. A negative value for net exposure indicates a higher weighting of short stocks. In general, it is lower risk to have a net exposure value closer to zero, where long and short positions are roughly equal.

Finally, drawdown is one of the main metrics that backtesting reveals. The drawdown of a security speaks to how much the price of an asset falls after a peak prior to exceeding that peak.  It is calculated by subtracting the lowest price it reaches after a peak from the original peak price, and dividing that value by the original peak price. This measures the downside volatility, so a lower value is ideal. Some investors have drawdown limits so that they automatically sell if the drawdown value exceeds a certain percent, in order to minimize their loss. When analyzing drawdown it is also valuable to consider the historical time it takes for a specific asset to recover from a drawdown, as that may affect your decision to sell.

Drawdown for algorithmic trading
(Source: Investopedia)

Conclusion

Algorithmic trading platforms provide an ideal environment for coding. There is a large supply of research and educational tools, and modules such as quantopian.pipeline and quantopian.optimize make the coding much more straightforward. Backtesting is also a huge benefit, as it gives investors some comfort knowing their algorithm’s historic results before using it in the live market. Backtesting is very customizable for use testing a wide-variety of assets and time periods, and offering a range of metrics that analyze risk and performance. With user-friendly algorithmic trading platforms that are accessible to anyone and could be used to incorporate I Know First forecasts, this is a tool that could prove very worthwhile for I Know First investors.

Disclaimer: This article is for informational purposes to show our investors the tools available to them, it is not a paid promotion by Quantopian.