Join the Quant Scientist Newsletter

Gain access to exclusive tools that Wall Street's Elite don't want you to have. Don't miss the next issue...

Join 11,500+ Quant Scientists learning one article at a time

Join 11,500+ Quant Scientists learning one article at a time

Polars for Algorithmic Trading and Quantitative Finance

10X Faster Algorithmic Trading and Quantitative Finance with Polars

July 19, 20246 min read

Python is insane for finance! In this QS Newsletter (get the code), we are showing how to do algorithmic trading and quantitative finance data manipulations in Python 10X faster using a new library called Polars. Today, you learn:

Disclaimer:

The information and educational material provided by Quant Science, LLC are for educational purposes only and should not be considered as financial advice or recommendations to purchase, hold, or sell any securities or other financial instruments. Before you proceed, please review our full disclaimer here.

Polars for Quant Finance

Join the Quant Scientist Newsletter (and Get the Code)

Want exclusive access to our FULL codebase for this Quant Science tutorial plus dozens more? The code is in the QS018 Folder. Join here:

Quant Scientist Newsletter - Get the Code

NEW: Free 5-Day Algorithmic Trading Course

5 Day Algorithmic Trading Course

Are you interested in learning Algorithmic Trading with Python? Do you want to learn how to execute trades automatically, how to find edge, backtest trading strategies, analyze risk, then take your winning trades from Paper Account to Production (Live Trading)?

If the answer is Yes, then we have a NEW Free 5-Day Algorithmic Trading.  

👉 Click here to join our free 5-Day Algorithmic Trading Course.

What is Polars (And Why Is It So Fast)?

According to the polars documentation:

The polars package for R gives users access to a lightning fast Data Frame library written in Rust. Polars’ embarrassingly parallel execution, cache efficient algorithms and expressive API makes it perfect for efficient data wrangling, data pipelines, snappy APIs, and much more besides. Polars also supports “streaming mode” for out-of-memory operations. This allows users to analyze datasets many times larger than RAM.

Why this is important to quants and algorithmic traders:

  1. Polars is designed for fast data manipulation including grouped aggregations, rolling calculations, and expanding calculations, which are common in time series and financial analysis

  2. Polars is super fast because it's built on top of Rust (a language that is as fast and in some cases faster than C++)

  3. Polars is built for scale (it uses parallel execution, and handles data that is larger than memory)

  4. You don't need anything other than Python to run it (Polars Rust implementation is transportable with a compiler so no extra build tools are required)

But how can we use Polars for algorithmic trading and quant finance?

That's where this tutorial will help.

Full Tutorial: How to do algorithmic trading signals and Quant Finance Analysis 10X Faster with Polars

Ok, let's dive in and see how to use Polars for algo trading signals and quant finance analysis. First, make sure to sign up for our Newsletter to get all of the code you see today.

Part 1: Download Stock Data from Yfinance for Stanley Druckenmiller's Portfolio (Top 25 Assets)

The code below downloads stock price data for the 25 top holdings from Stanley Druckenmiller's Portfolio (Duquesne Capital Management, LLC) valued at $4.39 Billion Assets Under Management (AUM) as of when this article was produced.

Stanley Druckenmiller Portfolio

Run this code from the "QS018-polars" Folder to download stock data from the 13F filing:

libraries and data

This produces a Polars data frame. Here's what the data looks like:

Polars Stock Data

Key Points:

  1. This Polars Data Frame is in the "wide" format. We will normally pivot the data into the "long format" to perform data analysis by group.

  2. This looks like Pandas, but it's not. It's Polars. You can tell because the data types are listed along with the data shape. Also there is no index with polars data frames.

Part 2: 10X Faster Algorithmic Trading Signals (Rolling Calculations)

Rolling calculations are a staple for algorithmic trading for signal development. Unfortunately, they take a long time to process especially for many time series groups (in finance, each stock symbol is a group).

Fortunately, Polars is extremely fast. In fact, it's between 10X and 3500X faster than Pandas.

Wide to Long Format

