Algorithmic Trading for Beginners
Last updated
Last updated
Technology has become an asset in finance. Financial institutions are now evolving into technology companies rather than just staying occupied with the financial aspects of the field.
Mathematical Algorithms bring about innovation and speed. They can help us gain a competitive advantage in the market.
The speed and frequency of financial transactions, together with the large data volumes, has drawn a lot of attention towards technology from all the big financial institutions.
Algorithmic or Quantitative trading is the process of designing and developing trading strategies based on mathematical and statistical analyses. It is an immensely sophisticated area of finance.
This tutorial serves as the beginnerâs guide to quantitative trading with Python. Youâll find this post very helpful if you are:
A student or someone aiming to become a quantitative analyst (quant) at a fund or bank.
Someone who is planning to start their own quantitative trading business.
Weâll go over the following topics in this post:
Basics of stocks and trading
Extracting data from Quandl API
Exploratory data analysis on stock pricing data
Moving averages
Formulating a trading strategy with Python
Visualizing the performance of the strategy
Before we deep dive into the details and dynamics of stock pricing data, we must first understand the basics of finance. If you are someone who is familiar with finance and how trading works, you can skip this section and click here to go to the next one.
A stock is a representation of a share in the ownership of a corporation, which is issued at a certain amount. It is a type of financial security that establishes your claim on a companyâs assets and performance.
An organization or company issues stocks to raise more funds/capital in order to scale and engage in more projects. These stocks are then publicly available and are sold and bought.
The process of buying and selling existing and previously issued stocks is called stock trading. There is a price at which a stock can be bought and sold, and this keeps on fluctuating depending upon the demand and the supply in the share market.
Depending on the companyâs performance and actions, stock prices may move up and down, but the stock price movement is not limited to the companyâs performance.
Traders pay money in return for ownership within a company, hoping to make some profitable trades and sell the stocks at a higher price.
Another important technique that traders follow is short sellingâ. This involves âborrowing shares and immediately selling them in the hope of buying them up later at a lower price, returning them to the lender, and making the margin.
So, most traders follow a plan and model to trade. This is known as a trading strategy.
Quantitative traders at hedge funds and investment banks design and develop these trading strategies and frameworks to test them. It requires profound programming expertise and an understanding of the languages needed to build your own strategy.
Python is one of the most popular programming languages used, among the likes of C++, Java, R, and MATLAB. It is being adopted widely across all domains, especially in data science, because of its easy syntax, huge community, and third-party support.
Youâll need familiarity with Python and statistics in order to make the most of this tutorial. Make sure to brush up on your Python and check out the fundamentals of statistics.
In order to extract stock pricing data, weâll be using the Quandl API. But before that, letâs set up the work environment. Hereâs how:
In your terminal, create a new directory for the project (name it however you want):
Make sure you have Python 3 and virtualenv installed on your machine.
Create a new Python 3 virtualenv using virtualenv <env_name>
and activate it using source <env_name>/bin/activate
.
Now, install jupyter-notebook using pip, and type in pip install jupyter-notebook
in the terminal.
Similarly, install the pandas
, quandl
, and numpy
packages.
Run your jupyter-notebook
from the terminal.
Now, your notebook should be running on localhost like the screenshot below:
You can create your first notebook by clicking on the New
dropdown on the right. Make sure you have created an account on Quandl. Follow the steps mentioned here to create your API key.
Once youâre all set, letâs dive right in:
Pandas is going to be the most rigorously used package in this tutorial as weâll be doing a lot of data manipulation and plotting.
After the packages are imported, we will make requests to the Quandl API by using the Quandl package:
Here we have Microsoftâs EOD stock pricing data for the last 9 years. All you had to do was call the get
method from the Quandl package and supply the stock symbol, MSFT, and the timeframe for the data you need.
This was really simple, right? Letâs move ahead to understand and explore this data further.
With the data in our hands, the first thing we should do is understand what it represents and what kind of information it encapsulates.
Printing the DataFrameâs info, we can see all that it contains:
As seen in the screenshot above, the DataFrame contains DatetimeIndex, which means weâre dealing with time-series data.
An index can be thought of as a data structure that helps us modify or reference the data. Time-series data is a sequence of snapshots of prices taken at consecutive, equally spaced intervals of time.
In trading, EOD stock pricing data captures the movement of certain parameters about a stock, such as the stock price, over a specified period of time with data points recorded at regular intervals.
Looking at other columns, letâs try to understand what each column represents:
Open/CloseâââCaptures the opening/closing price of the stock
Adj_Open/Adj_CloseâââAn adjusted opening/closing price is a stockâs price on any given day of trading that has been revised to include any dividend distributions, stock splits, and other corporate actions that occurred at any time before the next dayâs open.
VolumeâââIt records the number of shares that are being traded on any given day of trading.
High/LowâââIt tracks the highest and the lowest price of the stock during a particular day of trading.
These are the important columns that we will focus on at this point in time.
We can learn about the summary statistics of the data, which shows us the number of rows, mean, max, standard deviations, and so on. Try running the following line of code in the Ipython cell:
Pandasâ resample() method is used to facilitate control and flexibility on the frequency conversion of the time series data. We can specify the time intervals to resample the data to monthly, quarterly, or yearly, and perform the required operation over it.
This is an interesting way to analyze stock performance in different timeframes.
A financial return is simply the money made or lost on an investment. A return can be expressed nominally as the change in the amount of an investment over time. It can be calculated as the percentage derived from the ratio of profit to investment.
We have the pct_change() at our disposal for this purpose. Here is how you can calculate returns:
This will print the returns that the stock has been generating on a daily basis. Multiplying the number by 100 will give you the percentage change.
The formula used in pct_change() is:
Return = {(Price at t)âââ(Price at t-1)} / {Price at t-1}
Now, to calculate monthly returns, all you need to do is:
After resampling the data to months (for business days), we can get the last day of trading in the month using the apply()
function.
apply()
takes in a function and applies it to each and every row of the Pandas series. The lambda
function is an anonymous function in Python which can be defined without a name, and only takes expressions in the following format:
For example, lambda x: x * 2
is a lambda function. Here, x is the argument and x * 2
is the expression that gets evaluated and returned.
The concept of moving averages is going to build the base for our momentum-based trading strategy.
In finance, analysts often have to evaluate statistical metrics continually over a sliding window of time, which is called moving window calculations.
Letâs see how we can calculate the rolling mean over a window of 50 days, and slide the window by 1 day.
This is the magical function which does the tricks for us:
Youâll see the rolling mean over a window of 50 days (approx. 2 months). Moving averages help smooth out any fluctuations or spikes in the data, and give you a smoother curve for the performance of the company.
We can plot and see the difference:
You can now plot the rolling mean():
And you can see the difference for yourself, how the spikes in the data are consumed to give a general sentiment around the performance of the stock.
Here comes the final and most interesting part: designing and making the trading strategy. This will be a step-by-step guide to developing a momentum-based Simple Moving Average Crossover (SMAC) strategy.
Momentum-based strategies are based on a technical indicator that capitalizes on the continuance of the market trend. We purchase securities that show an upwards trend and short-sell securities which show a downward trend.
The SMAC strategy is a well-known schematic momentum strategy. It is a long-only strategy. Momentum, here, is the total return of stock including the dividends over the last n months. This period of n months is called the lookback period.
There are 3 main types of lookback periods: short term, intermediate-term, and long term. We need to define 2 different lookback periods of a particular time series.
A buy signal is generated when the shorter lookback rolling mean (or moving average) overshoots the longer lookback moving average. A sell signal occurs when the shorter lookback moving average dips below the longer moving average.
Now, letâs see how the code for this strategy will look:
Letâs see whatâs happening here. We have created 2 lookback periods. The short lookback period short_lb
is 50 days, and the longer lookback period for the long moving average is defined as a long_lb
of 120 days.
We have created a new DataFrame which is designed to capture the signals. These signals are being generated whenever the short moving average crosses the long moving average using the np.where
. It assigns 1.0
for true and 0.0
if the condition comes out to be false.
The positions
columns in the DataFrame tells us if there is a buy signal or a sell signal, or to stay put. We're basically calculating the difference in the signals column from the previous row using diff.
And there we have our strategy implemented in just 6 steps using Pandas. Easy, wasn't it?
Now, letâs try to visualize this using Matplotlib. All we need to do is initialize a plot figure, add the adjusted closing prices, short, and long moving averages to the plot, and then plot the buy and sell signals using the positions column in the signal_df
above:
Now, you can clearly see that whenever the blue line (short moving average) goes up and beyond the orange line (long moving average), there is a pink upward marker indicating a buy signal.
A sell signal is denoted by a black downward marker where thereâs a fall of the short_mav
below long_mav
.
Quantopian is a Zipline-powered platform that has manifold use cases. You can write your own algorithms, access free data, backtest your strategy, contribute to the community, and collaborate with Quantopian if you need capital.
Here is an explanation of the above metrics:
Total return: The total percentage return of the portfolio from the start to the end of the backtest.
Specific return: The difference between the portfolioâs total returns and common returns.
Common return: Returns that are attributable to common risk factors. There are 11 sector and 5 style risk factors that make up these returns. The Sector Exposure and Style Exposure charts in the Risk section provide more detail on these factors.
Sharpe: The 6-month rolling Sharpe ratio. It is a measure of risk-adjusted investment. It is calculated by dividing the portfolioâs excess returns over the risk-free rate by the portfolioâs standard deviation.
Max Drawdown: The largest drop of all the peak-to-trough movement in the portfolioâs history.
Volatility: Standard deviation of the portfolioâs returns.
Pat yourself on the back as you have successfully implemented your quantitative trading strategy!
Now that your algorithm is ready, youâll need to backtest the results and assess the metrics mapping the risk involved in the strategy and the stock. Again, you can use BlueShift and Quantopian to learn more about backtesting and trading strategies.
Quantra is a brainchild of QuantInsti. With a range of free and paid courses by experts in the field, Quantra offers a thorough guide on a bunch of basic and advanced trading strategies.
Data Science CourseâââThey have rolled out an introductory course on Data Science that helps you build a strong foundation for projects in Data Science.
Trading Courses for BeginnersâââFrom momentum trading to machine and deep learning-based trading strategies, researchers in the trading world like Dr. Ernest P. Chan are the authors of these niche courses.
Free Resources
To learn more about trading algorithms, check out these blogs:
Quantstartâââthey cover a wide range of backtesting algorithms, beginner guides, and more.
Investopediaâââeverything you want to know about investment and finance.
Quantivityâââdetailed mathematical explanations of algorithms and their pros and cons.
Warren Buffet says he reads about 500 pages a day, which should tell you that reading is essential in order to succeed in the field of finance.
Embark upon this journey of trading and you can lead a life full of excitement, passion, and mathematics.
With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:
These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science.
Explained Mathematics and derivations of why we do what we do in ML and Deep Learning.
Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.
Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google.
Reference : https://www.freecodecamp.org/news/algorithmic-trading-in-python/
Running the above cell in the Jupyter notebook would yield a plot like the one below:
We have written an algorithm to backtest our SMA strategy, and here are the results:
https://quantra.quantinsti.com/learning-track/algorithmic-trading-for-everyone?utm_source=harshit_tyagi&utm_medium=affiliate&utm_campaign=lt_everyone