refactor: Improve pandas-ta indicator initialization in DynamicStrategy

This commit is contained in:
Bobby (aider) 2025-02-13 23:08:06 -08:00
parent c20619d05b
commit b41046105d

View File

@ -18,25 +18,24 @@ class DynamicStrategy(Strategy):
# Initialize all selected indicators
for ind_name, ind_config in self.indicator_configs.items():
if ind_config['type'] == 'SMA':
self.indicators[ind_name] = self.I(ta.sma, self.data.Close, length=ind_config['params']['length'])
self.indicators[ind_name] = self.I(lambda x: ta.sma(x, length=ind_config['params']['length']), self.data.Close)
elif ind_config['type'] == 'EMA':
self.indicators[ind_name] = self.I(ta.ema, self.data.Close, length=ind_config['params']['length'])
self.indicators[ind_name] = self.I(lambda x: ta.ema(x, length=ind_config['params']['length']), self.data.Close)
elif ind_config['type'] == 'RSI':
self.indicators[ind_name] = self.I(ta.rsi, self.data.Close, length=ind_config['params']['length'])
self.indicators[ind_name] = self.I(lambda x: ta.rsi(x, length=ind_config['params']['length']), self.data.Close)
elif ind_config['type'] == 'MACD':
macd = ta.macd(self.data.Close,
fast=ind_config['params']['fast'],
slow=ind_config['params']['slow'],
signal=ind_config['params']['signal'])
self.indicators[f"{ind_name}_macd"] = self.I(lambda x: x['MACD_12_26_9'], macd)
self.indicators[f"{ind_name}_signal"] = self.I(lambda x: x['MACDs_12_26_9'], macd)
fast = ind_config['params']['fast']
slow = ind_config['params']['slow']
signal = ind_config['params']['signal']
self.indicators[f"{ind_name}_macd"] = self.I(lambda x: ta.macd(x, fast=fast, slow=slow, signal=signal).iloc[:,0], self.data.Close)
self.indicators[f"{ind_name}_signal"] = self.I(lambda x: ta.macd(x, fast=fast, slow=slow, signal=signal).iloc[:,2], self.data.Close)
elif ind_config['type'] == 'BB':
bb = ta.bbands(self.data.Close,
length=ind_config['params']['length'],
std=ind_config['params']['std'])
self.indicators[f"{ind_name}_upper"] = self.I(lambda x: x['BBU_20_2.0'], bb)
self.indicators[f"{ind_name}_lower"] = self.I(lambda x: x['BBL_20_2.0'], bb)
self.indicators[f"{ind_name}_middle"] = self.I(lambda x: x['BBM_20_2.0'], bb)
length = ind_config['params']['length']
std = ind_config['params']['std']
bbands = self.I(lambda x: ta.bbands(x, length=length, std=std), self.data.Close)
self.indicators[f"{ind_name}_upper"] = self.I(lambda x: x.iloc[:,0], bbands)
self.indicators[f"{ind_name}_middle"] = self.I(lambda x: x.iloc[:,1], bbands)
self.indicators[f"{ind_name}_lower"] = self.I(lambda x: x.iloc[:,2], bbands)
def next(self):
# Simple example strategy - should be customized based on user input