【问题标题】:pandas find two rolling max highs and calculate slope熊猫找到两个滚动的最高点并计算斜率
【发布时间】:2017-07-03 07:15:49
【问题描述】:

我正在寻找一种方法来找到滚动框架中的两个最大高点并计算斜率以推断可能的第三个高点。

我有几个问题:) a) 如何找到第二个高点? b) 如何知道两个高点的位置(对于一个简单的斜率:slope = (MaxHigh2-MaxHigh1)/(PosMaxHigh2-PosMaxHigh1))?

当然,我可以做这样的事情。但我只有在 high1 > high2 时才工作 :) 而且我不会有相同范围的高点。

import quandl
import pandas as pd
import numpy as np
import sys  


df = quandl.get("WIKI/GOOGL")
df = df.ix[:10, ['High', 'Close' ]]

df['MAX_HIGH_3P'] = df['High'].rolling(window=3,center=False).max()
df['MAX_HIGH_5P'] = df['High'].rolling(window=5,center=False).max()

df['SLOPE'] = (df['MAX_HIGH_5P']-df['MAX_HIGH_3P'])/(5-3)

print(df.head(20).to_string())

【问题讨论】:

  • “两个最大高度”似乎很不合适。你必须在你的上下文中定义它是什么,因为这没有一般意义。
  • @B.M.对不起。我需要最高的和次高的:)

标签: python pandas stock


【解决方案1】:

抱歉,解决方案有点混乱,但我希望它有所帮助:

首先我定义了一个函数,该函数将 numpy 数组作为输入,检查是否至少有 2 个元素不为空,然后计算斜率(根据您的公式 - 我认为),如下所示:

def calc_slope(input_list):
    if sum(~np.isnan(x) for x in input_list) < 2:
        return np.NaN
    temp_list = input_list[:]
    max_value = np.nanmax(temp_list)
    max_index = np.where(input_list == max_value)[0][0]
    temp_list = np.delete(temp_list, max_index)
    second_max = np.nanmax(temp_list)
    second_max_index = np.where(input_list == second_max)[0][0]
    return (max_value - second_max)/(1.0*max_index-second_max_index)

在变量 df 我有这个:

您只需将滚动窗口应用于您喜欢的任何内容,例如应用于“高”:

df['High'].rolling(window=5, min_periods=2, center=False).apply(lambda x: calc_slope(x))

最终结果如下所示:

如果您愿意,也可以将其存储在其他列中:

df['High_slope'] = df['High'].rolling(window=5, min_periods=2, center=False).apply(lambda x: calc_slope(x))

这是你想要的吗?

【讨论】:

  • 正是我需要的。不,我需要一些时间来了解你做了什么!谢谢! E.
猜你喜欢
  • 2014-01-30
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 2020-02-18
  • 2019-11-19
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多