refactor: Improve Bollinger Bands calculation with dynamic column detection and debug logging

This commit is contained in:
Bobby (aider) 2025-02-13 23:23:48 -08:00
parent efe820317c
commit a4ee19a1d0

View File

@ -56,23 +56,43 @@ class DynamicStrategy(Strategy):
std = float(ind_config['params']['std'])
def bb_calc(x):
# Use pandas-ta bbands with explicit column names
result = pd.DataFrame(ta.bbands(x, length=length, std=std))
if result is None or result.empty:
# Debug print input data
print(f"BB input data first few values: {x[:5]}")
# Calculate BB directly using pandas-ta
bb_result = ta.bbands(close=x, length=length, std=std)
# Debug print the result
print(f"BB calculation direct result type: {type(bb_result)}")
print(f"BB calculation direct result:\n{bb_result.head() if hasattr(bb_result, 'head') else bb_result}")
if bb_result is None:
print("BB calculation returned None")
return np.zeros(len(x)), np.zeros(len(x)), np.zeros(len(x))
# Debug print
print(f"BB calculation result columns: {result.columns}")
print(f"First few rows of BB calculation:\n{result.head()}")
# Get column names
bb_cols = bb_result.columns if hasattr(bb_result, 'columns') else []
print(f"BB result columns: {bb_cols}")
# Get the correct column names from pandas-ta output
upper_col = f'BBU_{length}_{std}.0'
middle_col = f'BBM_{length}_{std}.0'
lower_col = f'BBL_{length}_{std}.0'
# Find the correct column names
upper_col = [col for col in bb_cols if 'BBU_' in col][0]
middle_col = [col for col in bb_cols if 'BBM_' in col][0]
lower_col = [col for col in bb_cols if 'BBL_' in col][0]
return (result[upper_col].fillna(method='ffill').fillna(0).values,
result[middle_col].fillna(method='ffill').fillna(0).values,
result[lower_col].fillna(method='ffill').fillna(0).values)
print(f"Found BB columns - Upper: {upper_col}, Middle: {middle_col}, Lower: {lower_col}")
# Extract and process the values
upper = bb_result[upper_col].fillna(method='ffill').fillna(0).values
middle = bb_result[middle_col].fillna(method='ffill').fillna(0).values
lower = bb_result[lower_col].fillna(method='ffill').fillna(0).values
# Debug print the processed values
print(f"Processed BB values first few rows:")
print(f"Upper: {upper[:5]}")
print(f"Middle: {middle[:5]}")
print(f"Lower: {lower[:5]}")
return upper, middle, lower
bb_vals = self.I(bb_calc, self.data.Close)
self.indicators[f"{ind_name}_upper"] = bb_vals[0]