Python for Finance – Algorithmic Trading Tutorial for Beginners (2024)

/ #Python
Python for Finance – Algorithmic Trading Tutorial for Beginners (1)
Harsh*t Tyagi
Python for Finance – Algorithmic Trading Tutorial for Beginners (2)

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:

  1. A student or someone aiming to become a quantitative analyst (quant) at a fund or bank.
  2. 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.

What Are Stocks? What is Stock Trading?

Stocks

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.

Stock Trading and Trading Strategy

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.

Extracting data from the Quandl API

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:

  1. In your terminal, create a new directory for the project (name it however you want):
mkdir <directory_name>
  1. Make sure you have Python 3 and virtualenv installed on your machine.
  2. Create a new Python 3 virtualenv using virtualenv <env_name> and activate it using source <env_name>/bin/activate.
  3. Now, install jupyter-notebook using pip, and type in pip install jupyter-notebook in the terminal.
  4. Similarly, install the pandas, quandl, and numpy packages.
  5. Run your jupyter-notebook from the terminal.

Now, your notebook should be running on localhost like the screenshot below:

Python for Finance – Algorithmic Trading Tutorial for Beginners (3)

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:

# importing required packages
import pandas as pdimport quandl as q

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:

# set the API keyq.ApiConfig.api_key = "<API key>”
#send a get request to query Microsoft's end of day stock prices from 1st #Jan, 2010 to 1st Jan, 2019msft_data = q.get("EOD/MSFT", start_date="2010-01-01", end_date="2019-01-01")
# look at the first 5 rows of the dataframemsft_data.head()
Python for Finance – Algorithmic Trading Tutorial for Beginners (4)

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.

Exploratory Data Analysis on Stock Pricing Data

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:

Python for Finance – Algorithmic Trading Tutorial for Beginners (5)

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.

Important Terminology

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:

msft_data.describe()
Python for Finance – Algorithmic Trading Tutorial for Beginners (6)

resample()

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.

msft_data.resample('M').mean()
Python for Finance – Algorithmic Trading Tutorial for Beginners (7)

This is an interesting way to analyze stock performance in different timeframes.

Calculating returns

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:

# Import numpy packageimport numpy as np
# assign `Adj Close` to `daily_close`daily_close = msft_data[['Adj_Close']]
# returns as fractional changedaily_return = daily_close.pct_change()
# replacing NA values with 0daily_return.fillna(0, inplace=True)
print(daily_return)

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:

mdata = msft_data.resample('M').apply(lambda x: x[-1])monthly_return = mdata.pct_change()

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:

Lambda: expression

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.

Moving Averages in Trading

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.

rolling()

This is the magical function which does the tricks for us:

# assigning adjusted closing prices to adj_pricesadj_price = msft_data['Adj_Close']
# calculate the moving averagemav = adj_price.rolling(window=50).mean()
# print the resultprint(mav[-10:])
Python for Finance – Algorithmic Trading Tutorial for Beginners (8)

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:

# import the matplotlib package to see the plotimport matplotlib.pyplot as pltadj_price.plot()
Python for Finance – Algorithmic Trading Tutorial for Beginners (9)

You can now plot the rolling mean():

mav.plot()
Python for Finance – Algorithmic Trading Tutorial for Beginners (10)

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.

Formulating a Trading Strategy

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:

# step1: initialize the short and long lookback periodsshort_lb = 50long_lb = 120
# step2: initialize a new DataFrame called signal_df with a signal columnsignal_df = pd.DataFrame(index=msft_data.index)signal_df['signal'] = 0.0
# step3: create a short simple moving average over the short lookback periodsignal_df['short_mav'] = msft_data['Adj_Close'].rolling(window=short_lb, min_periods=1, center=False).mean()
# step4: create long simple moving average over the long lookback periodsignal_df['long_mav'] = msft_data['Adj_Close'].rolling(window=long_lb, min_periods=1, center=False).mean()
# step5: generate the signals based on the conditional statementsignal_df['signal'][short_lb:] = np.where(signal_df['short_mav'][short_lb:] > signal_df['long_mav'][short_lb:], 1.0, 0.0) 
# step6: create the trading orders based on the positions columnsignal_df['positions'] = signal_df['signal'].diff()signal_df[signal_df['positions'] == -1.0]

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:

