Introduction to Algorithmic Trading

Nora Kovacs
Pills of BSDSA
Published in
7 min readNov 10, 2023

In the past, when people would hear the word “stock trading”, they would imagine a big and bustling trading floor, with traders signaling their actions through yelling and gesturing. However, today that is not the case anymore, due to advances in technology. These advances have turned the trading floor into a computer monitor and have changed the way stocks are bought and sold — a once manual human activity is now something an automated trading algorithm does in a fraction of the time.

An algorithm is a list of rigorous instructions to complete a specific task. Algorithms are used in stock trading by giving these algorithms variables such as price, timing, and volume to evaluate and make a decision of buying, selling, or keeping the share. Algorithmic trading is often used for high-frequency trading, where a firm is able to make tens of thousands of trades per second — something physically impossible for a human to do. [1] The discipline first emerged in the 1970s, when computerized trading systems were introduced to the American financial markets. With time the algorithms were developed to be more complex and sophisticated, due to advances in technology and data analysis. In the 2000s traders also started incorporating machine learning and artificial intelligence into their algorithms. [2] Even today, trading algorithms continue developing to be more sophisticated, with Nasdaq engineers creating technology that can track time to 100 billionths of a second. [3]

In 2003, algorithmic trading accounted for around 15% of the market volume, but by 2010 that number had risen to more than 70% in the equity market. A similar volume of trade is done by algorithms in European and Japanese markets as well. In emerging economies, however, the share of trades done by algorithms is much lower, being roughly 40% of the overall trading volume. [4]

Initially, algorithms were employed by institutional investors, who had the technological infrastructure, access to data, and personnel. However, due to the emergence of algorithm trading courses and Application Programming Interfaces (API) which act as an intermediary between the code and the chosen broker platform and provide access to real-time data, retail investors can take advantage of this mode of trading in even greater numbers. In this article, we would like to show you the basic concepts that the complex algorithms are built on. It is a great start to understand the function, goal, and structure of trading algorithms.

Crossover Simple Moving Average Algorithm

In order to grasp this trading algorithm, you need to be familiar with the concept of simple moving average. In a financial context, it works by adding the price of an instrument for n periods and then dividing the sum by n. We refer to the number of periods by window size. The greater the window size we apply, the smoother our moving average curve will get, and the less importance we put on short-term fluctuations. This method helps us to disregard temporal fluctuations and highlight the underlying trends instead.

We will show you a simple Python code for a Moving Average Crossover strategy, highlighting the most important considerations you should make before designing your own algorithm. The logic of the algorithm is as follows: we analyze the short and long window sizes and compute two moving averages. The long window size gives us an idea about longer trends, whereas, the short window shows us where the price is moving currently. Our strategy advises us to sell or buy at the crossover of the two moving averages, as it suggests a shift in trends [5].

Constructing your algorithm, as a first step, you should make sure to import pandas to store your data about prices and matplotlib to create your graphs. Afterward, you need to determine your window size. It depends on your investment goals, there is no one-size-fits-all approach. If you are considering a long-term investment strategy, you may prefer to set larger window sizes, as you are interested in exploiting longer trends, for example, 200 for long and 50 for the short window size. In our code, we use 50 and 10 for window sizes to highlight crossovers in the most visible way on our data about Tesla shares of the last 365 days. For the calculation of the moving average, you need to use the rolling function as shown below.

The next step will be creating the signals that suggest buying or selling our instrument. We would like our algorithm to generate a signal when the moving averages cross. If the short-term average is lower than the long-term average in period n-1 and the two cross in period n, the algorithm creates a buy signal. In this case, we know that the short-term average is increasing, which reflects the current trend of our asset. As our instrument’s price is getting higher we opt for entering a long position, this is why the algorithm sends the buy signal. Conversely, when the two averages cross, in period n-1 the short trend is higher than the long one, price is decreasing, therefore, we’d better sell our instruments.

Lastly, we plot the moving averages and the signals.

Using data about last year’s Tesla prices, we get the following result. Our graph informs us of the moving averages and the moments when the algorithm would buy or sell our assets.

