python - pandas find two rolling max highs and calculate slope -


i'm looking way find 2 max highs in rolling frame , calculate slope extrapolate possible third high.

i have several problems :) a) how find second high? b) how know position of 2 highs (for simple slope : slope = (maxhigh2-maxhigh1)/(posmaxhigh2-posmaxhigh1))?

i could, of course, this. work if high1 > high2 :) , not have highs of same range.

import quandl import pandas pd import numpy 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()) 

sorry bit messy solution hope helps:

first define function takes input numpy array, checks if @ least 2 elements not null, , calculates slope (according formula - think), looks this:

def calc_slope(input_list):     if sum(~np.isnan(x) 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 have :

enter image description here

and have apply rolling window whatever prefer, in example applied "high":

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

final result looks this:

enter image description here

you can store in columns if like:

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

is wanted?


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -