Skip to content

Commit f5052c2

Browse files
authored
Update indicators.py
1 parent fba1efc commit f5052c2

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

indicators/indicators.py

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import talib
33
import pymysql
44
import os
5+
import json
56

67
host = os.getenv('DB_HOST', 'localhost') # Default to 'localhost' if not set
78
port = int(os.getenv('DB_PORT', 3306)) # Default to 3306 if not set
@@ -43,6 +44,27 @@ def load_data_from_db(stock_code, start_date, end_date, db_query_sec_record_num_
4344
return None
4445

4546

47+
def clean_indicators(indicators):
48+
"""Remove NaN values from indicators and convert to JSON-serializable format"""
49+
cleaned = {}
50+
51+
for key, value in indicators.items():
52+
if isinstance(value, tuple): # Handle tuple indicators like AROON
53+
cleaned_tuple = []
54+
for item in value:
55+
if isinstance(item, pd.Series):
56+
cleaned_tuple.append([x for x in item.values if pd.notna(x)])
57+
else:
58+
cleaned_tuple.append(item)
59+
cleaned[key] = tuple(cleaned_tuple)
60+
elif isinstance(value, pd.Series):
61+
cleaned[key] = [x for x in value.values if pd.notna(x)]
62+
else:
63+
cleaned[key] = value
64+
65+
return cleaned
66+
67+
4668
# 2. Calculate stock indicators
4769
def calculate_indicators(df):
4870
print("Calculating indicators...")
@@ -100,7 +122,7 @@ def calculate_indicators(df):
100122
# Williams' %R (WILLR)
101123
indicators['WILLR'] = talib.WILLR(df['High'], df['Low'], df['Close'])
102124

103-
return indicators
125+
return clean_indicators(indicators)
104126

105127

106128
# 3. Main program
@@ -109,11 +131,13 @@ def calc_stock_indicators(stock_code, start_date, end_date, record_num_limit=14)
109131
df = load_data_from_db(stock_code, start_date, end_date, record_num_limit)
110132

111133
if df is not None:
112-
df_with_indicators = calculate_indicators(df)
134+
indicators = calculate_indicators(df)
113135

114-
print(df_with_indicators)
136+
# Convert to JSON and print
137+
json_output = json.dumps(indicators, indent=2)
138+
print(json_output)
115139

116140

117141
# Example call
118142
if __name__ == "__main__":
119-
calc_stock_indicators('AAPL', '2022-01-01', '2022-12-31')
143+
calc_stock_indicators('AAPL', '2022-01-01', '2022-12-31', 50)

0 commit comments

Comments
 (0)