Spaces:
Sleeping
Sleeping
File size: 2,373 Bytes
244bb86 a750ea9 244bb86 9f7a5ba a750ea9 ac6f355 a750ea9 ac6f355 a750ea9 e6816b6 ee5c0b1 a750ea9 1fdcb21 ac6f355 244bb86 1fdcb21 e6816b6 1fdcb21 244bb86 a7bb0ed ac6f355 1fdcb21 244bb86 d8f12b9 244bb86 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import os
from fastapi import FastAPI
import yfinance as yf
import math
import pandas as pd
import uvicorn
app = FastAPI()
def clean_num(val):
try:
if val is None: return None
f_val = float(val)
if math.isnan(f_val) or math.isinf(f_val): return None
return f_val
except:
return None
@app.get("/")
def home():
return {"status": "Stock API is running", "endpoint": "/stock/{ticker}"}
@app.get("/stock/{ticker}")
def get_stock(ticker: str):
try:
stock = yf.Ticker(ticker.upper())
# 1. 尝试从 stock.info 获取数据
info = stock.info
# 2. 尝试获取详细的分析师预测表
try:
est = stock.earnings_estimate
except Exception:
est = None
eps_est_current = None
eps_est_next = None
if est is not None and not est.empty:
try:
# 方法 A: 使用位置索引 iloc
eps_est_current = est.iloc[2]['avg'] # 当前财年
eps_est_next = est.iloc[3]['avg'] # 下一财年
except Exception as e:
print(f"Error parsing dataframe: {e}")
# 3. 如果从表格获取失败,使用 info 中的备用数据
if eps_est_next is None and info:
eps_est_next = info.get('forwardEps')
if not info or len(info) < 5:
return {"error": "No data found", "ticker": ticker}
try:
ept = stock.eps_trend
except Exception:
ept = None
eps_current = None
if ept is not None and not ept.empty:
try:
eps_current = ept.iloc[2]['current'] # 当前财年
except Exception as e:
print(f"Error parsing dataframe: {e}")
return {
"ticker": ticker.upper(),
"pe_static": clean_num(info.get('trailingPE')),
"pe_dynamic": clean_num(info.get('forwardPE')),
"eps_est_avg_current_year": clean_num(eps_est_current),
"eps_est_avg_next_year": clean_num(eps_est_next),
"eps_avg_current_year": clean_num(eps_current),
}
except Exception as e:
return {"error": str(e)}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |