Refactor Cumulative RSI strategy to utilize RSI and SMA calculations from indicators module
This commit is contained in:
parent
e25e53eb70
commit
c7e434778f
@ -1,45 +1,17 @@
|
|||||||
import pandas as pd
|
from numpy import where
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from pandas import DataFrame, Series
|
from pandas import DataFrame, Series
|
||||||
|
|
||||||
def calculate_moving_average(data: DataFrame, window: int = 200) -> Series:
|
from indicators import rsi, sma
|
||||||
"""
|
|
||||||
Calculate the 200-day moving average and return it as a Series without modifying the original DataFrame.
|
|
||||||
"""
|
|
||||||
return data['Close'].rolling(window = window).mean()
|
|
||||||
|
|
||||||
def calculate_rsi(data: DataFrame, period: int = 2) -> Series:
|
|
||||||
"""
|
|
||||||
Calculate the 2-period RSI and return it as a Series without modifying the original DataFrame.
|
|
||||||
"""
|
|
||||||
delta = data['Close'].diff()
|
|
||||||
gain = np.where(delta > 0, delta, 0)
|
|
||||||
loss = np.where(delta < 0, -delta, 0)
|
|
||||||
|
|
||||||
alpha = 1 / period
|
|
||||||
avg_gain = pd.Series(gain).ewm(alpha = alpha, adjust = False).mean()
|
|
||||||
avg_loss = pd.Series(loss).ewm(alpha = alpha, adjust = False).mean()
|
|
||||||
|
|
||||||
rs = avg_gain / avg_loss
|
|
||||||
return 100 - (100 / (1 + rs))
|
|
||||||
|
|
||||||
def calculate_cumulative_rsi(rsi: Series, window: int = 2) -> Series:
|
|
||||||
"""
|
|
||||||
Calculate the cumulative RSI over a specified window period and return it as a Series.
|
|
||||||
"""
|
|
||||||
return rsi.rolling(window = window).sum()
|
|
||||||
|
|
||||||
def cumulative_rsi(data: DataFrame, rsi_period: int = 2, cumulative_period: int = 2) -> Series:
|
def cumulative_rsi(data: DataFrame, rsi_period: int = 2, cumulative_period: int = 2) -> Series:
|
||||||
"""
|
"""
|
||||||
Generate 'L'ong entry signals based on the Cumulative RSI strategy.
|
Calculate signals for the Cumulative RSI strategy.
|
||||||
Returns a Series with 'L' for entry signals and 'N' otherwise without modifying the original DataFrame.
|
|
||||||
|
Returns a Series with 'L' for long signals and 'N' otherwise.
|
||||||
Entry Condition: 2-period cumulative RSI below 35 and above the 200-day moving average.
|
|
||||||
"""
|
"""
|
||||||
ma_200 = calculate_moving_average(data)
|
ma_200 = sma(data, period = 200)
|
||||||
rsi_2 = calculate_rsi(data, period = rsi_period)
|
rsi_2 = rsi(data, period = rsi_period)
|
||||||
cumulative_rsi_2 = calculate_cumulative_rsi(rsi_2, window = cumulative_period)
|
cumulative_rsi_2 = rsi_2.rolling(window = cumulative_period).sum()
|
||||||
|
|
||||||
long_condition = (data['Close'] > ma_200) & (cumulative_rsi_2 < 35)
|
long_condition = (data['Close'] > ma_200) & (cumulative_rsi_2 < 35)
|
||||||
return Series(np.where(long_condition, 'L', 'N'), index = data.index)
|
return Series(where(long_condition, 'L', 'N'), index = data.index)
|
Loading…
Reference in New Issue
Block a user