Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: pub@towardsai.net
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab VeloxTrend Ultrarix Capital Partners Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Our 15 AI experts built the most comprehensive, practical, 90+ lesson courses to master AI Engineering - we have pathways for any experience at Towards AI Academy. Cohorts still open - use COHORT10 for 10% off.

Publication

Risk-Adjusted Returns with Python (Part 2): Sharpe Ratio versus Treynor Ratio (Friends or Foes)
Data Science   Latest   Machine Learning

Risk-Adjusted Returns with Python (Part 2): Sharpe Ratio versus Treynor Ratio (Friends or Foes)

Last Updated on September 23, 2025 by Editorial Team

Author(s): Siddharth Mahato

Originally published on Towards AI.

Two legendary metrics for measuring risk-adjusted performance. Which one should you trust for your portfolio?

Introduction

In Part 1, we analyzed and understood about the Treynor Ratio, a metric to measure investment performance based on systemic risk (Beta). However, the Treynor Ratio is not the only metric in the quant’s toolbox, as it has a more famous friend: the Sharpe ratio. So, which ratio is the better measure? As we will find out, it is not a matter of which one is better than the other, but is more a matter of context. This section will compare the two ratios against one another. We will write some Python code to calculate both ratios for specific real market data, visualize the data in charts, and then, at the end of the article, provide a framework for establishing which ratio to use, and when.

Let’s dive in.

The Core Difference: A Tale of Two Risks

The main difference in the two ratios is in their definitions and assessments of risk.

The Sharpe ratio (William F. Sharpe, 1966) considers total risk, or risk measured by standard deviation. It provides you an indication of the excess return you are receiving for all your volatility.

Formula:

Risk-Adjusted Returns with Python (Part 2): Sharpe Ratio versus Treynor Ratio (Friends or Foes)

The Treynor ratio (Jack L. Treynor, 1965) considers systematic risk, or risk measured by Beta. It provides you an indication of the excess return you are receiving for the risk you are taking, in the market.

Formula:

There is no right or wrong answer here. The million dollar question is do you care about all risk (Sharpe) or just the market risk (Treynor)? The answer is totally dependent upon how well diversified your portfolio is.

Python Showdown: Calculating Both Ratios

Let’s put theory into practice. We’ll use Python to calculate both ratios for three assets: Apple (AAPL), Tesla (TSLA), and the S&P 500 ETF (SPY). We’ll use SPY as our market benchmark.

Step 1: Importing all the libraries and Get Data

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Download data
tickers = ['AAPL', 'TSLA', 'SPY']
data = yf.download(tickers, start ='2020-01-01', end ='2023-01-01')['Close']
returns = data.pct_change().dropna()

# Set annual risk-free rate (e.g., 10-Year Treasury Avg)
risk_free_rate = 0.02

Step 2: Calculation of Key Metrics

annual_returns = returns.mean() * 252
annual_volatility = returns.std() * np.sqrt(252)

# Calculate Beta for each asset (for Treynor)
market_returns = returns['SPY'] # Using SPY as the market proxy
betas = {}

for ticker in tickers:
covariance = np.cov(returns[ticker], market_returns)[0][1]
market_variance = np.var(market_returns)
beta = covariance / market_variance
betas[ticker] = beta

betas_series = pd.Series(betas)

Step 3: Compute the Ratios

# Calculate Sharpe Ratio
sharpe_ratios = (annual_returns - risk_free_rate) / annual_volatility

# Calculate Treynor Ratio
treynor_ratios = (annual_returns - risk_free_rate) / betas_series

# Create a comparison DataFrame
comparison_df = pd.DataFrame({
'Annual Return': annual_returns,
'Annual Volatility': annual_volatility,
'Beta': betas_series,
'Sharpe Ratio': sharpe_ratios,
'Treynor Ratio': treynor_ratios
})

print(comparison_df.round(3))
Source: Image by Author (Output)

Interpretation

What Do the Numbers Indicate?
> Tesla (TSLA) posted the best rate of return (0.592) but also exhibited the most volatility and much higher Beta. TSLA had the highest Sharpe Ratio and Treynor Ratio, meaning it delivered the most reward per unit of risk during this particular bullish period. However, that risk might hurt if the market turns down.
> Apple (AAPL) had a respectable Sharpe Ratio (0.78), meaning it provided a satisfactory (good) total return in relation to its total volatility. However, its Treynor Ratio (0.215) is considerably less than TSLA’s, which means that, while Apple was an efficient investment overall, it was a less efficient use of capital than TSLA when considering the returns for the market risk taken on.
> SPY had the lowest ratios. This is understandable — SPY is the most widely accepted “market” benchmark, representing the average risk-adjusted return. This serves as a reminder that the goal of active management is to improve on these ratios.
Point to Remember: Note that SPY’s Sharpe Ratio (0.457) is greater than its Treynor Ratio (0.101). This indicates that in this period of this study, SPY’s volatility (total risk) was less than the Beta-adjusted risk premium of the other active risk portfolios. When building a diversified portfolio, the Sharpe Ratio (representing risk) will usually present a more positive picture than the Treynor Ratio (market-based risk).

