Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Rolling Sharpe and Sortino Ratios – Python Code

7 min read

This post gives you Python code to calculate the rolling Sharpe and Sortino ratio of the Nifty index and plot both over time. A rolling ratio recalculates risk-adjusted return over a moving window (here one trading year), so you can see when the index was rewarding risk well and when it was not. The original 2023 script is kept below, followed by an updated 2026 version that works with current yfinance releases, annualises the ratios and computes downside deviation correctly.

Key Takeaways

  • Sharpe ratio = average excess return divided by the standard deviation of returns; Sortino ratio uses only downside deviation in the denominator.
  • A rolling window (252 trading days = one year) turns a single number into a time series that shows how risk-adjusted performance changes with market regimes.
  • Multiply daily ratios by the square root of 252 to annualise them, so they are comparable with the Sharpe ratios quoted by fund houses.
  • Recent yfinance versions return adjusted prices in the Close column and no longer include Adj Close by default, so the original script needs a small change.
  • Rolling ratios are descriptive. They tell you how the past year looked, not what the next year will bring.

In the realm of investment, gauging performance and risk is paramount. Two metrics stand out for their effectiveness in measuring the risk-adjusted returns of an investment: the Sharpe ratio and the Sortino ratio. When applied on a rolling basis, these ratios provide a dynamic and nuanced view of an investment’s performance over time. In this blog post, we’ll look at why these rolling metrics are crucial for investors and how Python can be employed to calculate and visualize them for the Nifty index.

The Sharpe ratio, developed by Nobel laureate William F. Sharpe (Nobel Memorial Prize in Economic Sciences, 1990), measures the performance of an investment compared to a risk-free asset, after adjusting for its risk. It’s a simple yet powerful way to understand whether the returns of an investment are due to smart decision-making or a result of taking on excessive risk.

Python for traders, the quick way in

BEGINNER FRIENDLY · RATED 5.0

Python for traders, the quick way in

A crash course that gets you from zero to writing your own market data scripts.

  • Python basics with market examples
  • Fetch, clean and chart price data
  • Lifetime access
Start learning →by Marketcalls

The Rolling Sharpe Ratio: A Dynamic Perspective

While the traditional Sharpe ratio gives a single snapshot, the rolling Sharpe ratio provides a moving picture, recalculating the ratio over a fixed period as new data comes in. This rolling calculation offers a more immediate and ongoing analysis of the risk-adjusted performance, allowing investors to spot trends, volatility, and the impact of market events on investment returns.

The Sortino Ratio: Focusing on Downside Risk

The Sortino ratio modifies the Sharpe ratio by considering only downside volatility. This is particularly useful for investors who are more concerned about the potential for losses than the volatility from upside gains.

The Rolling Sortino Ratio: Timely Insights on Downside Exposure

Similar to the rolling Sharpe, the rolling Sortino ratio provides an evolving measure of downside risk. By focusing on the negative fluctuations in investment returns, investors can get a clearer understanding of how often and how severely their investments are losing value.

Rolling Sharpe and Sortino Ratio Formulas

For a window of n daily returns r and a daily risk-free rate rf:

Sharpe  = sqrt(252) * mean(r - rf) / std(r - rf)
Sortino = sqrt(252) * mean(r - rf) / sqrt( mean( min(r - rf, 0)^2 ) )

The downside deviation in the Sortino ratio uses every day in the window, with positive excess returns set to zero. Calculating the standard deviation of only the negative days, as many quick scripts do, gives a different (and usually smaller) number and also changes the effective window length.

Calculating Rolling Ratios with Python: A Practical Guide

Python, a powerful programming language, enables us to compute these rolling ratios efficiently. Using libraries such as yfinance for fetching financial data and seaborn for visualization, we can analyze and plot the metrics over time. Let’s break down the process.

Step 1: Fetching the Data

The yfinance library is utilized to download historical price data for the Nifty index. This provides us with a DataFrame containing the daily closing prices, which is the foundation for our calculations.

Step 2: Daily Returns and Excess Returns

We compute the daily returns of the Nifty index, which is the percentage change in price from one day to the next. Since we’re considering the risk-free rate as zero for simplicity, our excess returns are the same as the daily returns.

Step 3: The Rolling Ratios

