Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

# abdallah abdelkarim

## stap by stap A Comprehensive Guide to Python Code for Measuring Investment Risks

# Import required dependencies


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import yfinance as yf
import datetime as dt

## Next, we’ll define the required variables for data collection:

ticker = "AAPL" # Ticker symbol for the desired asset


benchmark_ticker = "^GSPC" # Ticker symbol for the benchmark index
start_date = "2022–01–01" # Start date for obtaining historical price data
end_date = "2024–03–21" # End date for obtaining historical price data

# Fetch historical price data for the asset and benchmark from a reliable data source
asset_data = yf.download(ticker, start_date, end_date)
benchmark_data = yf.download(benchmark_ticker, start_date, end_date)

# Extract the "close" prices from the data


asset_prices = asset_data["Close"]
benchmark_prices = benchmark_data["Close"]

# Calculate the asset returns and benchmark returns


asset_returns = asset_prices.pct_change().dropna()
benchmark_returns = benchmark_prices.pct_change().dropna()

# Calculate the average return


average_return = asset_returns.mean()

[*********************100%%**********************] 1 of 1 completed

1 Failed download:
['AAPL']: ValueError("time data '2024–03–21' does not match format '%Y-%m-%d'")
[*********************100%%**********************] 1 of 1 completed

1 Failed download:
['^GSPC']: ValueError("time data '2024–03–21' does not match format '%Y-%m-%d'")

## Section 4: Calculating and Analyzing Risk Management Statistics

# Standard Deviation
standard_deviation = asset_returns.std()

# 4.1 Sharpe Ratio: Assessing Risk-Adjusted Returns

## The Sharpe ratio can be calculated using the following formula:

# Sharpe Ratio
risk_free_rate = 0.03 # Assume a risk-free rate of 3%
sharpe_ratio = (average_return - risk_free_rate) / standard_deviation

## 4.2 Sortino Ratio: Focusing on Downside Risk

## To calculate the Sortino ratio, we need to consider only negative returns. Here’s an example code snippet:

# Sortino Ratio
downside_returns = asset_returns[asset_returns < 0]
average_downside_return = downside_returns.mean()
sortino_ratio = (average_return - risk_free_rate) / downside_returns.std()

# 4.3 Beta
model = sm.OLS(asset_returns, sm.add_constant(benchmark_returns)).fit()
beta = model.params[1]

### 4.4 Max Drawdown: Assessing the Largest Decline in Investment Value

## To visualize and analyze max drawdown, we can plot a cumulative returns chart and calculate the maximum
# drawdown. Here’s an example code snippet:

# Max Drowdown
cum_returns = (asset_returns + 1).cumprod()
cum_max = cum_returns.cummax()
drawdown = (cum_max - cum_returns) / cum_max
plt.plot(drawdown)
plt.title('Max Drawdown')
plt.xlabel('Date')
plt.ylabel('Drawdown')
plt.show()
max_drawdown = drawdown.max()

## 4.5 Value at Risk (VaR): Estimating Potential Losses

## To calculate VaR, we can utilize historical simulation assuming future returns follow the historical
# distribution. Here’s an example code snippet:

# Value at Risk (VaR)


confidence_level = 0.95
var = np.percentile(asset_returns, 100 - confidence_level * 100)

## 4.6 Conditional Value at Risk (CVaR): Capturing Extreme Losses

# To calculate CVaR, we can use the tail portion of returns beyond the VaR level. Here’s an example code
# snippet:

# Conditional Value at Risk (CVaR)


tail_returns = asset_returns[asset_returns < var]
cvar = tail_returns.mean()

## 4.8 R-squared: Measuring the Correlation Between an Asset and a Benchmark

# To calculate R-squared, we can perform linear regression between the asset’s returns and the benchmark
# returns. Here’s an example code snippet:

# R-squared
model = sm.OLS(asset_returns, sm.add_constant(benchmark_returns)).fit()
r_squared = model.rsquared

#5 Complet code

# Import required dependencies


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import yfinance as yf
import datetime as dt

ticker = "AAPL" # Ticker symbol for the desired asset


benchmark_ticker = "^GSPC" # Ticker symbol for the benchmark index

start_date = dt.datetime.today() - dt.timedelta(days=365) # Start date for obtaining historical price data
end_date = dt.datetime.today() # End date for obtaining historical price data

# Fetch historical price data for the asset and benchmark from a reliable data source
asset_data = yf.download(ticker, start_date, end_date)
benchmark_data = yf.download(benchmark_ticker, start_date, end_date)

# Extract the "close" prices from the data


asset_prices = asset_data["Close"]
benchmark_prices = benchmark_data["Close"]

# Calculate the asset returns and benchmark returns


asset_returns = asset_prices.pct_change().dropna()
benchmark_returns = benchmark_prices.pct_change().dropna()

# Calculate the average return


average_return = asset_returns.mean()

# Standard Deviation
standard_deviation = asset_returns.std()

# Sharpe Ratio
risk_free_rate = 0.03 # Assume a risk-free rate of 3%
sharpe_ratio = (average_return - risk_free_rate) / standard_deviation

# Sortino Ratio
downside_returns = asset_returns[asset_returns < 0]
average_downside_return = downside_returns.mean()
sortino_ratio = (average_return - risk_free_rate) / downside_returns.std()

# Beta
model = sm.OLS(asset_returns, sm.add_constant(benchmark_returns)).fit()
beta = model.params[1]

# Max Drowdown
cum_returns = (asset_returns + 1).cumprod()
cum_max = cum_returns.cummax()
drawdown = (cum_max - cum_returns) / cum_max
plt.plot(drawdown)
plt.title('Max Drawdown')
plt.xlabel('Date')
plt.ylabel('Drawdown')
plt.show()
max_drawdown = drawdown.max()
# Value at Risk (VaR)
confidence_level = 0.95
var = np.percentile(asset_returns, 100 - confidence_level * 100)

# Conditional Value at Risk (CVaR)


tail_returns = asset_returns[asset_returns < var]
cvar = tail_returns.mean()

# R-squared
model = sm.OLS(asset_returns, sm.add_constant(benchmark_returns)).fit()
r_squared = model.rsquared

[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed

Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like