forked from ANGELTALAVERA/Finance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_regression_slope.py
90 lines (78 loc) · 2.55 KB
/
linear_regression_slope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Import dependencies
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
import datetime as dt
yf.pdr_override()
# input
symbol1 = "AAPL"
symbol2 = "QQQ"
start = dt.date.today() - dt.timedelta(days=365 * 2)
end = dt.date.today()
# Read data
df1 = yf.download(symbol1, start, end)
df2 = yf.download(symbol2, start, end)
avg1 = df1["Adj Close"].mean()
avg2 = df2["Adj Close"].mean()
df1["AVGS1_S1"] = avg1 - df1["Adj Close"]
df1["AVGS2_S2"] = avg2 - df2["Adj Close"]
df1["Average_SQ"] = df1["AVGS1_S1"] ** 2
df1["AVG_AVG"] = df1["AVGS1_S1"] * df1["AVGS2_S2"]
sum_sq = df1["Average_SQ"].sum()
sum_avg = df1["AVG_AVG"].sum()
slope = sum_avg / sum_sq
intercept = avg2 - (slope * avg1)
m = (
(df1["Adj Close"] - df1["Adj Close"].mean())
* (df2["Adj Close"] - df2["Adj Close"].mean())
/ (df1["Adj Close"] - df1["Adj Close"].mean())
)
n = 20
df1["Slope"] = m.rolling(n).mean()
fig = plt.figure(figsize=(14, 7))
ax1 = plt.subplot(2, 1, 1)
ax1.plot(df1["Adj Close"])
ax1.set_title("Stock " + symbol1 + " Closing Price")
ax1.set_ylabel("Price")
ax1.legend(loc="best")
ax2 = plt.subplot(2, 1, 2)
# df1['VolumePositive'] = df1['Open'] < df1['Adj Close']
# colors = df1.VolumePositive.map({True: 'g', False: 'r'})
# ax2.bar(df1.index, df1['Volume'], color=colors, alpha=0.4)
ax2.plot(df1["Slope"], label="Slope")
ax2.grid()
ax2.set_ylabel("Slope")
ax2.set_xlabel("Date")
plt.show()
# ## Candlestick with Linear Regression Slope
from matplotlib import dates as mdates
dfc = df1.copy()
dfc["VolumePositive"] = dfc["Open"] < dfc["Adj Close"]
# dfc = dfc.dropna()
dfc = dfc.reset_index()
dfc["Date"] = mdates.date2num(dfc["Date"].tolist())
from mplfinance.original_flavor import candlestick_ohlc
fig = plt.figure(figsize=(14, 7))
ax1 = plt.subplot(2, 1, 1)
candlestick_ohlc(ax1, dfc.values, width=0.5, colorup="g", colordown="r", alpha=1.0)
ax1.xaxis_date()
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y"))
ax1.grid(True, which="both")
ax1.minorticks_on()
ax1v = ax1.twinx()
colors = dfc.VolumePositive.map({True: "g", False: "r"})
ax1v.bar(dfc.Date, dfc["Volume"], color=colors, alpha=0.4)
ax1v.axes.yaxis.set_ticklabels([])
ax1v.set_ylim(0, 3 * df1.Volume.max())
ax1.set_title("Stock " + symbol1 + " Closing Price")
ax1.set_ylabel("Price")
ax2 = plt.subplot(2, 1, 2)
# df1['VolumePositive'] = df1['Open'] < df1['Adj Close']
# colors = df1.VolumePositive.map({True: 'g', False: 'r'})
# ax2.bar(df1.index, df1['Volume'], color=colors, alpha=0.4)
ax2.plot(df1["Slope"], label="Slope")
ax2.grid()
ax2.set_ylabel("Slope")
ax2.set_xlabel("Date")
plt.show()