@@ -83,6 +83,43 @@ async def get_stock_details(ticker: str) -> dict:
83
83
return data
84
84
85
85
86
+ def add_afterhours_data (
87
+ data : dict , do_format_change : bool , prices : list , changes : list
88
+ ) -> dict :
89
+ try :
90
+ # Determine which price to report based on market hours
91
+ if afterHours ():
92
+ # Safely extract last close using .get() with fallback to None
93
+ last_close = (
94
+ data .get ("chart" , {})
95
+ .get ("result" , [{}])[0 ]
96
+ .get ("indicators" , {})
97
+ .get ("quote" , [{}])[0 ]
98
+ .get ("close" , [None ])[- 1 ]
99
+ )
100
+
101
+ # Ensure last_close is valid
102
+ if last_close is not None and last_close != 0 :
103
+ # Use .get() to safely get previous close, fallback to last_close if missing
104
+ previous_close = data ["chart" ]["result" ][0 ]["meta" ].get (
105
+ "previousClose" , last_close
106
+ )
107
+
108
+ # Ensure previous_close is valid before calculating change
109
+ if previous_close and previous_close != 0 :
110
+ ah_change = (last_close - previous_close ) / previous_close * 100
111
+
112
+ # Format change if required
113
+ if do_format_change :
114
+ ah_change = format_change (ah_change )
115
+
116
+ # Append valid data
117
+ prices .append (last_close )
118
+ changes .append (ah_change if ah_change is not None else "N/A" )
119
+ except Exception as e :
120
+ logger .error (f"Error in adding after hours data: { e } " )
121
+
122
+
86
123
async def yf_info (ticker : str , do_format_change : bool = True ):
87
124
# This can be blocking
88
125
try :
@@ -121,19 +158,7 @@ def append_price_data(price_key: str, prev_close_key: str):
121
158
changes .append (change or "N/A" ) # Handle None or missing change
122
159
123
160
append_price_data ("regularMarketPrice" , "previousClose" )
124
-
125
- # Determine which price to report based on market hours
126
- if afterHours ():
127
- last_close = data ["chart" ]["result" ][0 ]["indicators" ]["quote" ][0 ]["close" ][- 1 ]
128
- # Compare last close to current price
129
- previous_close = stock_info .get ("previousClose" , last_close )
130
- ah_change = (last_close - previous_close ) / previous_close * 100
131
-
132
- if do_format_change :
133
- ah_change = format_change (ah_change )
134
- if last_close and last_close != 0 :
135
- prices .append (last_close )
136
- changes .append (ah_change or "N/A" ) # Handle None or missing change
161
+ add_afterhours_data (data , do_format_change , prices , changes )
137
162
138
163
# Calculate volume
139
164
volume : float = (
0 commit comments