The Crossover Simple Moving average strategy is often employed for its simplicity, however, it is criticized for missing opportunities as they give signals after the trend has started, as you can observe on the graph. Also, they put equal weight on all periods, which is not realistic. The exponential moving average strategy can address the later problem, as it gives more weight to more recent periods.

Arbitrage Trading Strategies

Arbitrage is the process of simultaneously transacting multiple financial securities to make a profit from the difference in prices. An example would be a company’s stocks being traded in two locations — Milan and London. The same stock trades for 5€ in London, but 5.05€ in Milan. Using the arbitrage strategy, we would buy shares in London and sell them in Milan, thus making a profit of 0.05€ for every share.

Statistical arbitrage is a trading strategy, based on the statistical mispricing of one or more assets compared to the expected future value of the assets. One of these strategies is following assets that are correlated and looking for a deviation in the relationship. An example of this would be Pepsi and Coca-Cola stocks. Since the companies are in the same sector, their stock often moves together, enabling traders to identify a period of separation, thus identifying an arbitrage opportunity. Therefore, to have a successful statistical arbitrage trading algorithm, the algorithm needs to identify related stocks, and the entry-exit levels must be specified. [6]

Threats of Algorithms

Because of the complexity of trading algorithms, it is impossible to assess their exact impact on the financial market, however, in some cases, they undeniably demonstrated some dangers to the stability of markets. The most well-known example of algorithms’ failure is the Flash Crisis on 6 May 2010. On that day, the US equity market’s major indexes went down by 4%. Automated algorithms reacted aggressively, they started buying and selling securities at a high speed, which led to transactions being made at absurd prices. According to the International Organization of Securities Commissions (IOSCO) Technical Committee [7], 20,000 trades were executed with a 60% difference between their actual price and the price a few minutes before. A short time after the shock the prices recovered. It is reported that the flash crash was strongly amplified by algorithmic trading, which reacted quickly and automatically to the events and further exacerbated them.

In 2016 the British pound experienced another high-speed selling spiral, which was followed by the Twitter post of the French president saying that Britain will get a hard Brexit. In 2 mins the pound fell 6% against the dollar. The abrupt price change is attributed to algorithms by most experts, who claim that many algorithms employ natural language processing techniques, and thus use headlines as a basis of their decisions. Alarmed by the news the algorithms started selling the currency, which triggered further selling by other algorithms that are programmed to sell if the price changes reach a given threshold [8].

Risk Mitigation

In order to avoid being a victim of a similar crash and make your algorithm resilient, it is crucial to add some extra levels of safety. One of the simplest and best-known algorithms is stop-loss order, which ensures that you exit your position if prices change above a certain threshold. Referring back to our Crossover Simple Moving Average algorithm, you may add these lines of code to avoid losing a lot in volatile shocks.

Algorithmic trading is one of the most important emerging trends both in finance and computer science, therefore, it is essential to pay attention to new developments. The best way to get involved is to write your first code and implement it on platforms such as Alpaca, Interactive Brokers, TradeStation QuantConnect, and many others to get first-hand experience.

Sources:

  1. https://www.investopedia.com/terms/a/algorithmictrading.asp
  2. https://algomojo.com/blog/evolution-of-algorithmic-trading/#:~:text=History%20of%20Algorithmic%20Trading,at%20the%20best%20available%20prices
  3. https://www.nytimes.com/2018/06/29/technology/computer-networks-speed-nasdaq.html
  4. https://www.quantifiedstrategies.com/what-percentage-of-trading-is-algorithmic/#What_percentage_of_trading_is_algorithmic
  5. Donadio, S. and Ghosh, S. (2019) Learn algorithmic trading: Build and deploy Algorithmic Trading Systems and strategies using Python and Advanced Data Analysis. Birmingham: Packt Publishing Ltd.
  6. https://blog.quantinsti.com/statistical-arbitrage/
  7. The Economist (2016) ‘Sterling takes a pounding’. Available at: https://www.economist.com/buttonwoods-notebook/2016/10/07/sterling-takes-a-pounding (Accessed: 10 April 2023).
  8. The International Organization of Securities Commissions (IOSCO) Technical Committee (2011) ‘Regulatory Issues Raised by the Impact of Technological Changes on Market Integrity and Efficiency’, pp. 10–12.

By Albert Loog and Nóra Noémi Kovács

--

--