7.9 KiB
Load stock data and calculate daily returns¶
We start by loading stock data for three companies: Apple (AAPL), Microsoft (MSFT), and Google (GOOGL). We will use the adjusted closing prices from January 1, 2020, to January 1, 2022. Then, we calculate the daily returns for these stocks.
import pandas as pd import numpy as np import yfinance as yf import matplotlib.pyplot as plt
tickers = ['AAPL', 'MSFT', 'GOOGL'] data = yf.download(tickers, start='2020-01-01', end='2022-01-01')['Adj Close']
returns = data.pct_change().dropna()
We use the yf.download method from the yfinance library to fetch adjusted closing prices for the specified tickers and date range. The pct_change method calculates the daily returns, which represent the percentage change in stock prices from one day to the next. The dropna method ensures that we remove any missing values from our data. This step is crucial for accurate calculations in subsequent steps.
Calculate portfolio returns¶
Next, we will calculate the returns of a portfolio consisting of the three stocks. We assign specific weights to each stock and compute the portfolio returns based on these weights.
weights = np.array([0.4, 0.4, 0.2]) portfolio_returns = returns.dot(weights)
We create an array of weights that represent the proportion of the portfolio allocated to each stock: 40% to Apple, 40% to Microsoft, and 20% to Google. We then calculate the portfolio returns by taking the dot product of the daily returns and the weights. This gives us a time series of portfolio returns, which is the weighted sum of the individual stock returns for each day.
Calculate Sortino Ratio¶
We will now calculate the Sortino Ratio for the portfolio. The Sortino Ratio measures the risk-adjusted return, focusing only on downside risk. We first determine the excess returns over a risk-free rate and then compute the downside deviation.
risk_free_rate = 0.01 target_return = 0 excess_return = portfolio_returns - risk_free_rate / 252 downside_returns = excess_return[excess_return < 0] downside_deviation = np.std(downside_returns) sortino_ratio = np.mean(excess_return) / downside_deviation
We set the risk-free rate at 1% and assume a target return of 0. The excess return is calculated by subtracting the daily risk-free rate from the portfolio returns. We identify the downside returns, which are the negative excess returns, and compute the standard deviation of these downside returns to get the downside deviation. Finally, we calculate the Sortino Ratio by dividing the mean excess return by the downside deviation. This ratio helps us understand the portfolio's performance relative to the downside risk.
Plot portfolio returns and visualize the downside risk¶
Lastly, we will plot the portfolio returns and highlight the periods where the returns are below the target return. This will help us visualize the downside risk.
plt.figure(figsize=(12, 6)) plt.plot(portfolio_returns.index, portfolio_returns, label='Portfolio Returns') downside_returns = portfolio_returns[portfolio_returns < target_return] plt.fill_between(downside_returns.index, downside_returns, alpha=0.5, color='red', label='Downside Returns') plt.title('Portfolio Returns with Downside Risk Highlighted') plt.xlabel('Date') plt.ylabel('Returns') plt.legend() plt.show()
We create a plot with portfolio returns on the y-axis and dates on the x-axis. We use the plot method from matplotlib to visualize the portfolio returns. We then identify the dates where the returns are below the target return and highlight these periods using the fill_between method with a red fill color. The plot includes a title and labels for the axes, and a legend to distinguish between the portfolio returns and downside returns. This visualization helps us easily identify periods of negative performance.
Your next steps¶
Try changing the weights assigned to the stocks and observe how the portfolio returns and the Sortino Ratio change. You can also experiment with different time periods to see how the portfolio would have performed in various market conditions. This will give you a deeper understanding of portfolio performance and risk management.
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.
