# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernel_info:
#     name: python3
#   kernelspec:
#     argv:
#     - C:/Users/<NAME>/Anaconda3\python.exe
#     - -m
#     - ipykernel_launcher
#     - -f
#     - '{connection_file}'
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] nteract={"transient": {"deleting": false}}
# # List of Basic Regressions

# + [markdown] nteract={"transient": {"deleting": false}}
# # Linear Regression

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
import pandas as pd
import numpy as np
import scipy.stats as stats
from statsmodels import regression
from statsmodels import regression, stats
import scipy as sp
import statsmodels.api as sm
import math

import matplotlib.pyplot as plt
import seaborn as sns

import warnings
warnings.filterwarnings("ignore")

import yfinance as yf
yf.pdr_override()

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
start = '2018-01-01'
end = '2022-01-01'
market1 = 'SPY'
market2 = '^IXIC'
symbol1 = 'AMD'
symbol2 = 'INTC'

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
asset1 = yf.download(symbol1, start=start, end=end)['Adj Close']
asset2 = yf.download(symbol2, start=start, end=end)['Adj Close']
benchmark = yf.download(market1, start=start, end=end)['Adj Close']


# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
def linreg(X,Y):
    # Running the linear regression
    X = sm.add_constant(X)
    model = regression.linear_model.OLS(Y, X).fit()
    a = model.params[0]
    b = model.params[1]
    X = X[:, 1]

    # Return summary of the regression and plot results
    X2 = np.linspace(X.min(), X.max(), 100)
    Y_hat = X2 * b + a
    plt.scatter(X, Y, alpha=0.3) # Plot the raw data
    plt.plot(X2, Y_hat, 'r', alpha=0.9);  # Add the regression line, colored in red
    plt.xlabel('X Value')
    plt.ylabel('Y Value')
    return model.summary()



# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
r_a = asset1.pct_change()[1:].dropna()
r_b = benchmark.pct_change()[1:].dropna()

linreg(r_b.values, r_a.values)

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
sns.regplot(r_b.values, r_a.values)


# + [markdown] nteract={"transient": {"deleting": false}}
# # Regression Model Instability

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
def linreg(X,Y):
    x = sm.add_constant(X) # Add a row of 1's so that our model has a constant term
    model = regression.linear_model.OLS(Y, x).fit()
    return model.params[0], model.params[1] # Return the coefficients of the linear model


# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
breakpoint = 100
xs = np.arange(len(asset1))
xs2 = np.arange(breakpoint)
xs3 = np.arange(len(asset1) - breakpoint)

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
a, b = linreg(xs, asset1)
a2, b2 = linreg(xs2, asset1[:breakpoint])
a3, b3 = linreg(xs3, asset1[breakpoint:])

Y_hat = pd.Series(xs * b + a, index=asset1.index)
Y_hat2 = pd.Series(xs2 * b2 + a2, index=asset1.index[:breakpoint])
Y_hat3 = pd.Series(xs3 * b3 + a3, index=asset1.index[breakpoint:])

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
asset1.plot()
Y_hat.plot(color='y')
Y_hat2.plot(color='r')
Y_hat3.plot(color='g')
plt.title(symbol1 + ' Price')
plt.ylabel('Price')

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
b1 = yf.download(market1, start=start, end=end)['Adj Close']
b2 = yf.download(market2, start=start, end=end)['Adj Close']

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
mlr = regression.linear_model.OLS(asset1, sm.add_constant(np.column_stack((b1, b2)))).fit()
prediction = mlr.params[0] + mlr.params[1]*b1 + mlr.params[2]*b2
print('Constant:', mlr.params[0], 'MLR beta to S&P 500:', mlr.params[1], ' MLR beta to MDY', mlr.params[2])

# Plot the asset pricing data and the regression model prediction, just for fun
asset1.plot()
prediction.plot()
plt.title(symbol1 + ' ')
plt.ylabel('Price')
plt.legend(['Asset', 'Linear Regression Prediction'])

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Compute Pearson correlation coefficient
sp.stats.pearsonr(b1,b2)[0] # Second return value is p-value

# + [markdown] nteract={"transient": {"deleting": false}}
# # Multiple Linear Regression

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
slr = regression.linear_model.OLS(asset1, sm.add_constant(asset2)).fit()
print('SLR beta of stock2:', slr.params[1])

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Run multiple linear regression using asset2 and SPY as independent variables
mlr = regression.linear_model.OLS(asset1, sm.add_constant(np.column_stack((asset2, benchmark)))).fit()

prediction = mlr.params[0] + mlr.params[1]*asset2 + mlr.params[2]*benchmark
prediction.name = 'Prediction'

print('MLR beta of asset2:', mlr.params[1], '\nMLR beta of S&P 500:', mlr.params[2])

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Plot the three variables along with the prediction given by the MLR
asset1.plot(label=symbol1)
asset2.plot(label=symbol2)
benchmark.plot(label=market1)
prediction.plot(color='r', label='Prediction')
plt.title(symbol1 + ' & ' + symbol2 + ' Price')
plt.xlabel('Price')
plt.legend(bbox_to_anchor=(1,1), loc=2)

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
# Plot only the dependent variable and the prediction to get a closer look
asset1.plot(label = symbol1)
prediction.plot(color='y')
plt.xlabel('Price')
plt.title(symbol1 + ' Price')
plt.legend()

# + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
mlr.summary()

StarcoderdataJupyterScriptsDedupFiltered