Skip to main content
Code Review

Return to Revisions

3 of 4
edited tags

William Fractal technical indicator implementation

I'm really new to both Python, data analysis and Panda and for gathering a bit of familiarity with this components and trying to replicate a trading strategy I'm creating a function that give me the Wiliam Fractal technical indicator, which by nature is a lagging indicator to apply at the currently analysed row of the dataframe, rather than where it actually happen, but without look ahead bias to not have unrealistic backtesting results ( but also avoiding to go back and always looking for the signal 2 rows before when it actually occurs )

the indicator is defined with this constrains source \begin{aligned} \text{Bearish Fractal} =\ &\text{High} ( N ) > \text{High} ( N - 2 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N - 1 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N + 1 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N + 2 ) \\ \end{aligned}

\begin{aligned} \text{Bullish Fractal} =\ &\text{Low} ( N ) < \text{Low} ( N - 2 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N - 1 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N + 1 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N + 2 ) \\ \end{aligned}
which I implemented with the following code:

def wilFractal(dataframe):
 df = dataframe.copy()
 df['bear_fractal'] = (
 dataframe['high'].shift(4).lt(dataframe['high'].shift(2)) &
 dataframe['high'].shift(3).lt(dataframe['high'].shift(2)) &
 dataframe['high'].shift(1).lt(dataframe['high'].shift(2)) &
 dataframe['high'].lt(dataframe['high'].shift(2))
 )
 
 df['bull_fractal'] = (
 dataframe['low'].shift(4).gt(dataframe['low'].shift(2)) &
 dataframe['low'].shift(3).gt(dataframe['low'].shift(2)) &
 dataframe['low'].shift(1).gt(dataframe['low'].shift(2)) &
 dataframe['low'].gt(dataframe['high'].shift(2))
 )
 
 return df['bear_fractal'], df['bull_fractal']

any suggestions?

usage edit: The code in this case is used to signal buy signal for a crypto trading bot in this manner:

def populate_buy_trend(self, dataframe, metadata) 
 dataframe.loc[
 dataframe['bull_fractal'],
 'buy'] = 1
 return dataframe
Valex
  • 141
  • 1
  • 6
lang-py

AltStyle によって変換されたページ (->オリジナル) /