Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Rolling Sharpe and Sortino Ratios – Python Code

3 min read

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 delve into 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: Balancing Risk and Reward

The Sharpe ratio, developed by Nobel laureate William F. Sharpe, 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.

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.

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()

Conclusion

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.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

[Course] Designing a Stock Market Trading Dashboard App using…

Designing a Stock Market App using Python is a hands-on course that guides you through the development of a functional stock market application. Over...
Rajandran R
1 min read

Exploring the Essential Python Libraries for Data Analytics

Python has emerged as a powerhouse due to its versatility, ease of use, and extensive library support. Whether you're manipulating data, visualizing trends, performing...
Rajandran R
3 min read

Integrating Tradingview Lightweight Charts with Yahoo Finance Data –…

Hey traders! If you’re looking for a way to visualize your stock data dynamically and interactively, you’re in for a treat. Today, we’ll explore...
Rajandran R
2 min read

Leave a Reply

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