# initialize the plot using pltfig = plt.figure()
# Add a subplot and label for y-axisplt1 = fig.add_subplot(111, ylabel='Price in $')
msft_data['Adj_Close'].plot(ax=plt1, color='r', lw=2.)
# plot the short and long lookback moving averagessignal_df[['short_mav', 'long_mav']].plot(ax=plt1, lw=2., figsize=(12,8))
# plotting the sell signalsplt1.plot(signal_df.loc[signal_df.positions == -1.0].index, signal_df.short_mav[signal_df.positions == -1.0],'v', markersize=10, color='k')
# plotting the buy signalsplt1.plot(signal_df.loc[signal_df.positions == 1.0].index, signal_df.short_mav[signal_df.positions == 1.0], '^', markersize=10, color='m') # Show the plotplt.show()

Running the above cell in the Jupyter notebook would yield a plot like the one below:

Python for Finance – Algorithmic Trading Tutorial for Beginners (11)

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.

Visualize the Performance of the Strategy on Quantopian

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.

We have written an algorithm to backtest our SMA strategy, and here are the results:

Python for Finance – Algorithmic Trading Tutorial for Beginners (12)

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!

Where to go From Here?

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.

Further Resources

Python for Finance – Algorithmic Trading Tutorial for Beginners (13)

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:

If this tutorial was helpful, you should check out my data science and machine learning courses on Wiplane Academy. They are comprehensive yet compact and helps you build a solid foundation of work to showcase.

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Python for Finance – Algorithmic Trading Tutorial for Beginners (14)
Harsh*t Tyagi

Web and Data Science Consultant | Instructional Design

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

I am Harsh*t Tyagi, a seasoned expert in the intersection of finance and technology, with a focus on quantitative trading and algorithmic strategies. Over the years, I have delved deep into the intricacies of mathematical algorithms in finance, particularly in designing and developing trading strategies. My expertise extends to utilizing programming languages such as Python for quantitative analysis and strategy implementation.

In the provided article, I cover the fundamental concepts of quantitative trading using Python. Let's break down the key concepts discussed:

  1. Introduction to Quantitative Trading:

    • Financial institutions are transitioning into technology companies, emphasizing the importance of technology in finance.
    • Mathematical algorithms drive innovation and speed in the financial field.
    • Algorithmic or Quantitative trading involves designing trading strategies based on mathematical and statistical analyses.
  2. Topics Covered in the Tutorial:

    • 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
  3. Understanding Stocks and Stock Trading:

    • Stocks represent ownership in a corporation, issued to raise funds for scaling projects.
    • Stock trading involves buying and selling existing stocks at fluctuating prices.
    • Traders follow trading strategies, including short selling, and quantitative analysts design these strategies.
  4. Role of Python in Quantitative Trading:

    • Python is a popular programming language for quantitative trading due to its easy syntax, community support, and third-party libraries.
    • Proficiency in Python and statistics is crucial for effective quantitative trading.
  5. Data Extraction from Quandl API:

    • Setting up the project environment using Python and Jupyter Notebook.
    • Utilizing the Quandl API to extract stock pricing data, specifically Microsoft's end-of-day stock prices for the last nine years.
  6. Exploratory Data Analysis (EDA) on Stock Pricing Data:

    • Understanding the structure of the data, which includes time-series data with columns like Open/Close, Adj_Open/Adj_Close, Volume, High/Low.
    • Performing summary statistics and using Pandas' resample() method to analyze stock performance in different timeframes.
  7. Calculating Returns:

    • Defining and calculating financial returns using the pct_change() method in Python.
  8. Moving Averages in Trading:

    • Introducing the concept of moving averages to smooth out fluctuations in stock data.
    • Calculating and plotting the rolling mean over a window of 50 days.
  9. Formulating a Trading Strategy:

    • Designing a momentum-based Simple Moving Average Crossover (SMAC) strategy in six steps using Python and Pandas.
    • Visualizing the strategy's performance using Matplotlib.
  10. Visualizing Performance on Quantopian:

    • Backtesting the SMA strategy on Quantopian, a Zipline-powered platform, and assessing metrics such as total return, specific return, Sharpe ratio, max drawdown, and volatility.
  11. Further Resources and Recommendations:

    • Encouraging readers to explore additional resources and courses on Quantra, data science, and trading for continuous learning.
    • Mentioning free resources like Quantstart, Investopedia, and Quantivity for deeper insights into trading algorithms and finance.

The tutorial concludes with a call to action, encouraging readers to subscribe for upcoming series covering the entire data science space, including Python fundamentals, mathematics in machine learning, podcasts with industry experts, and practical projects.

If you found this breakdown informative, consider exploring my data science and machine learning courses on Wiplane Academy for a comprehensive and practical learning experience.

