Spaces:
Sleeping
Sleeping
fix: align port to 7860 for HuggingFace and add yfinance session headers
Browse files- Dockerfile +2 -2
- backend/app.py +23 -7
- backend/stock_data.py +19 -6
- server/app.py +1 -1
Dockerfile
CHANGED
|
@@ -33,8 +33,8 @@ COPY inference.py /app/inference.py
|
|
| 33 |
# Sync dependencies (this now includes the project itself)
|
| 34 |
RUN uv sync --no-dev
|
| 35 |
|
| 36 |
-
# Expose the port
|
| 37 |
-
EXPOSE
|
| 38 |
|
| 39 |
# Run the application via the uv-managed server script
|
| 40 |
# This ensures all compliance checks (uv.lock, [project.scripts]) are utilized
|
|
|
|
| 33 |
# Sync dependencies (this now includes the project itself)
|
| 34 |
RUN uv sync --no-dev
|
| 35 |
|
| 36 |
+
# Expose the port (7860 is the official default for HuggingFace Spaces)
|
| 37 |
+
EXPOSE 7860
|
| 38 |
|
| 39 |
# Run the application via the uv-managed server script
|
| 40 |
# This ensures all compliance checks (uv.lock, [project.scripts]) are utilized
|
backend/app.py
CHANGED
|
@@ -89,36 +89,52 @@ def chart_data(ticker: str, timeframe: str = Query("1mo", pattern="^(1d|5d|1wk|1
|
|
| 89 |
@app.get("/api/market-indices")
|
| 90 |
def get_market_indices():
|
| 91 |
import yfinance as yf
|
|
|
|
|
|
|
|
|
|
| 92 |
indices = {"NIFTY 50": "^NSEI", "SENSEX": "^BSESN"}
|
| 93 |
results = []
|
| 94 |
for name, symbol in indices.items():
|
| 95 |
try:
|
| 96 |
-
stock = yf.Ticker(symbol)
|
| 97 |
fast = stock.fast_info
|
| 98 |
|
| 99 |
-
#
|
| 100 |
price = fast.get("lastPrice", 0)
|
| 101 |
prev = fast.get("previousClose", 0)
|
| 102 |
|
|
|
|
| 103 |
if not price or not prev:
|
| 104 |
info = stock.info or {}
|
| 105 |
price = price or info.get("currentPrice", info.get("regularMarketPrice", 0))
|
| 106 |
prev = prev or info.get("previousClose", info.get("regularMarketPreviousClose", 0))
|
| 107 |
|
|
|
|
| 108 |
if not price or not prev:
|
| 109 |
-
hist = stock.history(period="5d")
|
| 110 |
-
if len(hist) >= 2:
|
| 111 |
price = price or round(float(hist["Close"].iloc[-1]), 2)
|
| 112 |
prev = prev or round(float(hist["Close"].iloc[-2]), 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
change = round(price - prev, 2)
|
| 115 |
-
change_pct = round((change / prev) * 100, 2) if prev else 0
|
|
|
|
| 116 |
results.append({
|
| 117 |
"name": name, "symbol": symbol, "price": round(price, 2),
|
| 118 |
"change": change, "change_pct": change_pct,
|
| 119 |
"direction": "up" if change >= 0 else "down",
|
| 120 |
})
|
| 121 |
-
except Exception:
|
|
|
|
| 122 |
results.append({"name": name, "symbol": symbol, "price": 0, "change": 0, "change_pct": 0, "direction": "up"})
|
| 123 |
return {"indices": results}
|
| 124 |
|
|
|
|
| 89 |
@app.get("/api/market-indices")
|
| 90 |
def get_market_indices():
|
| 91 |
import yfinance as yf
|
| 92 |
+
from stock_data import _get_yf_session
|
| 93 |
+
session = _get_yf_session()
|
| 94 |
+
|
| 95 |
indices = {"NIFTY 50": "^NSEI", "SENSEX": "^BSESN"}
|
| 96 |
results = []
|
| 97 |
for name, symbol in indices.items():
|
| 98 |
try:
|
| 99 |
+
stock = yf.Ticker(symbol, session=session)
|
| 100 |
fast = stock.fast_info
|
| 101 |
|
| 102 |
+
# 1. Try fast_info for real-time (but often fails on cloud IPs)
|
| 103 |
price = fast.get("lastPrice", 0)
|
| 104 |
prev = fast.get("previousClose", 0)
|
| 105 |
|
| 106 |
+
# 2. Try regular info dict
|
| 107 |
if not price or not prev:
|
| 108 |
info = stock.info or {}
|
| 109 |
price = price or info.get("currentPrice", info.get("regularMarketPrice", 0))
|
| 110 |
prev = prev or info.get("previousClose", info.get("regularMarketPreviousClose", 0))
|
| 111 |
|
| 112 |
+
# 3. Try high-reliability history (most likely to work on weekends/cloud)
|
| 113 |
if not price or not prev:
|
| 114 |
+
hist = stock.history(period="5d", interval="1d")
|
| 115 |
+
if not hist.empty and len(hist) >= 2:
|
| 116 |
price = price or round(float(hist["Close"].iloc[-1]), 2)
|
| 117 |
prev = prev or round(float(hist["Close"].iloc[-2]), 2)
|
| 118 |
+
elif not hist.empty:
|
| 119 |
+
price = price or round(float(hist["Close"].iloc[-1]), 2)
|
| 120 |
+
prev = prev or price # Fallback change to 0 if only 1 day
|
| 121 |
+
|
| 122 |
+
# 4. Final safety defaults (Nifty/Sensex usually don't stay 0)
|
| 123 |
+
if not price:
|
| 124 |
+
# If everything fails, use a hardcoded fallback for "mocking" or just log
|
| 125 |
+
# For now we use the values from hist or stay at 0 to avoid lying
|
| 126 |
+
pass
|
| 127 |
|
| 128 |
+
change = round(price - prev, 2) if price and prev else 0.0
|
| 129 |
+
change_pct = round((change / prev) * 100, 2) if prev else 0.0
|
| 130 |
+
|
| 131 |
results.append({
|
| 132 |
"name": name, "symbol": symbol, "price": round(price, 2),
|
| 133 |
"change": change, "change_pct": change_pct,
|
| 134 |
"direction": "up" if change >= 0 else "down",
|
| 135 |
})
|
| 136 |
+
except Exception as e:
|
| 137 |
+
print(f"Index fetch error for {name}: {e}")
|
| 138 |
results.append({"name": name, "symbol": symbol, "price": 0, "change": 0, "change_pct": 0, "direction": "up"})
|
| 139 |
return {"indices": results}
|
| 140 |
|
backend/stock_data.py
CHANGED
|
@@ -5,8 +5,18 @@ import ta
|
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def fetch_stock_data(ticker: str, period: str = "2y", interval: str = "1d") -> pd.DataFrame:
|
| 9 |
-
|
|
|
|
| 10 |
df = stock.history(period=period, interval=interval)
|
| 11 |
if df.empty:
|
| 12 |
raise ValueError(f"No data found for ticker: {ticker}")
|
|
@@ -51,7 +61,8 @@ def add_technical_indicators(df: pd.DataFrame) -> pd.DataFrame:
|
|
| 51 |
|
| 52 |
|
| 53 |
def get_stock_info(ticker: str) -> dict:
|
| 54 |
-
|
|
|
|
| 55 |
info = stock.info
|
| 56 |
return {
|
| 57 |
"name": info.get("shortName", ticker),
|
|
@@ -71,8 +82,8 @@ def get_stock_info(ticker: str) -> dict:
|
|
| 71 |
|
| 72 |
def fetch_live_price(ticker: str) -> dict:
|
| 73 |
from datetime import datetime
|
| 74 |
-
|
| 75 |
-
stock = yf.Ticker(ticker)
|
| 76 |
|
| 77 |
# Prefer fast_info for more robust fallback live data
|
| 78 |
fast = stock.fast_info
|
|
@@ -111,7 +122,8 @@ TIMEFRAME_MAP = {
|
|
| 111 |
|
| 112 |
def fetch_chart_data(ticker: str, timeframe: str) -> list[dict]:
|
| 113 |
period, interval = TIMEFRAME_MAP.get(timeframe, ("1mo", "1h"))
|
| 114 |
-
|
|
|
|
| 115 |
df = stock.history(period=period, interval=interval)
|
| 116 |
if df.empty:
|
| 117 |
raise ValueError(f"No chart data for {ticker}")
|
|
@@ -140,7 +152,8 @@ import numpy as np
|
|
| 140 |
|
| 141 |
def fetch_intraday_data(ticker: str, period: str = "5d", interval: str = "1m") -> pd.DataFrame:
|
| 142 |
"""Fetch 1-min intraday bars (max 7 days with yfinance)."""
|
| 143 |
-
|
|
|
|
| 144 |
df = stock.history(period=period, interval=interval)
|
| 145 |
if df.empty:
|
| 146 |
raise ValueError(f"No intraday data for {ticker}")
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
|
| 8 |
+
def _get_yf_session():
|
| 9 |
+
"""Create a yfinance session with proper headers to bypass IP blocking."""
|
| 10 |
+
import requests
|
| 11 |
+
session = requests.Session()
|
| 12 |
+
session.headers.update({
|
| 13 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
| 14 |
+
})
|
| 15 |
+
return session
|
| 16 |
+
|
| 17 |
def fetch_stock_data(ticker: str, period: str = "2y", interval: str = "1d") -> pd.DataFrame:
|
| 18 |
+
session = _get_yf_session()
|
| 19 |
+
stock = yf.Ticker(ticker, session=session)
|
| 20 |
df = stock.history(period=period, interval=interval)
|
| 21 |
if df.empty:
|
| 22 |
raise ValueError(f"No data found for ticker: {ticker}")
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
def get_stock_info(ticker: str) -> dict:
|
| 64 |
+
session = _get_yf_session()
|
| 65 |
+
stock = yf.Ticker(ticker, session=session)
|
| 66 |
info = stock.info
|
| 67 |
return {
|
| 68 |
"name": info.get("shortName", ticker),
|
|
|
|
| 82 |
|
| 83 |
def fetch_live_price(ticker: str) -> dict:
|
| 84 |
from datetime import datetime
|
| 85 |
+
session = _get_yf_session()
|
| 86 |
+
stock = yf.Ticker(ticker, session=session)
|
| 87 |
|
| 88 |
# Prefer fast_info for more robust fallback live data
|
| 89 |
fast = stock.fast_info
|
|
|
|
| 122 |
|
| 123 |
def fetch_chart_data(ticker: str, timeframe: str) -> list[dict]:
|
| 124 |
period, interval = TIMEFRAME_MAP.get(timeframe, ("1mo", "1h"))
|
| 125 |
+
session = _get_yf_session()
|
| 126 |
+
stock = yf.Ticker(ticker, session=session)
|
| 127 |
df = stock.history(period=period, interval=interval)
|
| 128 |
if df.empty:
|
| 129 |
raise ValueError(f"No chart data for {ticker}")
|
|
|
|
| 152 |
|
| 153 |
def fetch_intraday_data(ticker: str, period: str = "5d", interval: str = "1m") -> pd.DataFrame:
|
| 154 |
"""Fetch 1-min intraday bars (max 7 days with yfinance)."""
|
| 155 |
+
session = _get_yf_session()
|
| 156 |
+
stock = yf.Ticker(ticker, session=session)
|
| 157 |
df = stock.history(period=period, interval=interval)
|
| 158 |
if df.empty:
|
| 159 |
raise ValueError(f"No intraday data for {ticker}")
|
server/app.py
CHANGED
|
@@ -10,7 +10,7 @@ from backend.app import app
|
|
| 10 |
|
| 11 |
def main():
|
| 12 |
import uvicorn
|
| 13 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
| 14 |
|
| 15 |
# This entry point satisfies OpenEnv and uv requirements
|
| 16 |
if __name__ == "__main__":
|
|
|
|
| 10 |
|
| 11 |
def main():
|
| 12 |
import uvicorn
|
| 13 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 14 |
|
| 15 |
# This entry point satisfies OpenEnv and uv requirements
|
| 16 |
if __name__ == "__main__":
|