【问题标题】:how to draw outside mplfinance plot?如何绘制外部 mplfinance 情节?
【发布时间】:2021-02-24 20:05:14
【问题描述】:
from datetime import datetime, timedelta, date
import pandas_datareader as pdr
import mplfinance as mpf
    
df_history = pdr.get_data_yahoo(symbols='GOLD', 
                                    start=datetime(2020, 8, 30), 
                                    end=datetime(2021, 2, 23))
    
# Today is: 24.02.2021
two_points  = [(datetime(2020, 8, 30),28.72),(datetime(2021, 3, 26),23.49)]
mpf.plot(df_history, type='candle', alines=two_points)

我收到错误消息:

ValueError: User specified line date "2020-08-30 00:00:00" is before (less than) range of plotted data (2020-08-31 00:00:00 to 2021-02-23 00:00:00)

有没有办法在范围之外绘制?

【问题讨论】:

    标签: python plot mplfinance


    【解决方案1】:

    解决方法是设置show_nontrading=True

    我用你的代码测试过,修改为:

    mpf.plot(df_history, type='candle', alines=two_points, show_nontrading=True)
    

    得到

    这不适用于show_nontrading=False(如果未指定,则为默认值)的原因是因为在这种情况下,x 轴值实际上只是表示数据框中行号的整数(尽管 x 轴标签格式为日期),因此您传递给 aline kwarg 的日期必须转换为行号(如果日期介于两行之间,则转换为行号)。该算法使用现有数据。会考虑是否可以轻松修改以进行推断(如果可以,可能不完全是线性的)。 The code can be seen here。我愿意接受建议。与此同时,show_nontrading=True 应该可以正常工作。


    另一种解决方法是在数据框的开头和结尾放置一个额外的行,其中包含趋势线的日期。

    您需要开始结束的原因是因为两个您的趋势线日期都超出了您的数据范围。

    这对于datetime(2020, 8, 30) 可能并不明显,因为对get_data_yahoo() 的调用使用相同的日期,然而API 返回 8.31.2020 作为第一个日期,因为 8.0 是星期日,并且非交易日。

    因此:

    from datetime import datetime, timedelta, date
    import pandas_datareader as pdr
    import mplfinance as mpf
        
    df_history = pdr.get_data_yahoo(symbols='GOLD', 
                                        start=datetime(2020, 8, 30), 
                                        end=datetime(2021, 2, 23))
    
    dfa = df_history.iloc[0:1].copy()     # copy first row
    dfa.index = [datetime(2020, 8, 30)]   # switch the date
    
    dfb = df_history.iloc[-2:-1].copy()   # copy last row
    dfb.index = [datetime(2021, 3, 26)]   # switch the date
    
    # Concatenate the three DataFrames
    df_history = pd.concat([dfa,df_history,dfb])
    
    # Now we the trend line dates are withing the range of data in df_history:
    
    two_points  = [(datetime(2020, 8, 30),28.72),(datetime(2021, 3, 26),23.49)]
    mpf.plot(df_history, type='candle', alines=two_points)
    

    结果:

    For more details about trend line extrapolation, and the issues that relate to whether or not you trend includes non-trading days, click here.

    【讨论】:

    • 谢谢Goldfarb先生,帽子帮了大忙,很荣幸得到您的答复
    • @Chris0815 不客气。请注意,我已经编辑/添加到答案以包含另一个允许保持show_nontrading False 的解决方法。 请注意,外推趋势线的角度变化取决于是否包括非交易日。上面提到的link 中详细讨论了这个问题。
    • 再次非常感谢您。 show_nontrading = True 目前对我来说没问题,但你永远不知道,也许将来它可能是错误的,现在也有解决这种情况的方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多