For the rolling Sharpe ratio, we calculate the mean of the excess returns over a rolling window and divide it by the standard deviation of the excess returns over that same window. This gives us a measure of how much excess return is received per unit of volatility or risk.

The rolling Sortino ratio is similar, but it only considers negative returns in its calculation of downside risk. We first isolate the downside returns and then calculate the mean and the standard deviation of these downside returns over the rolling window.

Step 4: Visualization with Seaborn

With seaborn, a statistical data visualization library, we plot the Nifty index prices along with the rolling Sharpe and Sortino ratios on separate axes. This visualization provides a clear and concurrent view of how the risk-adjusted performance has evolved over time.

Python Code in Action

The Python code provided below takes you through the entire process, from data retrieval to plotting the results. It is a concise script that leverages Python’s power to perform financial analysis.

import yfinance as yf
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Fetch NIFTY data
nifty = yf.download('^NSEI', start='2019-01-01')

# Calculate daily returns
nifty['Daily Return'] = nifty['Adj Close'].pct_change()

# Define the rolling window
rolling_window = 252  # assuming 252 trading days in a year

# Calculate Rolling Sharpe Ratio assuming risk-free rate is zero
# (Change '0' to your desired annualized risk-free interest rate)
risk_free_rate = 0.0
nifty['Rolling Sharpe'] = (nifty['Daily Return'].rolling(window=rolling_window).mean() - risk_free_rate) / nifty['Daily Return'].rolling(window=rolling_window).std()

# Calculate daily return downside deviation for Sortino Ratio
negative_returns = nifty['Daily Return'][nifty['Daily Return'] < 0]
nifty['Downside Deviation'] = negative_returns.rolling(window=rolling_window).std()

# Calculate Rolling Sortino Ratio
nifty['Rolling Sortino'] = (nifty['Daily Return'].rolling(window=rolling_window).mean() - risk_free_rate) / nifty['Downside Deviation']

# Drop NaN values from the dataframe to avoid issues during plotting
nifty.dropna(inplace=True)

# Set the aesthetic style of the plots
sns.set(style="whitegrid")

# Create subplots
fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)

# Plot Nifty Index
sns.lineplot(ax=axes[0], data=nifty, x=nifty.index, y='Adj Close', color='blue').set_title('NIFTY Index')

# Plot Rolling Sharpe Ratio
sns.lineplot(ax=axes[1], data=nifty, x=nifty.index, y='Rolling Sharpe', color='green').set_title('Rolling Sharpe Ratio')

# Plot Rolling Sortino Ratio
sns.lineplot(ax=axes[2], data=nifty, x=nifty.index, y='Rolling Sortino',color='red').set_title('Rolling Sortino Ratio')

# Set the title for the entire figure
plt.suptitle("NIFTY Performance Metrics")

# Adjust the layout
plt.tight_layout(rect=[0, 0.03, 1, 0.95])

# Display the plot
plt.show()

Notes on the Original Code (2023)

The script above was written for yfinance as it was in 2023. If you run it today, three things are worth knowing:

  1. No Adj Close column: newer versions of yfinance download with auto_adjust=True by default, so prices in Close are already adjusted and nifty['Adj Close'] raises a KeyError. Columns also come back as a two-level index (field, ticker) unless you pass multi_level_index=False.
  2. Downside deviation: negative_returns.rolling(window=252) rolls over the last 252 negative days, which can stretch across two or more calendar years, rather than over the last 252 trading days.
  3. Daily, not annual, ratios: the ratios are not multiplied by the square root of 252, and the comment suggests entering an annual risk-free rate that is then subtracted from a daily return. Both are fixed in the updated version.

Updated Version (2026): Rolling Sharpe and Sortino Ratio in Python

