KKKMatthias commited on
Commit
244bb86
·
verified ·
1 Parent(s): 1246b28

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ # 禁用 yfinance 的磁盘缓存,防止在只读环境中报错
3
+ os.environ['YF_NOCACHE'] = 'True'
4
+
5
+ from fastapi import FastAPI
6
+ import yfinance as yf
7
+ import math
8
+ import uvicorn
9
+
10
+ app = FastAPI()
11
+
12
+ def clean_num(val):
13
+ try:
14
+ if val is None: return None
15
+ f_val = float(val)
16
+ if math.isnan(f_val) or math.isinf(f_val): return None
17
+ return f_val
18
+ except:
19
+ return None
20
+
21
+ @app.get("/")
22
+ def home():
23
+ return {"status": "Stock API is running", "endpoint": "/stock/{ticker}"}
24
+
25
+ @app.get("/stock/{ticker}")
26
+ def get_stock(ticker: str):
27
+ try:
28
+ # yfinance 在 HF 的环境下表现非常稳定
29
+ stock = yf.Ticker(ticker.upper())
30
+ info = stock.info
31
+
32
+ if not info or len(info) < 5:
33
+ return {"error": "No data found", "ticker": ticker}
34
+
35
+ return {
36
+ "ticker": ticker.upper(),
37
+ "pe_static": clean_num(info.get('trailingPE')),
38
+ "pe_dynamic": clean_num(info.get('forwardPE')),
39
+ "eps_current_year": clean_num(info.get('trailingEps')),
40
+ "eps_next_year": clean_num(info.get('forwardEps')),
41
+ "source": "hf_space_v1"
42
+ }
43
+ except Exception as e:
44
+ return {"error": str(e)}
45
+
46
+ if __name__ == "__main__":
47
+ # Hugging Face 会自动分配端口,通常是 7860
48
+ uvicorn.run(app, host="0.0.0.0", port=7860)