【问题标题】:Extending the trendline of a stock chart to the right将股票图表的趋势线向右延伸
【发布时间】:2021-10-25 09:22:15
【问题描述】:

我想将我绘制的这条趋势线延伸到右侧。 到目前为止的代码如下:

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()

这是输出图像:

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

    标签: pandas numpy matplotlib


    【解决方案1】:

    这是结合使用时间戳的非常简单的数学:

    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])
    

    输出:

    【讨论】:

    • 谢谢@mozway。你为什么把斜率转换成秒?
    • 要获得用于坡度划分的数字,您不能使用 TimeDelta 来划分数字
    • 注意。转换为秒的不是斜率,而是时间的增量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多