Home > Back-end >  How to calculate rolling.agg('max') utilising a dataframe column as input to my function
How to calculate rolling.agg('max') utilising a dataframe column as input to my function

Time:11-18

I'm working with a kline dataframe. I'm adding a Swing_High and Swing_Low column to my df.

I've picked up an error where during low volatile periods my Close == Swing_Low price. This gives me a inf error in another function I have where close / Swing_Low.

To fix this I need to calculate the max/min value based on whether Close == Swing_Low or not. Default is for the rolling period to be 10 but if the above is true then increase the rolling period to 15.

Below is how I calculated the Swing_High and Swing_Low up to encountering Inf error.

import pandas as pd

df = pd.read_csv('Data/bybit_BTCUSD_15m.csv')
df["Date"] = df["Date"].astype('datetime64[ns]')

# Calculate the swing high and low for a given length
df['Swing_High'] = df['High'].rolling(10).agg('max')
df['Swing_Low'] = df['Low'].rolling(10).agg('min')

I tried the below function but it gives me a ValueError: The truth value of a Series is ambiguous

def swing_high(close, high, period1, period2):
    a = high.rolling(period1).agg('max')
    b = high.rolling(period2).agg('max')
    if a != close:
        return a
    else:
        return b

df['Swing_High'] = swing_high(df['Close'], df['High'], 10, 15)

How do I fix this or is there a better way to achieve my desired outcome?

CodePudding user response:

A simple solution for what you're trying to achieve :

using the where function:

here’s the basic syntax using the pandas where() function:

df['col'] = (value_if_false).where(condition, value_if_true)
df['Swing_High_10']=df['High'].rolling(10).agg('max')
df['Swing_High_15']=df['High'].rolling(15).agg('max')

df['Swing_High']=(df['Swing_High_15']).where(df['Swing_High_10']!=df['Close'], df['Swing_High_15'])
  • Related