Financial Analysis in Python with ffn

`

Savvy Investors Know Where to Get Their News—Do You?

Here’s the truth: Most financial media focuses on clicks, not clarity. The Daily Upside, created by Wall Street insiders, delivers valuable insights—free. Join 1M+ readers and subscribe today!

Exciting News: Paid Subscriptions Have Launched! 🚀

On September 1, we officially rolled out our new paid subscription plans at GuruFinance Insights, offering you the chance to take your investing journey to the next level! Whether you're just starting or are a seasoned trader, these plans are packed with exclusive trading strategies, in-depth research paper analysis, ad-free content, monthly AMAsessions, coding tutorials for automating trading strategies, and much more.

Our three tailored plans—Starter Investor, Pro Trader, and Elite Investor—provide a range of valuable tools and personalized support to suit different needs and goals. Don’t miss this opportunity to get real-time trade alerts, access to masterclasses, one-on-one strategy consultations, and be part of our private community group. Click here to explore the plans and see how becoming a premium member can elevate your investment strategy!

Check Out Latest Premium Articles

Financial analysis in Python has reached new heights, thanks to powerful libraries like ffn (Financial Functions for Python). If you’re exploring finance or data science, this library can save you time and simplify complex tasks. In this article, we’ll explore how ffn enables you to work with financial data, generate meaningful visualizations, and analyze performance metrics — all with minimal effort.

Let’s dive into the world of financial analysis with ffn!

What is ffn?

ffn is a Python library designed for quick and straightforward financial data analysis. It provides tools for pulling data, calculating returns, visualizing performance, and much more — all in just a few lines of code.

In this guide, we’ll cover:

  1. Getting financial data.

  2. Analyzing return distributions.

  3. Comparing performance metrics.

  4. Exploring historical drawdowns.

1. Getting Financial Data and Plotting

The first step in financial analysis is gathering data. With ffn, you can easily pull stock prices and compare their performance over time.

Here’s how to get started:

import ffn
%matplotlib inline

# Download price data for Apple and Microsoft from Yahoo! Finance
prices = ffn.get('aapl,msft', start='2010-01-01')

# Rebase prices to compare relative performance
ax = prices.rebase().plot(figsize=(10, 5))

What’s happening here:

  • ffn.get(): Fetches historical price data (adjusted close prices by default).

  • Rebase: Aligns the starting values of both stocks for easy comparison.

This will generate a clean chart showing how Apple and Microsoft have performed relative to each other since 2010.

2. Displaying a Returns Histogram

Want to understand how often stocks gain or lose? A returns histogram provides insight into their distribution.

# Calculate daily returns and drop missing values
returns = prices.to_returns().dropna()

# Plot a histogram of returns
ax = returns.hist(figsize=(10, 5))

What’s happening here:

  • to_returns(): Converts price data into daily percentage changes.

  • Histogram: Visualizes the frequency of returns (gains and losses).

This plot helps you gauge the risk and volatility of your assets. Are returns mostly centered around zero, or do they have fat tails?

3. Comparing Performance Metrics

Understanding key performance metrics is crucial when comparing assets. With ffn, it’s incredibly simple:

# Calculate and display performance stats
stats = prices.calc_stats()
stats.display()

What’s happening here:

  • calc_stats(): Computes metrics like CAGR (Compound Annual Growth Rate), Sharpe ratio, maximum drawdown, and more.

  • display(): Outputs these metrics in a neatly formatted table.

This one-liner provides a wealth of insights, such as which stock offers better returns and which carries more risk.

4. Exploring Drawdowns

Drawdowns show how much an asset has fallen from its peak value — critical for assessing risk.

# Visualize drawdown series
ax = stats.prices.to_drawdown_series().plot(figsize=(10, 5))

What’s happening here:

  • to_drawdown_series(): Tracks the decline of asset prices from their peak over time.

This plot helps identify periods of significant losses and assess recovery times.

Why Use ffn?

ffn is perfect for beginners and professionals alike. Its concise syntax saves time, and its robust functionality ensures high-quality analysis. Whether you’re creating reports, exploring market trends, or backtesting strategies, ffn has got you covered.

Are UK stocks undervalued compared to their US counterparts?”

To explore this, we can analyze the performance of UK and US stock indices over the past decade using the ffn library in Python.

Step 1: Install and Import ffn

First, ensure you have the ffn library installed:

pip install ffn

Then, import the necessary libraries:

import ffn
import matplotlib.pyplot as plt

Step 2: Fetch Historical Data

We’ll retrieve data for the FTSE 100 (representing UK stocks) and the S&P 500 (representing US stocks) from Yahoo Finance:

# Define the tickers for FTSE 100 and S&P 500
tickers = '^FTSE,^GSPC'

# Fetch the data starting from January 1, 2015
data = ffn.get(tickers, start='2015-01-01')

Step 3: Rebase and Plot the Data

Rebasing allows us to compare the relative performance of both indices from a common starting point:

# Rebase the data to a common starting point
rebased_data = data.rebase()

# Plot the rebased data
rebased_data.plot(figsize=(10, 5))
plt.title('FTSE 100 vs. S&P 500 Performance (2015-2025)')
plt.ylabel('Rebased Price')
plt.show()

Step 4: Calculate Performance Metrics

To assess the performance, we can calculate key statistics:

# Calculate performance statistics
stats = data.calc_stats()

# Display the statistics
stats.display()

Interpreting the Results

By examining the plotted data and performance metrics, we can observe:

  • Total Return: Indicates the overall gain or loss over the period.

  • CAGR (Compound Annual Growth Rate): Shows the mean annual growth rate.

  • Volatility: Measures the price fluctuations.

  • Sharpe Ratio: Assesses risk-adjusted returns.

These metrics provide insights into whether UK stocks are undervalued compared to US stocks. A lower total return and CAGR for the FTSE 100 might suggest undervaluation, but it’s essential to consider other factors like economic conditions, currency fluctuations, and market sentiment.

By leveraging the ffn library, we can efficiently analyze and visualize financial data to inform investment decisions.

Copy and paste the code snippet into your Python environment to visualize the performance comparison between the FTSE 100 and S&P 500 indices.

import ffn
import matplotlib.pyplot as plt

# Define the tickers for FTSE 100 (^FTSE) and S&P 500 (^GSPC)
tickers = '^FTSE,^GSPC'

# Fetch the data starting from January 1, 2015
data = ffn.get(tickers, start='2015-01-01')

# Rebase the data to a common starting point
rebased_data = data.rebase()

# Plot the rebased data
plt.figure(figsize=(12, 6))
rebased_data.plot(ax=plt.gca())
plt.title('FTSE 100 vs. S&P 500 Performance (2015-2025)', fontsize=14)
plt.ylabel('Rebased Price', fontsize=12)
plt.xlabel('Date', fontsize=12)
plt.legend(['FTSE 100', 'S&P 500'], loc='upper left', fontsize=10)
plt.grid(visible=True, alpha=0.5)
plt.show()

Financial analysis no longer requires tedious code or complicated tools. With ffn, you can:

  • Quickly fetch financial data.

  • Generate insightful visualizations.

  • Analyze performance with confidence.

By following the examples above, you’re well on your way to mastering financial analysis in Python. So, fire up your Python environment, install ffn, and start exploring the financial markets with ease!