Files
strategy-lab/to_explore/pyquantnews/36_TreynorRatio.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

5.2 KiB

No description has been provided for this image

This notebook calculates the Treynor ratio for a given stock and its benchmark index over time. It fetches historical price data for the specified stock and benchmark, computes daily returns, and calculates rolling beta values. The Treynor ratio is then derived using these beta values. This ratio helps in assessing the risk-adjusted performance of the asset relative to the benchmark, aiding in investment decision-making.

In [ ]:
from openbb_terminal.sdk import openbb
from openbb_terminal.sdk import TerminalStyle
In [ ]:
theme = TerminalStyle("light", "light", "light")

Load historical stock data for JPM and SPY over the specified date range

In [ ]:
data = openbb.stocks.load(
    "JPM, SPY",
    start_date="2014-01-01",
    end_date="2022-12-31"
)

Extract adjusted closing prices for JPM and SPY from the loaded data

In [ ]:
asset = data["Adj Close"].JPM
benchmark = data["Adj Close"].SPY

Calculate daily returns for JPM and SPY, dropping any missing values

In [ ]:
asset_returns = asset.pct_change().dropna()
benchmark_returns = benchmark.pct_change().dropna()

Calculate the rolling variance of benchmark returns over a 30-day window

In [ ]:
bm_var = benchmark_returns.rolling(
    window=30
).var()

Calculate the rolling covariance between asset returns and benchmark returns over a 30-day window

In [ ]:
bm_cov = benchmark_returns.rolling(
    window=30
).cov(asset_returns)

Compute the rolling beta values by dividing the rolling covariance by the rolling variance

In [ ]:
beta = bm_cov / bm_var

Calculate the Treynor ratio by adjusting the returns of the asset against its beta

In [ ]:
treynor = (
    asset_returns - benchmark_returns
) / beta

Display the calculated Treynor ratio

In [ ]:
treynor

Plot the Treynor ratio over time to visualize its trend

In [ ]:
treynor.plot()

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.