
Risk-Adjusted Returns with Python (Part 1): The Treynor Ratio
Last Updated on September 12, 2025 by Editorial Team
Author(s): Siddharth Mahato
Originally published on Towards AI.
“Risk comes from not knowing what you’re doing.” — Warren Buffett
Most investors chase returns. But ask any seasoned fund manager, and you’ll hear a different question:
“Am I being rewarded fairly for the risks I’m taking?”
That’s where risk-adjusted returns enter the scene. Over this two-part series, we’re going to take a look at metrics that are more than just raw returns.
Part 1 (this article) → We’ll start with the Treynor Ratio and implement it step by step using Python.
Part 2 → Will be comparing it with the Sharpe Ratio, which is more commonly used, and view both in action.
What is the Treynor Ratio?
The Treynor Ratio measures how much excess return (above the risk-free rate) a portfolio generates per unit of market risk (beta).
Formula:

Difference from Sharpe Ratio:
- Sharpe uses standard deviation (total risk).
- Treynor uses beta (systematic risk).
Interpretation:
- A higher Treynor Ratio means better compensation for market risk.
- Best used when comparing diversified portfolios or funds.
Python Implementation
Let’s bring this to life with an example of a real multi-national company ‘APPLE’.
Step 1: Importing all the necessary libraries
import pandas as pd
import numpy as np
import yfinance as yf
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
Step 2: Downloading and Loading Data
# Calculate daily returns from the 'Close' prices
portfolio_ticker = 'AAPL'
market_ticker = '^GSPC'
start_date = '2023-01-01'
end_date = '2024-01-01'
portfolio_data = yf.download(portfolio_ticker, start = start_date, end = end_date)
market_data = yf.download(market_ticker, start = start_date, end = end_date)
Step 3: Computing Stock Daily Returns
# Combine into single DataFrame
portfolio_returns = portfolio_data['Close'].pct_change().dropna()
market_returns = market_data['Close'].pct_change().dropna()
returns = pd.concat([portfolio_returns, market_returns], axis = 1)
returns.columns = ['AAPL', 'SP500']
returns = returns.dropna()

Step 4: Calculating Treynor Ratio
# Computation of Beta value
X = sm.add_constant(returns['SP500']) # Add constant for regression
y = returns['AAPL']
model = sm.OLS(y, X).fit()
beta = model.params['SP500']
print("Beta (Systematic Risk):", beta)
Outcome: Beta (Systematic Risk): 1.104513
# Define Risk-free Rate (annualized, e.g., 3% U.S. T-bills) ---
rf = 0.03 / 252 # convert annual 3% to daily risk-free rate
# Calculate average excess return of portfolio ---
excess_return = returns['AAPL'].mean() - rf
# Computation of Treynor Ratio ---
treynor_ratio = excess_return / beta
print("Treynor Ratio:", treynor_ratio)
To understand beta better, let’s visualize it using a regression plot.
# Regression Plot (AAPL vs SP500) ---
plt.figure(figsize = (8,6))
sns.regplot(x = returns['SP500'], y = returns['AAPL'], line_kws = {'color':'red'})
plt.title("Regression of AAPL on S&P500 (Beta Estimation)")
plt.xlabel("S&P500 Daily Returns")
plt.ylabel("AAPL Daily Returns")
plt.grid(True)
plt.show()

Interpretation
- If the slope (β) = 1, AAPL moves in line with the market.
- If β > 1, AAPL is more volatile than the market (amplifies market movements).
- If β < 1, AAPL is less volatile than the market.
Conculsion
In the first part we reviewed the Treynor Ratio, from its definition, use, and formula, to analyzing its application with a financial dataset. We saw its measures risk-adjusted returns in regards to systematic risk (beta), making it a viable metric for investors who are seeking to measure portfolio performance with respect to market movements, or risk factors.
“Information is the oxygen of the modern age.”
Similar to the life giving characteristic of oxygen, the information provides essentials for the decision-making process in finance. But information is not enough — we need to have tools that help us understand it, assess it and even compare it to other information. This is where performance ratios like the Sharpe Ratio and Treynor Ratio come in to the picture and ultimately bring focus and clarity to the cloudy decisions we are often making with investments.
As a base, we now get ready to take a more balanced view of portfolio performance evaluation. In Part 2, we will discuss the Sharpe Ratio, another common metric of portfolio performance which considers total risk, while we compare the Treynor Ratio and Sharpe Ratio as two metrics that may be more useful in some situations than others.
This will allow a better, more rounded picture of portfolio performance evaluation.
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.
Published via Towards AI
Take our 90+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!
Towards AI has published Building LLMs for Production—our 470+ page guide to mastering LLMs with practical projects and expert insights!

Discover Your Dream AI Career at Towards AI Jobs
Towards AI has built a jobs board tailored specifically to Machine Learning and Data Science Jobs and Skills. Our software searches for live AI jobs each hour, labels and categorises them and makes them easily searchable. Explore over 40,000 live jobs today with Towards AI Jobs!
Note: Content contains the views of the contributing authors and not Towards AI.