5.2 KiB
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.
from openbb_terminal.sdk import openbb from openbb_terminal.sdk import TerminalStyle
theme = TerminalStyle("light", "light", "light")
Load historical stock data for JPM and SPY over the specified date range
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
asset = data["Adj Close"].JPM benchmark = data["Adj Close"].SPY
Calculate daily returns for JPM and SPY, dropping any missing values
asset_returns = asset.pct_change().dropna() benchmark_returns = benchmark.pct_change().dropna()
Calculate the rolling variance of benchmark returns over a 30-day window
bm_var = benchmark_returns.rolling( window=30 ).var()
Calculate the rolling covariance between asset returns and benchmark returns over a 30-day window
bm_cov = benchmark_returns.rolling( window=30 ).cov(asset_returns)
Compute the rolling beta values by dividing the rolling covariance by the rolling variance
beta = bm_cov / bm_var
Calculate the Treynor ratio by adjusting the returns of the asset against its beta
treynor = ( asset_returns - benchmark_returns ) / beta
Display the calculated Treynor ratio
treynor
Plot the Treynor ratio over time to visualize its trend
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.
