Algorithmic Trading in Less than 100 Lines of Python Code

O'Reilly Media
Dec 17, 2020 · 9 min read

If You Know Trading and Python, this Is Easy

Editor’s Note: The barriers to entry for algorithmic trading have never been lower. Not too long ago, only institutional investors with IT budgets in the millions of dollars could take part, but today even individuals equipped only with a notebook and an Internet connection can get started within minutes. In this piece from Python for Algorithmic Trading, author Yves Hilpisch shows you how to implement a complete algorithmic trading project, from backtesting the strategy to performing automated, real-time trading.

Algorithmic trading refers to the computerized, automated trading of financial instruments (based on some algorithm or rule) with little or no human intervention during trading hours. Almost any kind of financial instrument — be it stocks, currencies, commodities, credit products or volatility — can be traded in such a fashion. Not only that, in certain market segments, algorithms are responsible for the lion’s share of the trading volume. The books The Quants by Scott Patterson, More Money Than God by Sebastian Mallaby, and, more recently, The Man Who Solved the Market by Gregory Zuckerman paint a vivid picture of the beginnings of algorithmic trading and the personalities behind its rise.

The barriers to entry for algorithmic trading have never been lower. Not too long ago, only institutional investors with IT budgets in the millions of dollars could take part, but today even individuals equipped only with a notebook and an Internet connection can get started within minutes. A few major trends are behind this development:

  • Open source software: Every piece of software that a trader needs to get started in algorithmic trading is available in the form of open source; specifically, Python has become the language and ecosystem of choice.
  • Open data sources: More and more valuable data sets are available from open and free sources, providing a wealth of options to test trading hypotheses and strategies.
  • Online trading platforms: There are a large number of online trading platforms that provide easy, standardized access to historical data (via RESTful APIs) and real-time data (via socket streaming APIs), and also offer trading and portfolio features (via programmatic APIs).

