22import talib
33import pymysql
44import os
5+ import json
56
67host = os .getenv ('DB_HOST' , 'localhost' ) # Default to 'localhost' if not set
78port = 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
4769def 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
118142if __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