The issue you're encountering—where all entries in the 'SSG' column remain 0—is likely due to the conditions in your run method never being satisfied. Here are the primary reasons and suggestions to fix them:
1. Exact Equality with Floating-Point Numbers
Problem:
You are using the == operator to compare floating-point numbers, such as:
if self.df['DoubleSlowK'].iloc[i] == self.l2
Floating-point comparisons using == can be unreliable because of precision issues. Even if two numbers appear identical, their binary representations might differ slightly, causing the comparison to fail.
Solution:
Use a tolerance-based approach to check if the values are approximately equal. For example:
tolerance = 1e-5 # Adjust the tolerance as needed
if abs(self.df['DoubleSlowK'].iloc[i] - self.l2) < tolerance:
# Proceed with the condition
Alternatively, if l2 and l2l represent specific levels or thresholds, consider using inequality comparisons to check if the values are within a range.
2. Logical Conditions Not Being Met
Problem:
The combined conditions might be too restrictive, meaning it's rare or impossible for all of them to be True simultaneously. This could result in the 'SSG' column never being updated from its initial value of 0.
Solution:
- Break Down the Conditions: Start by verifying each part of your condition separately to ensure they can be met.
- Add Debugging Statements: Insert print statements or logging to monitor the values and see why the conditions aren't being satisfied.
for i in range(2, len(self.df)):
ds_k = self.df['DoubleSlowK'].iloc[i]
ds_k_prev = self.df['DoubleSlowK'].iloc[i-1]
fast_d = self.df['%FastD'].iloc[i]
fast_d_prev = self.df['%FastD'].iloc[i-1]
fast_d_prev2 = self.df['%FastD'].iloc[i-2]
print(f"Index {i}: DoubleSlowK={ds_k}, prev={ds_k_prev}, %FastD={fast_d}, prev={fast_d_prev}, prev2={fast_d_prev2}")
# First condition
if (abs(ds_k - self.l2) < tolerance and
abs(ds_k_prev - self.l2) < tolerance and
fast_d < self.l1):
if (fast_d < fast_d_prev and fast_d_prev > fast_d_prev2):
self.df.loc[i, 'SSG'] = -1
print(f"Set SSG at index {i} to -1")
# Second condition
if (abs(ds_k - self.l2l) < tolerance and
abs(ds_k_prev - self.l2) < tolerance and
fast_d > self.l1l):
if (fast_d > fast_d_prev and fast_d_prev < fast_d_prev2):
self.df.loc[i, 'SSG'] = 1
print(f"Set SSG at index {i} to 1")
3. Unused strategy_signals DataFrame
Problem:
You initialize a strategy_signals DataFrame but never use it. This might indicate that you intended to store the signals there instead of directly modifying self.df.
Solution:
Decide where you want to store your signals. If you prefer using strategy_signals, modify and return it accordingly. Otherwise, you can remove the unused DataFrame to avoid confusion.
4. Potential Data Issues
Problem:
Ensure that the columns 'DoubleSlowK' and '%FastD' exist in self.df and contain valid numerical data without NaN values that might affect the conditions.
Solution:
- Verify Columns: Check if the required columns are present in the DataFrame.
- Handle Missing Values: Decide how to handle
NaN values—whether to skip those indices or fill them with appropriate values.
required_columns = ['DoubleSlowK', '%FastD']
for col in required_columns:
if col not in self.df.columns:
raise ValueError(f"Missing required column: {col}")
# Optionally, drop rows with NaN values in these columns
self.df.dropna(subset=required_columns, inplace=True)
5. Refined Implementation Example
Here's a revised version of your SSG class with some of the suggested fixes:
class SSG(indchecks):
def __init__(self, df, l1, l2, l1l, l2l, tolerance=1e-5):
super().__init__(df)
self.l1 = l1
self.l2 = l2
self.l1l = l1l
self.l2l = l2l
self.tolerance = tolerance # Added tolerance for comparisons
def run(self):
self.df['SSG'] = 0
# Removed strategy_signals as it's unused
for i in range(2, len(self.df)):
ds_k = self.df['DoubleSlowK'].iloc[i]
ds_k_prev = self.df['DoubleSlowK'].iloc[i-1]
fast_d = self.df['%FastD'].iloc[i]
fast_d_prev = self.df['%FastD'].iloc[i-1]
fast_d_prev2 = self.df['%FastD'].iloc[i-2]
# Debugging print statements
# print(f"Index {i}: DoubleSlowK={ds_k}, prev={ds_k_prev}, %FastD={fast_d}, prev={fast_d_prev}, prev2={fast_d_prev2}")
# First condition: set to -1
if (abs(ds_k - self.l2) < self.tolerance and
abs(ds_k_prev - self.l2) < self.tolerance and
fast_d < self.l1):
if (fast_d < fast_d_prev and fast_d_prev > fast_d_prev2):
self.df.loc[i, 'SSG'] = -1
# print(f"Set SSG at index {i} to -1")
# Second condition: set to 1
if (abs(ds_k - self.l2l) < self.tolerance and
abs(ds_k_prev - self.l2) < self.tolerance and
fast_d > self.l1l):
if (fast_d > fast_d_prev and fast_d_prev < fast_d_prev2):
self.df.loc[i, 'SSG'] = 1
# print(f"Set SSG at index {i} to 1")
6. Additional Recommendations
-
Logging: Instead of using print statements, consider using Python's logging module for better control over debug output.
-
Testing Conditions Separately: Create unit tests or separate functions to test individual conditions in isolation. This can help ensure that each part behaves as expected.
-
Data Inspection: Manually inspect parts of your DataFrame where you expect conditions to be True to verify if the logic aligns with your expectations.
Summary
The primary culprit is likely the use of exact equality (==) for floating-point comparisons, which rarely succeeds due to precision issues. Switching to a tolerance-based comparison or using range-based checks should resolve the issue of conditions never being met, allowing the 'SSG' column to be updated appropriately.