This version was tested with yfinance 1.8 and pandas. It uses the adjusted Close column, converts an annual risk-free rate to a daily rate, annualises both ratios and computes downside deviation over the same 252-day window.

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Fetch Nifty 50 daily data (recent yfinance versions adjust prices by default,
# so use 'Close' and flatten the single-ticker column index)
nifty = yf.download('^NSEI', start='2019-01-01', auto_adjust=True,
                    multi_level_index=False, progress=False)

window = 252              # one trading year
rf_annual = 0.0           # annual risk-free rate, e.g. 0.065 for 6.5%
rf_daily = rf_annual / 252

returns = nifty['Close'].pct_change().dropna()
excess = returns - rf_daily

# Rolling Sharpe ratio (annualised)
roll_mean = excess.rolling(window).mean()
roll_std = excess.rolling(window).std()
rolling_sharpe = np.sqrt(252) * roll_mean / roll_std

# Rolling Sortino ratio (annualised): downside deviation uses every day in the
# window, with positive excess returns set to zero
downside = excess.clip(upper=0)
downside_dev = np.sqrt((downside ** 2).rolling(window).mean())
rolling_sortino = np.sqrt(252) * roll_mean / downside_dev

metrics = pd.DataFrame({'Close': nifty['Close'],
                        'Rolling Sharpe': rolling_sharpe,
                        'Rolling Sortino': rolling_sortino}).dropna()
print(metrics.tail())

fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)
metrics['Close'].plot(ax=axes[0], color='blue', title='Nifty 50')
metrics['Rolling Sharpe'].plot(ax=axes[1], color='green', title='Rolling 1-year Sharpe ratio')
metrics['Rolling Sortino'].plot(ax=axes[2], color='red', title='Rolling 1-year Sortino ratio')
for ax in axes[1:]:
    ax.axhline(0, color='grey', linewidth=0.8)
plt.suptitle('Nifty 50 Rolling Risk-Adjusted Performance')
plt.tight_layout()
plt.show()

To use a risk-free rate, set rf_annual to the current yield of a short-term government security such as the 91-day T-bill. To analyse a stock, ETF or your own strategy equity curve, replace the price series and keep the rest of the code unchanged. Change window to 126 for a six-month view or 63 for a quarterly view; shorter windows react faster but are noisier.

How to Read Rolling Sharpe and Sortino Charts

  • Above 1 (annualised): the past year delivered good return for the volatility taken. Long, smooth rallies push the rolling Sharpe ratio up.
  • Between 0 and 1: positive but modest risk-adjusted returns, typical of choppy markets.
  • Below 0: the index lost money (or underperformed the risk-free rate) over the window.
  • Sortino well above Sharpe: most volatility came from up moves; the downside has been limited.
  • Sortino close to Sharpe: falls were as large as rises, so downside risk dominated.

Sharp drops in the rolling ratios often coincide with corrections, and the ratios recover with a lag because the window still contains the bad period. For the theory behind the two measures, see the difference between the Sharpe ratio and Sortino ratio, and for full strategy tear sheets with these metrics, see enhancing backtesting metrics with QuantStats.

Frequently Asked Questions

What is a rolling Sharpe ratio?

It is the Sharpe ratio recalculated every day over a fixed look-back window, such as the last 252 trading days. Plotting it shows how risk-adjusted performance changes over time instead of giving one number for the whole period.

How do you calculate the Sortino ratio in Python?

Compute daily excess returns, set positive values to zero, take the square root of the mean of the squared values to get downside deviation, then divide the mean excess return by it. Multiply by the square root of 252 to annualise. The updated code above does this on a rolling basis with pandas.

What is a good Sharpe ratio?

As a rough guide, an annualised Sharpe ratio above 1 is considered good and above 2 is very good, but it depends on the asset class and period. Compare like with like, for example a fund against its benchmark over the same window.

Why does my yfinance code give KeyError: ‘Adj Close’?

Recent yfinance versions download with auto_adjust=True by default, so the Close column is already adjusted and there is no Adj Close column. Use Close, or pass auto_adjust=False if you need both.

Final Word

The rolling Sharpe and Sortino ratios are indispensable tools for the modern investor. They allow for a temporal analysis of an investment’s performance, providing insights that static, point-in-time ratios cannot. By understanding and utilizing these rolling metrics, investors can make more informed decisions, manage risks better, and strive for superior risk-adjusted returns.

Python, with its vast ecosystem of data analysis and visualization libraries, offers an accessible and efficient way to calculate and plot these metrics. Whether you’re a seasoned financial analyst or an individual investor, the ability to harness these tools can significantly enhance your investment analysis process.

If you are new to the data side, start with this guide to analysing stock market data with yfinance.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More