Spaces:
Sleeping
Sleeping
Optimize deployment: Implement lazy-loading architecture to resolve HuggingFace startup timeouts
Browse files- backend/app.py +34 -21
backend/app.py
CHANGED
|
@@ -3,21 +3,6 @@ from fastapi import FastAPI, HTTPException, Query
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data, fetch_india_vix
|
| 6 |
-
from sentiment import analyze_sentiment
|
| 7 |
-
from model import train_and_predict
|
| 8 |
-
from technical_signals import score_technical_signals
|
| 9 |
-
from llm_analysis import analyze_with_llm
|
| 10 |
-
from intraday_model import generate_intraday_signal
|
| 11 |
-
from reliability_scoring import calculate_long_term_reliability
|
| 12 |
-
from dynamic_params import DynamicParams, KEYS
|
| 13 |
-
from feedback_engine import FeedbackEngine
|
| 14 |
-
from llm_vision_analysis import LLMVisionEngine
|
| 15 |
-
from optimizer_agent import OptimizerAgent
|
| 16 |
-
from trader import (
|
| 17 |
-
get_portfolio, reset_portfolio, toggle_bot, evaluate_trade_signal,
|
| 18 |
-
execute_sell, check_position, add_to_balance, withdraw_from_balance,
|
| 19 |
-
get_wallet_transactions, get_value_history, execute_buy
|
| 20 |
-
)
|
| 21 |
import concurrent.futures
|
| 22 |
|
| 23 |
app = FastAPI(title="StockSense AI", version="3.0.0")
|
|
@@ -43,11 +28,8 @@ def health():
|
|
| 43 |
|
| 44 |
@app.post("/reset")
|
| 45 |
def reset_environment():
|
| 46 |
-
"""
|
| 47 |
-
OpenEnv grader hook — resets the trading environment to a clean state.
|
| 48 |
-
Called by the hackathon platform before running automated evaluation.
|
| 49 |
-
"""
|
| 50 |
try:
|
|
|
|
| 51 |
result = reset_portfolio()
|
| 52 |
return {"status": "ok", "message": "Environment reset successfully.", "portfolio": result}
|
| 53 |
except Exception as e:
|
|
@@ -152,6 +134,10 @@ def get_market_indices():
|
|
| 152 |
|
| 153 |
@app.get("/api/predict/{ticker}")
|
| 154 |
def predict(ticker: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
try:
|
| 156 |
df = fetch_stock_data(ticker)
|
| 157 |
df = add_technical_indicators(df)
|
|
@@ -219,6 +205,7 @@ def predict(ticker: str):
|
|
| 219 |
@app.get("/api/sentiment/{ticker}")
|
| 220 |
def sentiment(ticker: str):
|
| 221 |
try:
|
|
|
|
| 222 |
return analyze_sentiment(ticker)
|
| 223 |
except Exception as e:
|
| 224 |
raise HTTPException(status_code=400, detail=str(e))
|
|
@@ -226,6 +213,10 @@ def sentiment(ticker: str):
|
|
| 226 |
|
| 227 |
@app.get("/api/summary/{ticker}")
|
| 228 |
def summary(ticker: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
try:
|
| 230 |
info = get_stock_info(ticker)
|
| 231 |
df = fetch_stock_data(ticker)
|
|
@@ -496,6 +487,7 @@ def high_potential():
|
|
| 496 |
|
| 497 |
@app.get("/api/trade/portfolio")
|
| 498 |
def trade_portfolio():
|
|
|
|
| 499 |
try:
|
| 500 |
portfolio = get_portfolio()
|
| 501 |
total_unrealized = 0
|
|
@@ -539,16 +531,22 @@ def trade_portfolio():
|
|
| 539 |
|
| 540 |
@app.post("/api/trade/reset")
|
| 541 |
def trade_reset():
|
|
|
|
| 542 |
return reset_portfolio()
|
| 543 |
|
| 544 |
|
| 545 |
@app.post("/api/trade/toggle")
|
| 546 |
def trade_toggle():
|
|
|
|
| 547 |
return toggle_bot()
|
| 548 |
|
| 549 |
|
| 550 |
@app.post("/api/trade/execute/{ticker}")
|
| 551 |
def trade_execute(ticker: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
try:
|
| 553 |
live = fetch_live_price(ticker)
|
| 554 |
current_price = live["price"]
|
|
@@ -609,6 +607,7 @@ def trade_execute(ticker: str):
|
|
| 609 |
|
| 610 |
@app.post("/api/trade/sell/{ticker}")
|
| 611 |
def trade_force_sell(ticker: str):
|
|
|
|
| 612 |
try:
|
| 613 |
live = fetch_live_price(ticker)
|
| 614 |
result = execute_sell(ticker, live["price"], "Manual sell (forced)")
|
|
@@ -619,6 +618,7 @@ def trade_force_sell(ticker: str):
|
|
| 619 |
|
| 620 |
@app.get("/api/trade/check/{ticker}")
|
| 621 |
def trade_check(ticker: str):
|
|
|
|
| 622 |
try:
|
| 623 |
live = fetch_live_price(ticker)
|
| 624 |
result = check_position(ticker, live["price"])
|
|
@@ -631,6 +631,7 @@ def trade_check(ticker: str):
|
|
| 631 |
@app.get("/api/trade/intraday-signal/{ticker}")
|
| 632 |
def trade_intraday_signal(ticker: str):
|
| 633 |
"""Single-stock intraday signal using XGBoost pipeline."""
|
|
|
|
| 634 |
try:
|
| 635 |
signal = generate_intraday_signal(ticker)
|
| 636 |
return signal
|
|
@@ -641,6 +642,8 @@ def trade_intraday_signal(ticker: str):
|
|
| 641 |
@app.post("/api/trade/auto-scan")
|
| 642 |
def trade_auto_scan():
|
| 643 |
"""Auto-scan using intraday XGBoost pipeline with dynamic SL/TP."""
|
|
|
|
|
|
|
| 644 |
try:
|
| 645 |
portfolio = get_portfolio()
|
| 646 |
if not portfolio["bot_active"]:
|
|
@@ -706,6 +709,7 @@ class WithdrawRequest(BaseModel):
|
|
| 706 |
@app.get("/api/wallet/balance")
|
| 707 |
def wallet_balance():
|
| 708 |
"""Return wallet balance (= portfolio cash balance)."""
|
|
|
|
| 709 |
portfolio = get_portfolio()
|
| 710 |
return {"balance": portfolio["balance"], "status": "success"}
|
| 711 |
|
|
@@ -713,6 +717,7 @@ def wallet_balance():
|
|
| 713 |
@app.post("/api/wallet/add")
|
| 714 |
def wallet_add(req: AddMoneyRequest):
|
| 715 |
"""Credit wallet after Razorpay payment."""
|
|
|
|
| 716 |
if req.amount <= 0:
|
| 717 |
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 718 |
result = add_to_balance(req.amount, req.payment_id)
|
|
@@ -722,6 +727,7 @@ def wallet_add(req: AddMoneyRequest):
|
|
| 722 |
@app.post("/api/wallet/withdraw")
|
| 723 |
def wallet_withdraw(req: WithdrawRequest):
|
| 724 |
"""Withdraw from wallet (portfolio cash)."""
|
|
|
|
| 725 |
if req.amount <= 0:
|
| 726 |
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 727 |
result = withdraw_from_balance(req.amount)
|
|
@@ -733,6 +739,7 @@ def wallet_withdraw(req: WithdrawRequest):
|
|
| 733 |
@app.get("/api/wallet/transactions")
|
| 734 |
def wallet_transactions():
|
| 735 |
"""Return wallet transaction history."""
|
|
|
|
| 736 |
txns = get_wallet_transactions()
|
| 737 |
return {"transactions": txns, "status": "success"}
|
| 738 |
|
|
@@ -740,6 +747,7 @@ def wallet_transactions():
|
|
| 740 |
@app.get("/api/portfolio/value-history")
|
| 741 |
def portfolio_value_history():
|
| 742 |
"""Return portfolio value snapshots for the account value chart."""
|
|
|
|
| 743 |
try:
|
| 744 |
snapshots = get_value_history()
|
| 745 |
return {"snapshots": snapshots, "status": "success"}
|
|
@@ -749,6 +757,8 @@ def portfolio_value_history():
|
|
| 749 |
@app.get("/api/dashboard/{ticker}")
|
| 750 |
def dashboard_data(ticker: str):
|
| 751 |
"""Aggregate payload for the frontend Company Dashboard."""
|
|
|
|
|
|
|
| 752 |
try:
|
| 753 |
import yfinance as yf
|
| 754 |
import re
|
|
@@ -769,8 +779,6 @@ def dashboard_data(ticker: str):
|
|
| 769 |
}
|
| 770 |
|
| 771 |
# 2. Full yfinance info for profile / fundamentals
|
| 772 |
-
# get_stock_info() returns a trimmed dict; we need the raw .info for
|
| 773 |
-
# longBusinessSummary, industry, sector, employees, freeCashflow, etc.
|
| 774 |
stock_obj = yf.Ticker(ticker)
|
| 775 |
try:
|
| 776 |
yinfo = stock_obj.info or {}
|
|
@@ -866,6 +874,7 @@ def dashboard_data(ticker: str):
|
|
| 866 |
@app.get("/api/engine/performance")
|
| 867 |
def engine_performance(days: int = 7):
|
| 868 |
"""Get the accuracy and performance metrics of the AI engine."""
|
|
|
|
| 869 |
try:
|
| 870 |
stats = FeedbackEngine.get_accuracy_report(days=days)
|
| 871 |
return {"status": "success", "performance": stats}
|
|
@@ -875,6 +884,7 @@ def engine_performance(days: int = 7):
|
|
| 875 |
@app.get("/api/engine/params")
|
| 876 |
def engine_params():
|
| 877 |
"""Get the current dynamic parameters used by the bot."""
|
|
|
|
| 878 |
try:
|
| 879 |
# Load active dynamic parameters to merge logically with the display parameters
|
| 880 |
active_params = DynamicParams.get_all()
|
|
@@ -896,6 +906,7 @@ def engine_params():
|
|
| 896 |
@app.post("/api/engine/optimize")
|
| 897 |
def engine_optimize():
|
| 898 |
"""Trigger the Optimizer Agent to tune parameters based on recent performance."""
|
|
|
|
| 899 |
try:
|
| 900 |
agent = OptimizerAgent()
|
| 901 |
result = agent.run_optimization()
|
|
@@ -906,6 +917,7 @@ def engine_optimize():
|
|
| 906 |
@app.post("/api/engine/resolve")
|
| 907 |
def engine_resolve():
|
| 908 |
"""Manually trigger resolution of pending predictions."""
|
|
|
|
| 909 |
try:
|
| 910 |
prices = {}
|
| 911 |
for t in SCAN_TICKERS[:10]:
|
|
@@ -922,6 +934,7 @@ def engine_resolve():
|
|
| 922 |
@app.get("/api/predict/vision/{ticker}")
|
| 923 |
def predict_vision(ticker: str):
|
| 924 |
"""Multimodal prediction using Gemini Vision on the live chart."""
|
|
|
|
| 925 |
try:
|
| 926 |
df = fetch_stock_data(ticker)
|
| 927 |
df = add_technical_indicators(df)
|
|
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data, fetch_india_vix
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import concurrent.futures
|
| 7 |
|
| 8 |
app = FastAPI(title="StockSense AI", version="3.0.0")
|
|
|
|
| 28 |
|
| 29 |
@app.post("/reset")
|
| 30 |
def reset_environment():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
+
from trader import reset_portfolio
|
| 33 |
result = reset_portfolio()
|
| 34 |
return {"status": "ok", "message": "Environment reset successfully.", "portfolio": result}
|
| 35 |
except Exception as e:
|
|
|
|
| 134 |
|
| 135 |
@app.get("/api/predict/{ticker}")
|
| 136 |
def predict(ticker: str):
|
| 137 |
+
from sentiment import analyze_sentiment
|
| 138 |
+
from model import train_and_predict
|
| 139 |
+
from technical_signals import score_technical_signals
|
| 140 |
+
from llm_analysis import analyze_with_llm
|
| 141 |
try:
|
| 142 |
df = fetch_stock_data(ticker)
|
| 143 |
df = add_technical_indicators(df)
|
|
|
|
| 205 |
@app.get("/api/sentiment/{ticker}")
|
| 206 |
def sentiment(ticker: str):
|
| 207 |
try:
|
| 208 |
+
from sentiment import analyze_sentiment
|
| 209 |
return analyze_sentiment(ticker)
|
| 210 |
except Exception as e:
|
| 211 |
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
| 213 |
|
| 214 |
@app.get("/api/summary/{ticker}")
|
| 215 |
def summary(ticker: str):
|
| 216 |
+
from sentiment import analyze_sentiment
|
| 217 |
+
from model import train_and_predict
|
| 218 |
+
from technical_signals import score_technical_signals
|
| 219 |
+
from llm_analysis import analyze_with_llm
|
| 220 |
try:
|
| 221 |
info = get_stock_info(ticker)
|
| 222 |
df = fetch_stock_data(ticker)
|
|
|
|
| 487 |
|
| 488 |
@app.get("/api/trade/portfolio")
|
| 489 |
def trade_portfolio():
|
| 490 |
+
from trader import get_portfolio
|
| 491 |
try:
|
| 492 |
portfolio = get_portfolio()
|
| 493 |
total_unrealized = 0
|
|
|
|
| 531 |
|
| 532 |
@app.post("/api/trade/reset")
|
| 533 |
def trade_reset():
|
| 534 |
+
from trader import reset_portfolio
|
| 535 |
return reset_portfolio()
|
| 536 |
|
| 537 |
|
| 538 |
@app.post("/api/trade/toggle")
|
| 539 |
def trade_toggle():
|
| 540 |
+
from trader import toggle_bot
|
| 541 |
return toggle_bot()
|
| 542 |
|
| 543 |
|
| 544 |
@app.post("/api/trade/execute/{ticker}")
|
| 545 |
def trade_execute(ticker: str):
|
| 546 |
+
from sentiment import analyze_sentiment
|
| 547 |
+
from technical_signals import score_technical_signals
|
| 548 |
+
from model import train_and_predict
|
| 549 |
+
from trader import evaluate_trade_signal
|
| 550 |
try:
|
| 551 |
live = fetch_live_price(ticker)
|
| 552 |
current_price = live["price"]
|
|
|
|
| 607 |
|
| 608 |
@app.post("/api/trade/sell/{ticker}")
|
| 609 |
def trade_force_sell(ticker: str):
|
| 610 |
+
from trader import execute_sell
|
| 611 |
try:
|
| 612 |
live = fetch_live_price(ticker)
|
| 613 |
result = execute_sell(ticker, live["price"], "Manual sell (forced)")
|
|
|
|
| 618 |
|
| 619 |
@app.get("/api/trade/check/{ticker}")
|
| 620 |
def trade_check(ticker: str):
|
| 621 |
+
from trader import check_position
|
| 622 |
try:
|
| 623 |
live = fetch_live_price(ticker)
|
| 624 |
result = check_position(ticker, live["price"])
|
|
|
|
| 631 |
@app.get("/api/trade/intraday-signal/{ticker}")
|
| 632 |
def trade_intraday_signal(ticker: str):
|
| 633 |
"""Single-stock intraday signal using XGBoost pipeline."""
|
| 634 |
+
from intraday_model import generate_intraday_signal
|
| 635 |
try:
|
| 636 |
signal = generate_intraday_signal(ticker)
|
| 637 |
return signal
|
|
|
|
| 642 |
@app.post("/api/trade/auto-scan")
|
| 643 |
def trade_auto_scan():
|
| 644 |
"""Auto-scan using intraday XGBoost pipeline with dynamic SL/TP."""
|
| 645 |
+
from trader import get_portfolio, check_position, execute_sell, execute_buy
|
| 646 |
+
from intraday_model import generate_intraday_signal
|
| 647 |
try:
|
| 648 |
portfolio = get_portfolio()
|
| 649 |
if not portfolio["bot_active"]:
|
|
|
|
| 709 |
@app.get("/api/wallet/balance")
|
| 710 |
def wallet_balance():
|
| 711 |
"""Return wallet balance (= portfolio cash balance)."""
|
| 712 |
+
from trader import get_portfolio
|
| 713 |
portfolio = get_portfolio()
|
| 714 |
return {"balance": portfolio["balance"], "status": "success"}
|
| 715 |
|
|
|
|
| 717 |
@app.post("/api/wallet/add")
|
| 718 |
def wallet_add(req: AddMoneyRequest):
|
| 719 |
"""Credit wallet after Razorpay payment."""
|
| 720 |
+
from trader import add_to_balance
|
| 721 |
if req.amount <= 0:
|
| 722 |
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 723 |
result = add_to_balance(req.amount, req.payment_id)
|
|
|
|
| 727 |
@app.post("/api/wallet/withdraw")
|
| 728 |
def wallet_withdraw(req: WithdrawRequest):
|
| 729 |
"""Withdraw from wallet (portfolio cash)."""
|
| 730 |
+
from trader import withdraw_from_balance
|
| 731 |
if req.amount <= 0:
|
| 732 |
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 733 |
result = withdraw_from_balance(req.amount)
|
|
|
|
| 739 |
@app.get("/api/wallet/transactions")
|
| 740 |
def wallet_transactions():
|
| 741 |
"""Return wallet transaction history."""
|
| 742 |
+
from trader import get_wallet_transactions
|
| 743 |
txns = get_wallet_transactions()
|
| 744 |
return {"transactions": txns, "status": "success"}
|
| 745 |
|
|
|
|
| 747 |
@app.get("/api/portfolio/value-history")
|
| 748 |
def portfolio_value_history():
|
| 749 |
"""Return portfolio value snapshots for the account value chart."""
|
| 750 |
+
from trader import get_value_history
|
| 751 |
try:
|
| 752 |
snapshots = get_value_history()
|
| 753 |
return {"snapshots": snapshots, "status": "success"}
|
|
|
|
| 757 |
@app.get("/api/dashboard/{ticker}")
|
| 758 |
def dashboard_data(ticker: str):
|
| 759 |
"""Aggregate payload for the frontend Company Dashboard."""
|
| 760 |
+
from sentiment import analyze_sentiment
|
| 761 |
+
from reliability_scoring import calculate_long_term_reliability
|
| 762 |
try:
|
| 763 |
import yfinance as yf
|
| 764 |
import re
|
|
|
|
| 779 |
}
|
| 780 |
|
| 781 |
# 2. Full yfinance info for profile / fundamentals
|
|
|
|
|
|
|
| 782 |
stock_obj = yf.Ticker(ticker)
|
| 783 |
try:
|
| 784 |
yinfo = stock_obj.info or {}
|
|
|
|
| 874 |
@app.get("/api/engine/performance")
|
| 875 |
def engine_performance(days: int = 7):
|
| 876 |
"""Get the accuracy and performance metrics of the AI engine."""
|
| 877 |
+
from feedback_engine import FeedbackEngine
|
| 878 |
try:
|
| 879 |
stats = FeedbackEngine.get_accuracy_report(days=days)
|
| 880 |
return {"status": "success", "performance": stats}
|
|
|
|
| 884 |
@app.get("/api/engine/params")
|
| 885 |
def engine_params():
|
| 886 |
"""Get the current dynamic parameters used by the bot."""
|
| 887 |
+
from dynamic_params import DynamicParams
|
| 888 |
try:
|
| 889 |
# Load active dynamic parameters to merge logically with the display parameters
|
| 890 |
active_params = DynamicParams.get_all()
|
|
|
|
| 906 |
@app.post("/api/engine/optimize")
|
| 907 |
def engine_optimize():
|
| 908 |
"""Trigger the Optimizer Agent to tune parameters based on recent performance."""
|
| 909 |
+
from optimizer_agent import OptimizerAgent
|
| 910 |
try:
|
| 911 |
agent = OptimizerAgent()
|
| 912 |
result = agent.run_optimization()
|
|
|
|
| 917 |
@app.post("/api/engine/resolve")
|
| 918 |
def engine_resolve():
|
| 919 |
"""Manually trigger resolution of pending predictions."""
|
| 920 |
+
from feedback_engine import FeedbackEngine
|
| 921 |
try:
|
| 922 |
prices = {}
|
| 923 |
for t in SCAN_TICKERS[:10]:
|
|
|
|
| 934 |
@app.get("/api/predict/vision/{ticker}")
|
| 935 |
def predict_vision(ticker: str):
|
| 936 |
"""Multimodal prediction using Gemini Vision on the live chart."""
|
| 937 |
+
from llm_vision_analysis import LLMVisionEngine
|
| 938 |
try:
|
| 939 |
df = fetch_stock_data(ticker)
|
| 940 |
df = add_technical_indicators(df)
|