Issue
I want to extend this trendline that I have drawn to the right.
Following is the code:
import matplotlib.pyplot as plt
import yfinance as yf
df = yf.download('aapl', '2020-01-01', '2021-01-01')
df1 = df[df.index > '2020-06-01']
df2 = df[df.index < '2020-06-02']
lowest2 = df1[df1.Close == df1.Close.min()]
lowest1 = df2[df2.Close == df2.Close.min()]
fig, ax = plt.subplots(figsize= (10, 6))
ax.plot(df.index, df.Close)
ax.plot([lowest1.index[0], lowest2.index[0]], [lowest1.Low[0], lowest2.Low[0]])
ax.set_xlim(df.index[0], df.index[-1])
plt.show()
Solution
This is really simple maths combined with the use of Timestamps:
import matplotlib.pyplot as plt
import yfinance as yf
df = yf.download('aapl', '2020-01-01', '2021-01-01')
df1 = df[df.index > '2020-06-01']
df2 = df[df.index < '2020-06-02']
lowest2 = df1[df1.Close == df1.Close.min()]
lowest1 = df2[df2.Close == df2.Close.min()]
fig, ax = plt.subplots(figsize= (10, 6))
ax.plot(df.index, df.Close)
## calculating slope
x1, x2, y1, y2 = lowest1.index[0], lowest2.index[0], lowest1.Low[0], lowest2.Low[0]
slope = (y2-y1)/(x2-x1).total_seconds()
## extending line
x3 = pd.Timestamp('2020-10-01')
y3 = y1+(x3-x1).total_seconds()*slope
## plotting lines
ax.plot([x1, x2], [y1, y2])
ax.plot([x1, x3], [y1, y3], ls=':')
ax.set_xlim(df.index[0], df.index[-1])
output:
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.