【问题标题】:How do I find out where one line crosses another with pandas/matplotlib?如何使用 pandas/matplotlib 找出一条线与另一条线相交的位置?
【发布时间】:2021-10-27 15:35:28
【问题描述】:

我有一个名为df['x'] 的数据框,我已使用 Matplotlib 绘制如下图所示。数据框有一个日期时间索引,在0和0以上之间波动。还有两条紫色线y=2和y=5。

我有兴趣在索引上找到蓝线向上穿过紫线 y=2 的日期。但是需要注意的是,如果蓝线在达到 0 之前再次穿过紫线,我不希望它被计算在内。所以我正在寻找一个可以返回 6 个日期的系统。感谢您的帮助。

https://gyazo.com/40aac726ef3546c22c9191fa2d9bc3e2

【问题讨论】:

    标签: pandas numpy matplotlib


    【解决方案1】:

    我最终尝试了很多不同的东西。最初我真的不确定如何解决这个问题,因为我对编码还很陌生。在做了一些研究之后,我找到了一个解决方案,它通过应用一个函数来创建一个新列,然后找到满足特定条件的列区域的索引。

    #Making a function to apply to df
    trade_pos = ''
    dip = ''
    def apply_function(df):
        global trade_pos
        global dip
        if df.Drawdown == 0 and trade_pos == 'open':
            trade_pos = 'closed'
            dip = 'false'
            return 'Exit'
        elif df.Drawdown == 0:
            trade_pos = 'closed'
            dip = 'false'
            return 0
        elif df.Drawdown >= 2 and df.Drawdown < 5 and trade_pos == 'closed' and dip != 'true':
            trade_pos = 'open'
            return 'Entry'
        elif df.Drawdown >=5 and trade_pos == 'open':
            trade_pos = 'closed'
            dip = 'true'
            return 'Exit'
        else:
            return 0
    
    #Applying function to df
    df['Strategy'] = df.apply(apply_function, axis=1)
    
    Finding dates of crossover with caveats
    entry = df[df['Strategy'] == 'Entry']
    entry = list(entry.index)
    #We finish with a list of dates that meet the criteria of the original post
    

    希望对遇到类似问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2016-07-27
      • 2011-12-24
      • 1970-01-01
      相关资源
      最近更新 更多