parkerjj commited on
Commit
9d3e0cb
·
1 Parent(s): 479b95f

优化获取股票最新价格的函数,增加重试机制和错误处理,改进缓存逻辑以提高稳定性

Browse files
Files changed (1) hide show
  1. us_stock.py +40 -12
us_stock.py CHANGED
@@ -155,8 +155,14 @@ def reduce_columns(df, columns_to_keep):
155
  # 创建缓存字典
156
  _price_cache = {}
157
 
158
- def get_last_minute_stock_price(symbol: str) -> float:
159
- """获取股票最新价格,使用30分钟缓存"""
 
 
 
 
 
 
160
  current_time = datetime.now()
161
 
162
  # 检查缓存
@@ -166,17 +172,39 @@ def get_last_minute_stock_price(symbol: str) -> float:
166
  if current_time - cached_time < timedelta(minutes=30):
167
  return cached_price
168
 
169
- # 缓存无效或不存在,从yfinance获取新数据
170
- stock_data = yfinance.download(symbol, period='1d', interval='5m')
171
- if stock_data.empty:
172
- return -1.0
173
-
174
- latest_price = float(stock_data['Close'].iloc[-1])
175
-
176
- # 更新缓存
177
- _price_cache[symbol] = (latest_price, current_time)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- return latest_price
180
 
181
  # 返回个股历史数据
182
  def get_stock_history(symbol, news_date, retries=10):
 
155
  # 创建缓存字典
156
  _price_cache = {}
157
 
158
+ def get_last_minute_stock_price(symbol: str, max_retries=3) -> float:
159
+ """获取股票最新价格,使用30分钟缓存,并包含重试机制"""
160
+
161
+ if not symbol:
162
+ return -1.0
163
+ if symbol == "NONE_SYMBOL_FOUND":
164
+ return -1.0
165
+
166
  current_time = datetime.now()
167
 
168
  # 检查缓存
 
172
  if current_time - cached_time < timedelta(minutes=30):
173
  return cached_price
174
 
175
+ # 重试机制
176
+ for attempt in range(max_retries):
177
+ try:
178
+ # 缓存无效或不存在,从yfinance获取新数据
179
+ stock_data = yfinance.download(
180
+ symbol,
181
+ period='1d',
182
+ interval='5m',
183
+ progress=False, # 禁用进度条
184
+ timeout=10 # 设置超时时间
185
+ )
186
+
187
+ if stock_data.empty:
188
+ print(f"Warning: Empty data received for {symbol}, attempt {attempt + 1}/{max_retries}")
189
+ if attempt == max_retries - 1:
190
+ return -1.0
191
+ time.sleep(1) # 等待1秒后重试
192
+ continue
193
+
194
+ latest_price = float(stock_data['Close'].iloc[-1])
195
+
196
+ # 更新缓存
197
+ _price_cache[symbol] = (latest_price, current_time)
198
+
199
+ return latest_price
200
+
201
+ except Exception as e:
202
+ print(f"Error fetching price for {symbol}, attempt {attempt + 1}/{max_retries}: {str(e)}")
203
+ if attempt == max_retries - 1:
204
+ return -1.0
205
+ time.sleep(1) # 等待1秒后重试
206
 
207
+ return -1.0
208
 
209
  # 返回个股历史数据
210
  def get_stock_history(symbol, news_date, retries=10):