So, Which Ratio Should You Use?

The choice isn’t arbitrary. Use this decision tree:

Source: Image by Author
  • The Sharpe Ratio should be used when you are evaluating a single asset, or a concentrated portfolio like a couple of stocks. The ratio penalizes idiosyncratic risk (specific to that asset) — that is the risk you are fully exposed to.
  • The Treynor Ratio should be used when you are evaluating a well-diversified fund or a portfolio manager’s performance. The Treynor Ratio assumes that you’ve already diversified away unsystematic risk, and you only care about exposure to the market.

Bonus Tip: Let’s vizualise the graph
A graph takes the numeric result you gave in the abstract table and turns it into an instant and intuitive understanding. It’s the difference between telling someone the numbers versus showing them the story! In the case of an article on comparative risk-adjusted returns, a visualization is not just a nice-to-have, it is a very effective means of communicating your key argument and a powerful tool for making it stick. Let’s talk about why (and how) you can do this very well.

“Without data, you’re just another person with an opinion.”
— W. Edwards Deming

# Setting up the figure and axes for a dual bar chart
fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (5, 5))
fig.suptitle('Sharpe vs. Treynor Ratio Comparison (2020-2022)', fontweight = 'bold', fontsize = 16)

# Plot 1: Sharpe Ratio
x_pos = np.arange(len(sharpe_ratios))
ax1.bar(x_pos, sharpe_ratios.values, color = ['#1f77b4', '#ff7f0e', '#2ca02c']) # REMOVED () after .values
ax1.set_xticks(x_pos)
ax1.set_xticklabels(sharpe_ratios.index)
ax1.set_ylabel('Ratio Value')
ax1.set_title('Sharpe Ratio (Risk = Volatility)')
ax1.grid(axis = 'y', linestyle = '--', alpha = 0.7)
# Add value labels on top of the bars
for i, v in enumerate(sharpe_ratios.values):
ax1.text(i, v + 0.01, str(round(v, 2)), ha = 'center', fontweight = 'bold')
# Plot 2: Treynor Ratio
ax2.bar(x_pos, treynor_ratios.values, color = ['#1f77b4', '#ff7f0e', '#2ca02c']) # REMOVED () after .values
ax2.set_xticks(x_pos)
ax2.set_xticklabels(treynor_ratios.index)
ax2.set_ylabel('Ratio Value')
ax2.set_title('Treynor Ratio (Risk = Beta)')
ax2.grid(axis = 'y', linestyle ='--', alpha = 0.7)
# Add value labels on top of the bars
for i, v in enumerate(treynor_ratios.values):
ax2.text(i, v + 0.01, str(round(v, 2)), ha = 'center', fontweight = 'bold')

plt.tight_layout()
plt.show()
Source: Image by Author (Visualization)

Visual Storytelling: Analyzing the Numbers

The double bar chart above encapsulates the story we constructed with the numbers. Here are the findings from the chart:
> Tesla (TSLA) Rank Highest on Both Metrics: The orange bars illustrate that on both of the risk-adjusted return measures — whether we use Volatility to define risk (Sharpe) or Beta (Treynor) — TSLA had the best risk-adjusted returns. While that agrees with our understanding of TSLA as a high-risk, high-reward investment in this bull market period, the chart visually reinforces this story.
> The Story of the S&P 500 (SPY): The green bars in particular, are a perfect visual definition of the distinction between the two ratios. SPY had a respectable Sharpe Ratio reflecting SPY lower volatility (relative to TSLA) to justify it, but it also had the lowest Treynor Ratio. This is simply because SPY is the benchmark of the market (Beta = 1) and the “market return” was simply the market return. The Treynor Ratio simply determines the return based on that mark, which means it had no excess return relative to itself, so it received a low score on that metric.
> Meanwhile, Apple (AAPL): AAPL landed perfectly in the middle for both ratios: a balanced risk/return profile regardless of how you measure risk. As you can see, total risk versus just market risk certainly changes the assessment of investment rankings, and this visual comparison drives the point home.

Conclusion: Selecting Your Lens to Analyze Risk

We’ve been through the risk-adjusted return exercise and come away with two analytical tools that are both powerful and separate: the Sharpe Ratio and the Treynor Ratio. These are not competing answers; rather they are two different answers to two different questions.
The Sharpe Ratio asks: “What was the return for every unit of total risk I incurred?” This is the fundamental measure for the individual investor. The trader, or whoever is examining an asset or concentrated portfolio where each and every unit of volatility is meaningful.
The Treynor Ratio asks: “What was the return for every unit of market risk I incurred?” This is the most appropriate lens for the institutional investor, the fund analyst, or anyone examining a well-diversified portfolio where they have eliminated unsystematic risk, and are left with only exposure to the market. The visual example and Python code we’ve created support the point: the same investment can tell a very different story, depending on the lens you select. Tesla was a stellar performer through either lens during the period we examined; the S&P 500 told us a story of market average efficiency. There is no “correct” ratio, only the most correct ratio for your context and situation.

Happy Learning and Analyzing…

Thank you for reading my article. If you enjoyed reading it do show some appreciation by hitting the clap button.

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.