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

8.8 KiB

No description has been provided for this image

This code analyzes the relationship between Tesla (TSLA) and S&P 500 (SPY) returns using linear regression. It downloads historical price data for TSLA and SPY, calculates daily returns, and plots them. A linear regression model is then used to estimate the alpha and beta of TSLA in relation to SPY. The code also constructs and evaluates a beta-hedged portfolio combining TSLA and SPY returns.

In [ ]:
import numpy as np
from statsmodels import regression
import statsmodels.api as sm
import matplotlib.pyplot as plt
import yfinance as yf

Download historical price data for TSLA and SPY from Yahoo Finance

In [ ]:
data = yf.download("TSLA, SPY", start="2014-01-01", end="2015-01-01")

Extract adjusted close prices for TSLA and SPY

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

Calculate daily returns for TSLA and SPY and drop any missing values

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

Plot daily returns for TSLA and SPY

In [ ]:
asset_returns.plot()
benchmark_returns.plot()
plt.ylabel("Daily Return")
plt.legend()

Extract daily returns values for linear regression analysis

In [ ]:
X = benchmark_returns.values
Y = asset_returns.values
In [ ]:
def linreg(x, y):
    """Perform linear regression on two arrays.
    
    This function adds a constant to x, performs linear regression, 
    and returns the alpha and beta coefficients.
    
    Parameters
    ----------
    x : np.ndarray
        The independent variable (e.g., benchmark returns).
    y : np.ndarray
        The dependent variable (e.g., asset returns).
    
    Returns
    -------
    alpha : float
        The intercept of the regression line.
    beta : float
        The slope of the regression line.
    """

    # Add a column of 1s to fit alpha
    x = sm.add_constant(x)

    # Fit the OLS regression model to the data
    model = regression.linear_model.OLS(y, x).fit()

    # Remove the constant now that we're done
    x = x[:, 1]

    return model.params[0], model.params[1]

Calculate alpha and beta for TSLA relative to SPY using linear regression

In [ ]:
alpha, beta = linreg(X, Y)
print(f"Alpha: {alpha}")
print(f"Beta: {beta}")

Generate a range of X values for plotting the regression line

In [ ]:
X2 = np.linspace(X.min(), X.max(), 100)

Calculate the predicted Y values (regression line) for the generated X values

In [ ]:
Y_hat = X2 * beta + alpha

Plot the raw data points (TSLA vs. SPY daily returns)

In [ ]:
plt.scatter(X, Y, alpha=0.3)
plt.xlabel("SPY Daily Return")
plt.ylabel("TSLA Daily Return")

Plot the regression line on the scatter plot

In [ ]:
plt.plot(X2, Y_hat, 'r', alpha=0.9);

Construct a beta-hedged portfolio by combining TSLA and SPY returns

In [ ]:
portfolio = -1 * beta * benchmark_returns + asset_returns
portfolio.name = "TSLA + Hedge"

Plot the returns of the beta-hedged portfolio, TSLA, and SPY

In [ ]:
portfolio.plot(alpha=0.9)
benchmark_returns.plot(alpha=0.5)
asset_returns.plot(alpha=0.5)
plt.ylabel("Daily Return")
plt.legend();

Print the mean and standard deviation of the beta-hedged portfolio and TSLA returns

In [ ]:
print("means: ", portfolio.mean(), asset_returns.mean())
print("volatilities: ", portfolio.std(), asset_returns.std())

Extract portfolio values for further linear regression analysis

In [ ]:
P = portfolio.values

Calculate alpha and beta for the beta-hedged portfolio using linear regression

In [ ]:
alpha, beta = linreg(X, P)
print('alpha: ' + str(alpha))
print('beta: ' + str(beta))

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.