Python for Finance – Algorithmic Trading Tutorial for Beginners (2024)

FAQs

Is Python enough for algo trading? ›

In general, Python is more commonly used in algo trading due to its versatility and ease of use, as well as its extensive community and library support. However, some traders may prefer R for its advanced statistical analysis capabilities and built-in functions.

How long does it take to learn Python for trading? ›

The duration to learn Python for finance ranges from one week to several months, depending on the depth of the course and your prior knowledge of Python programming and data science. Learning Python for finance requires a solid foundation in Python programming basics and an understanding of data science.

What is the best Python platform for algo trading? ›

Quantopian: Quantopian is another popular open source python platform for testing and developing trading ideas and strategies. It allocates capital for selected trading algorithms and you get a share of your algorithm's net profit.

How to learn Python coding for trading? ›

Learn Algorithmic Trading Using Python
  1. Unsupervised Learning Trading Strategy. The first part delves into the utilization of unsupervised learning for devising trading strategies. ...
  2. Twitter Sentiment Investing Strategy. ...
  3. Intraday Strategy Using GARCH Model.
Oct 26, 2023

Is algo trading always profitable? ›

Algo trading is not only profitable, but it also increases your odds of becoming a profitable trader., Algo trading is ideal for someone who wants to trade with their full-time job.

How successful are Algo traders? ›

Globally, 70-80 percent of market volumes come from algo trading and in India, algo trading has a 50 percent share of the entire Indian financial market (including stock, commodity and currency market).

Can I teach myself Python? ›

Yes, it's absolutely possible to learn Python on your own. Although it might affect the amount of time you need to take to learn Python, there are plenty of free online courses, video tips, and other interactive resources to help anyone learn to program with Python.

How fast can I learn Python and get a job? ›

If you're looking for a general answer, here it is: If you just want to learn the Python basics, it may only take a few weeks. However, if you're pursuing a data science career from the beginning, you can expect it to take four to twelve months to learn enough advanced Python to be job-ready.

Is it worth learning Python in 2024? ›

Python is undoubtedly one of the most popular languages, and it opens up so many different career paths that it is definitely worth learning.

Who is the most successful algo trader? ›

He built mathematical models to beat the market. He is none other than Jim Simons. Even back in the 1980's when computers were not much popular, he was able to develop his own algorithms that can make tremendous returns. From 1988 to till date, not even a single year Renaissance Tech generated negative returns.

Which Python library is used in algo trading? ›

PyAlgoTrade is a Python library for algorithmic trading. It allows developers to create trading strategies using a simple, expressive syntax.

What is the monthly fee for algo trading? ›

Algo Traders can activate the ProStocks Unlimited Trading Plan that charges zero brokerage on all intraday trades (Equity and F&O) by paying a monthly fee of Rs. 899.

How to learn Python for finance from scratch? ›

You can start by learning the Python programming basics, then progress to advanced Python uses, or you can explore classes that specialize in teaching the financial uses of Python programming.

How can a beginner make money in Python? ›

Building a website with Python can be a great way to make money. You can monetize your website by offering services such as web hosting, selling ads, or selling products and services related to your site's content. You can also use it to build powerful data analysis tools that you can offer for a fee.

How do I start learning algorithm trading? ›

Steps to Start Algo-Trading

For a start, you need to know your trade. You must be aware of where you are investing your money. A good amount of market and financial instrument research is required. If you know how to code or have an understanding of coding languages then you can explore more about algorithmic trading.

Can we automate trading using Python? ›

Python is a popular programming language in finance and trading due to its versatility and ease of use. By automating your trading strategy using Python, you can save time and reduce human errors while also enabling you to test and backtest your strategies more easily.

Which language is used to create algo trading? ›

What Programming Language Do Algorithmic Traders Use? Because it is highly efficient in processing high volumes of data, C++ is a popular programming choice among algorithmic traders.

Is Python used for high-frequency trading? ›

Advantages of Using Python for HFT: Rapid Development: Python is known for its ease of use and rapid development, allowing traders and developers to quickly prototype and implement trading strategies. Large Ecosystem: Python has a vast ecosystem of libraries and frameworks, such as NumPy, pandas, SciPy.

Is coding required for algo trading? ›

In conclusion, it can be said that possessing programming skills can be advantageous, but being an expert programmer is not a strict requirement for utilising algo trading. uTrade Algos provides an user-friendly interface and visual tools, enabling traders to design algorithms without in-depth coding expertise.

Top Articles
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 5810

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.