Run this code to convert the wide data into long format. We need long format so we can do grouped analysis (i.e. by stock symbol).

Wide to Long Format

Visualize Prices Over Time

We can visualize the Stock Prices Over Time using 1 line of code in polars. Run this code:

Prices over time

Fast Algorithmic Trading Signals (10-Day and 50-Day Moving Averages)

Next, run this code to perform 10-day and 50-day moving averages for 25 stocks in a few milliseconds (about 10X faster than Pandas):

Fast Algorithmic Trading Signals

Visualize the Trading Signals

We can quickly visualize the trading signals for one of the stocks. Run this code to visualize NVDA:

Visualize Trading Signals

You can see how fast the rolling averages were performed, and how quickly we can then develop trading signals with Polars.

Next, let's cover a common Quant Finance task...

Part 3: Rolling Sharpe Ratio for 10X Larger Quantitive Finance Stock Screening and Feature Engineering

A common task in Quant Finance is investigating the rolling Sharpe Ratio for tens of thousands of stocks. The rolling sharpe can be used as a screening tool or as a feature in financial machine learning models.

50-Day Rolling Sharpe Ratio by Stock

We can do this fast with polars. Run this code to calculate the returns by stock and then the 50-Day rolling Sharpe Ratio by stock:

Rolling Sharpe Ratio

50-Day Rolling Sharpe Plot (25 Stocks)

Next, run this code to visualize the 50-Day rolling Sharpe Ratio for each of the 25 stocks.

50-Day Rolling Sharpe Plot

There you have it-- An easy way to screen stocks by rolling Sharpe Ratio and add a rolling Sharpe Ratio to your Algorithmic Machine Learning models. With Polars we can scale this to 100,000s of assets.

Conclusion: Polars is insane for Finance

Polars is insane for finance. We've used Polars to perform fast rolling calculations for algorithmic trading signals and to create scalable rolling sharpe ratios for screening and machine learning trading models. The best part-- We can scale this to 100,000+ stocks.

Are you interested in learning active investing strategies that use algorithms to maximize returns responsibly, help you manage risk, and grow your investments? We implement 3 core trading strategies including portfolio, momentum, and spread trades that have worked in our favor in the past and continue to produce results for our students.

Learn with 250+ of us that are learning to apply python to algorithmic trading to grow investments.

Leo was up 11.5% in just 13 trading days.

Leo up 13pct

Alex was waiting 9 years for a course like this:

testimonial

Ready to make Algorithmic Trading Strategies that actually work?

There's nothing worse than going at this alone--

Learning Python is tough.

❌ Learning Trading is tough.

Learning Math & Stats is tough.

It's no wonder why it's easy to feel lost, make bad decisions, and lose money.

Want help?

Python for Algorithmic Trading Course

👉 Join 10,700+ future Quant Scientists on our Python for Algorithmic Trading Course Waitlist: https://learn.quantscience.io/python-algorithmic-trading-course-waitlist

button course waitlist

investingstockspythonalgorithmic tradingsoftwarepolars
Matt is a Data Science expert with over 18 years working in business and 10+ years as a Data Scientist, Consultant, and Trainer. Matt has built Business Science, a successful educational platform with similar goals to Quant Science, but focused on developing Data Scientists in business, marketing, and finance disciplines.

Matt Dancho

Matt is a Data Science expert with over 18 years working in business and 10+ years as a Data Scientist, Consultant, and Trainer. Matt has built Business Science, a successful educational platform with similar goals to Quant Science, but focused on developing Data Scientists in business, marketing, and finance disciplines.

Back to Blog

Start Your Journey To Becoming A Quant Today!

Join the Quant Scientist Newsletter

Gain access to exclusive tools that Wall Street's Elite don't want you to have. Don't miss the next issue...

Join 11,500+ Quant Scientists learning one article at a time

Join 11,500+ Quant Scientists learning one article at a time

© 2024 Quant Science - All Rights Reserved

Cohort 6 launches Wednesday, October 2nd at 10AM EST