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

Financial Functions in Python (with ffn)

Quantitative Finance Functions in Python (with ffn)

September 22, 20244 min read

Python is wild for quantitative finance and algorithmic trading! In this QS Newsletter (get the code), we are showing how to do financial performance analysis in Python with the ffn package.

What You’ll Learn:

  1. How to retrieve and analyze financial data using ffn.

  2. Performance analysis, drawdowns, and returns visualization.

  3. Bonus: Extracting and displaying key statistics as a DataFrame.

Sample Portfolio:

  • Assets: AAPL, GOOGL, MSFT, JPM, NVDA

  • Date Range: January 2023 - September 2024

BONUS: Get the Python Code for EVERYTHING you see in this post

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.

Financial Functions for Python with the ffn Package

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 QS020 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.

Financial Functions for Python with the ffn Package

Ok, let's dive in and see how to use the ffn package to perform quantitative finance analysis in Python. First, make sure to sign up for our Newsletter to get all of the code you see today.

Step 1: Load the Libraries, Data, and Get Price Data

In the first step, we'll import the necessary Python libraries, collect stock data for each asset using yfinance, and then convert them to returns. Run this code:

Libraries and Data

Sign up for our Newsletter to get all of the code you see today

This returns the daily closing prices for each stock symbol:

Daily Stock Prices

Step 2: Performance Analysis at a Glance

Next, let's complete a quick performance analysis. We'll use calc_stats(), which gives a complete performance breakdown of your assets, summarizing returns, volatility, Sharpe ratios, and more.

Performance Breakdown:

  • Sharpe Ratio: Measures risk-adjusted return.

  • Max Drawdown: Largest peak-to-trough decline during the time period.

  • Total Return: The overall percentage gain or loss. Run this code:

Run this code:

Performance at a Glance

Step 3: Lookback Returns

Visualize and analyze lookback returns over different time periods such as MTD, 3 Month, 6 Month, YTD, 1Y, 3Y, 5Y, and 10Y. Perfect for making client reports. Run this code:

Lookback Returns

Step 4: Monthly Returns by Asset

Another thing I love about ffn is how easy it is to make performance reports by month. Run this code:

Monthly Returns by Asset

Step 5: Get Performance, Asset Return Correlations, and Drawdowns

  • Performance Plots can help you understand which assets or portfolios are growing the fastest compared to benchmarks and other assets. ffn makes it easy to make performance plots.

  • Correlations can help you understand the interrelationships between different assets in the portfolio. ffn makes it easy to visualize these with heatmaps.

  • Drawdowns are a critic metric in risk management. ffn makes it easy to visualize drawdown plots.

Run this code:

Performance, Correlations, and Drawdowns

Step 6 (BONUS): Get all of the stats as a data frame

One thing that bugged me is that I want the key performance stats as a data frame. This is useful when I want to store information about trades in a database or post-process performance analysis. I can get the data by running this code:

How to get the performance metrics as a data frame

Conclusion: ffn makes it easy to financial performance analysis

Congrats! You just learned how to create a comprehensive financial performance analysis in Python using the ffn package. But, there's more to learn in algorithmic trading:

  • Backtesting your portfolio construction algorithm to make sure the strategy will work in the future

  • Executing the trades automatically

  • Monthly rebalancing

  • Tracking your actual Profit and Loss

  • Incorporating Trading Fees

Are you interested in learning algorithmic trading strategies that 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.

Join 400+ 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 tradingsoftwareffn
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

Next Cohort Launch: Wednesday, January 15th at 10AM EST