Ele
Ele

Reputation: 553

pandas find two rolling max highs and calculate slope

I'm looking for a way to find the two max highs in a rolling frame and calculate the slope to extrapolate a possible third high.

I have several problems with this :) a) how to find a second high? b) how to know the position of the two highs (for a simple slope : slope = (MaxHigh2-MaxHigh1)/(PosMaxHigh2-PosMaxHigh1))?

I could, of course, do something like this. but I only work if high1 > high2 :) and I would not have the highs of the same range.

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

Upvotes: 1

Views: 1393

Answers (1)

Kacper Wolkowski
Kacper Wolkowski

Reputation: 1597

Sorry for a bit messy solution but I hope it helps:

first I define a function which takes as input numpy array, checks if at least 2 elements are not null, and then calculates slope (according to your formula - i think), looks like this:

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)

in variable df I have this :

enter image description here

And you just have to apply rolling window to whatever you prefer, in example applied to "High":

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

Final result looks like this:

enter image description here

You can also store it in another columns if you like:

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

Is that what you wanted?

Upvotes: 1

Related Questions