This article shows you how to implement a complete algorithmic trading project, from backtesting the strategy to performing automated, realtime trading. Here are the major elements of the project:

  • Strategy: I chose a time series momentum strategy (see Moskowitz, Tobias, Yao Hua Ooi, and Lasse Heje Pedersen (2012): “Time Series Momentum.” Journal of Financial Economics, Vol. 104, 228–250.), which basically assumes that a financial instrument that has performed well/badly will continue to do so.
  • Platform: I chose Oanda as the trading platform. It allows you to trade a variety of leveraged contracts for differences (CFDs, see also http://www.investopedia.com/terms/c/contractfordifferences.asp), which essentially allow for directional bets on a diverse set of financial instruments (such as currencies, stock indices, commodities).
  • Data: We’ll get all our historical data and streaming data from Oanda.
  • Software: We’ll use Python in combination with the powerful data analysis library pandas, plus a few additional Python packages.

The following assumes that you have a Python 3.6+ installation available with the major data analytics libraries, like NumPy and pandas, installed. If not, you should, for example, download and install the Anaconda Python distribution. Or even easier, sign up for free on the Quant Platform, execute your code in the cloud, and leverage lots of free Python content for algorithmic trading.

Oanda Account

At http://oanda.com, anyone can register for a free demo (“paper trading”) account within minutes. Once you have done that, to access the Oanda API programmatically, you need to install the relevant Python package:

To work with the package, you need to create a configuration file with filename oanda.cfg in your current working directory that has the following content:

Replace the information above with the access token that you can generate and and the account ID that you find in your demo account on the Oanda platform.

The execution of the following code equips you with the main API object to work programmatically with the Oanda platform.

Backtesting

We have already set up everything needed to get started with the backtesting of the momentum strategy. In particular, we are able to retrieve historical data from Oanda. The instrument we use is EUR_USD and is based on the EUR/USD exchange rate.

The first step in backtesting is to retrieve the data. The data set itself is for a single day, November 11, 2020, and has a granularity of one minute. Open (o), High (h), Low (l), Close © values — together OHCL — are returned for each minute which form the basis of a common one minute bar or candlestick type structure, along with Tick Volume (volume) and Complete (complete). The output at the end of the following code block gives a detailed overview of the data set. It is used to implement the backtesting of the trading strategy.

Second, we formalize the momentum strategy by telling Python to take the mean log return over the last 15, 30, 60, 120, and 150 minute bars to derive the position in the instrument. For example, the mean log return for the last 15 minute bars gives the average value of the last 15 return observations. If this value is positive, we go/stay long the traded instrument; if it is negative we go/stay short.

Third, to derive the gross performance of the momentum strategy for the different momentum intervals (in minutes), you need to multiply the positions (signals) derived above (shifed by one day) by the market returns. Here’s how to do that:

Inspection of the plot above reveals that, over the period of the data set, the traded instrument itself has a negative performance. Among the momentum strategies, the one based on 150 minutes performs best with a positive return of about 0.35% (ignoring the bid/ask spread, see http://www.investopedia.com/ terms/b/bid-askspread.asp). In principle, this strategy shows “real alpha” (see also http://www.investopedia.com/terms/a/alpha.asp): it generates a positive return even when the instrument itself shows a negative one — while the risk as measured by the volatility stays the same for long/short strategies.

Automated Trading

Once you have decided on which trading strategy to implement, you are ready to automate the trading operation. To speed up things, I am implementing the automated trading based on twelve five-second bars for the time series momentum strategy instead of one-minute bars as used for backtesting. A single, rather concise class does the trick:

The code below lets the MomentumTrader class do its work. The automated trading takes place on the momentum calculated over five intervals of length five seconds. The class automatically stops trading after 100 ticks of data received. This is arbitrary but allows for a quick demonstration of the MomentumTrader class.

The output above shows the single trades as executed by the MomentumTrader class during a demonstration run. During the execution of the trading algorithm, you can use Oandas trading tools to monitor the executed trades and open positions. The following screenshot shows the browser-based trade application — two positions are open.

The following code closes out the final position and shows the complete, detailed order object.

All example outputs shown in this article are based on a demo account (where only paper money is used instead of real money) to simulate algorithmic trading. To move to a live trading operation with real money, you simply need to set up a real account with Oanda, provide real funds, and adjust the environment and account parameters used in the code. The code itself does not need to be changed.

However, you should be fully aware of the risks that such an endeavour entails and you should also have mastered the skills to manage such a transition to real trading on your own.

Conclusions

This article shows that you can start a basic algorithmic trading operation with fewer than 100 lines of Python code. In principle, all the steps of such a project are illustrated, like retrieving data for backtesting purposes, backtesting a momentum strategy, and automating the trading based on a momentum strategy specification. The code presented provides a starting point to explore many different directions: using alternative algorithmic trading strategies, trading alternative instruments, trading multiple instruments at once, and so forth. Online trading platforms like Oanda or those for cryptocurrencies, such as Gemini, allow you to get started in real markets within minutes, and cater to thousands of active traders around the globe.

Resources

To learn more about the skills required to apply Python for Algorithmic Trading you should consult these books and resources:

  • Hilpisch, Yves. 2018. Python for Finance: Mastering Data-Driven Finance. 2nd ed. Sebastopol: O’Reilly.
  • Hilpisch, Yves. 2020. Artificial Intelligence in Finance: A Python-Based Guide. Sebastopol: O’Reilly.
  • Hilpisch, Yves. 2021. Python for Algorithmic Trading: From Idea to Cloud Deployment. Sebastopol: O’Reilly.
  • Quant Platform with Jupyter Lab in the cloud — including free trial accounts and free Python code from the book Python for Algorithmic Trading
  • Certificate Program in Python Algorithmic Trading by The Python Quants

Learn faster. Dig deeper. See farther.

Join the O’Reilly online learning platform. Get a free trial today and find answers on the fly, or master something new and useful.

Learn more

Dr. Yves J. Hilpisch is founder and CEO of The Python Quants, a group focusing on the use of open source technologies for financial data science, artificial intelligence, algorithmic trading, and computational finance. He is also the founder and CEO of The AI Machine, a company focused on AI-powered algorithmic trading based on a proprietary strategy execution platform.

Yves has a Diploma in Business Administration (with distinction), a Ph.D. in Mathematical Finance (magna cum laude) and is Adjunct Professor for Computational Finance.

Yves is the author of five books:

  • Python for Algorithmic Trading (2020, O’Reilly)
  • Artificial Intelligence in Finance (2020, O’Reilly)
  • Python for Finance (2018, 2nd ed., O’Reilly)
  • Listed Volatility and Variance Derivatives (2017, Wiley Finance)
  • Derivatives Analytics with Python (2015, Wiley Finance)

Yves is the director of the first online training program leading to University Certificates in Python for Algorithmic Trading and Computational Finance. He also lectures on computational finance, machine learning, and algorithmic trading at the CQF Program.

Yves is the originator of the financial analytics library DX Analytics and organizes Meetup group events, conferences, and bootcamps about Python, artificial intelligence, and algorithmic trading in London, New York, Frankfurt, Berlin, and Paris. He has given keynote speeches at technology conferences in the United States, Europe, and Asia.

oreillymedia

Insights and Advice for Software Developers, Data Scientists, and Engineers

oreillymedia

O’Reilly Media on Medium is a space curated by O’Reilly editors, offering advice, insights, viewpoints and experiences on tech.

O'Reilly Media

Written by

O'Reilly Media spreads the knowledge of innovators through its books, video training, webcasts, events, and research.

oreillymedia

O’Reilly Media on Medium is a space curated by O’Reilly editors, offering advice, insights, viewpoints and experiences on tech.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store