steviebaraik commited on
Commit
db89292
·
2 Parent(s): c34cf1f3a00d16

Merge HF remote — keep project files

Browse files
.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ .env
4
+ .venv
5
+ venv
6
+ .git
7
+ .gitignore
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Hugging Face Spaces Docker deployment ────────────────────────────────────
2
+ FROM python:3.12-slim
3
+
4
+ # System deps for numpy/scipy/statsmodels
5
+ RUN apt-get update && \
6
+ apt-get install -y --no-install-recommends gcc g++ && \
7
+ rm -rf /var/lib/apt/lists/*
8
+
9
+ WORKDIR /app
10
+
11
+ # Install Python dependencies
12
+ COPY requirements.txt .
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ # Copy application code
16
+ COPY . .
17
+
18
+ # HF Spaces uses port 7860
19
+ EXPOSE 7860
20
+
21
+ # Run with uvicorn — HF Spaces sets secrets as env vars automatically
22
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
app/__init__.py ADDED
File without changes
app/api/__init__.py ADDED
File without changes
app/api/routes/__init__.py ADDED
File without changes
app/api/routes/advanced_analytics.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """API routes for advanced analytics: Sector Rotation, GARCH, Macro, Risk Factors."""
2
+
3
+ from fastapi import APIRouter, HTTPException, Query
4
+
5
+ from ...schemas.advanced_analytics import (
6
+ SectorRotationResponse,
7
+ VolatilityForecastResponse,
8
+ VolSymbol,
9
+ MacroDashboardResponse,
10
+ RiskFactorRequest,
11
+ RiskFactorResponse,
12
+ )
13
+ from ...services.sector_rotation import get_sector_rotation
14
+ from ...services.volatility import get_volatility_forecast, get_vol_symbols
15
+ from ...services.macro import get_macro_dashboard
16
+ from ...services.risk_factors import get_risk_factors
17
+
18
+ router = APIRouter(prefix="/advanced", tags=["Advanced Analytics"])
19
+
20
+
21
+ # ── Sector Rotation ──────────────────────────────────────────────────────────
22
+
23
+ @router.get("/sector-rotation", response_model=SectorRotationResponse)
24
+ async def sector_rotation(force: bool = Query(False)):
25
+ """Sector momentum rankings, rotation signals, and market phase."""
26
+ try:
27
+ return await get_sector_rotation(force=force)
28
+ except Exception as e:
29
+ raise HTTPException(status_code=500, detail=str(e))
30
+
31
+
32
+ # ── Volatility Forecasting ───────────────────────────────────────────────────
33
+
34
+ @router.get("/volatility/{symbol}", response_model=VolatilityForecastResponse)
35
+ async def volatility_forecast(symbol: str):
36
+ """GARCH(1,1) volatility forecast with vol cones and regime detection."""
37
+ try:
38
+ return await get_volatility_forecast(symbol)
39
+ except ValueError as e:
40
+ raise HTTPException(status_code=404, detail=str(e))
41
+ except Exception as e:
42
+ raise HTTPException(status_code=500, detail=str(e))
43
+
44
+
45
+ @router.get("/volatility-symbols", response_model=list[VolSymbol])
46
+ async def volatility_symbols():
47
+ """List available symbols for volatility analysis."""
48
+ return await get_vol_symbols()
49
+
50
+
51
+ # ── Macro Dashboard ──────────────────────────────────────────────────────────
52
+
53
+ @router.get("/macro", response_model=MacroDashboardResponse)
54
+ async def macro_dashboard(force: bool = Query(False)):
55
+ """Macro indicators, correlations, and market regime classification."""
56
+ try:
57
+ return await get_macro_dashboard(force=force)
58
+ except Exception as e:
59
+ raise HTTPException(status_code=500, detail=str(e))
60
+
61
+
62
+ # ── Risk Factor Decomposition ────────────────────────────────────────────────
63
+
64
+ @router.post("/risk-factors", response_model=RiskFactorResponse)
65
+ async def risk_factors(req: RiskFactorRequest):
66
+ """Fama-French-style factor decomposition for given stocks."""
67
+ try:
68
+ return await get_risk_factors(req.symbols)
69
+ except ValueError as e:
70
+ raise HTTPException(status_code=400, detail=str(e))
71
+ except Exception as e:
72
+ raise HTTPException(status_code=500, detail=str(e))
app/api/routes/advisor.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import StreamingResponse
3
+ from ...schemas.financial import AdvisorChatRequest, AdvisorChatResponse
4
+ from ...services.ai_advisor import get_advisor_response, stream_advisor_response
5
+
6
+ router = APIRouter(prefix="/advisor", tags=["AI Advisor"])
7
+
8
+
9
+ @router.post("/chat", response_model=AdvisorChatResponse)
10
+ async def chat(req: AdvisorChatRequest):
11
+ """Non-streaming fallback."""
12
+ return await get_advisor_response(req)
13
+
14
+
15
+ @router.post("/chat/stream")
16
+ async def chat_stream(req: AdvisorChatRequest):
17
+ """Streaming endpoint — returns SSE tokens."""
18
+ return StreamingResponse(
19
+ stream_advisor_response(req),
20
+ media_type="text/event-stream",
21
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
22
+ )
app/api/routes/analytics.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analytics API routes — thin controllers delegating to the analytics service."""
2
+
3
+ from typing import Optional
4
+ from fastapi import APIRouter, Query, HTTPException
5
+
6
+ from ...schemas.analytics import (
7
+ MarketOverview,
8
+ TechnicalSignal,
9
+ StockAnalysis,
10
+ PortfolioOptimizationResult,
11
+ PortfolioOptimizeRequest,
12
+ CorrelationMatrix,
13
+ ScreenerResponse,
14
+ AnalyticsReport,
15
+ BacktestResult,
16
+ SmartPortfolioRequest,
17
+ SmartPortfolioResponse,
18
+ TimeSeriesAnalysisResult,
19
+ )
20
+ from ...services import analytics as svc
21
+ from ...services import timeseries as ts_svc
22
+
23
+ router = APIRouter(prefix="/analytics", tags=["analytics"])
24
+
25
+
26
+ @router.get("/market-overview", response_model=MarketOverview)
27
+ def market_overview():
28
+ """Sector heatmap, top gainers/losers, anomaly alerts, market breadth."""
29
+ return svc.get_market_overview()
30
+
31
+
32
+ @router.get("/stock-signals", response_model=list[TechnicalSignal])
33
+ def stock_signals(
34
+ direction: Optional[str] = Query(None, description="BUY | HOLD | SELL"),
35
+ limit: int = Query(10, ge=1, le=30),
36
+ ):
37
+ """Return technical signals for tracked stocks, optionally filtered by direction."""
38
+ signals = []
39
+ for sym in svc.get_stock_universe():
40
+ df = svc._get_cached_df(sym, "1y")
41
+ if df is None or df.empty:
42
+ continue
43
+ sig = svc.compute_technical_signals(sym, df)
44
+ if direction and sig.composite_signal.value != direction:
45
+ continue
46
+ signals.append(sig)
47
+
48
+ signals.sort(key=lambda s: s.confidence_score, reverse=True)
49
+ return signals[:limit]
50
+
51
+
52
+ @router.get("/stock/{symbol}", response_model=StockAnalysis)
53
+ def stock_analysis(symbol: str):
54
+ """On-demand full analysis for a single stock."""
55
+ import pandas as pd
56
+ df = svc._get_cached_df(symbol, "1y")
57
+ if df is None or df.empty:
58
+ raise HTTPException(status_code=404, detail=f"No data found for symbol: {symbol}")
59
+ _nifty = svc._get_cached_df(svc.NIFTY_INDEX, "1y")
60
+ nifty_df = _nifty if _nifty is not None else pd.DataFrame()
61
+ signals = svc.compute_technical_signals(symbol, df)
62
+ risk = svc.compute_risk_metrics(symbol, df, nifty_df)
63
+ prob_up, rf_sig = svc.train_rf_classifier(df, symbol=symbol)
64
+ anomalies = svc.detect_anomalies(symbol, df)
65
+ return StockAnalysis(
66
+ symbol=symbol,
67
+ company_name=svc.get_stock_name(symbol),
68
+ sector=svc.get_stock_sector(symbol),
69
+ technical_signals=signals,
70
+ risk_metrics=risk,
71
+ rf_probability=prob_up,
72
+ rf_signal=rf_sig,
73
+ anomalies=anomalies,
74
+ )
75
+
76
+
77
+ @router.post("/portfolio-optimize", response_model=PortfolioOptimizationResult)
78
+ def portfolio_optimize(body: PortfolioOptimizeRequest):
79
+ """Run Monte Carlo + scipy portfolio optimisation for a set of symbols."""
80
+ result = svc.optimize_portfolio(body.symbols, body.risk_profile, body.n_portfolios)
81
+ if result is None:
82
+ raise HTTPException(status_code=422, detail="Not enough valid data for optimisation")
83
+ return result
84
+
85
+
86
+ @router.get("/correlation", response_model=CorrelationMatrix)
87
+ def correlation(
88
+ symbols: Optional[str] = Query(None, description="Comma-separated symbols; defaults to top 15"),
89
+ ):
90
+ """Pearson correlation matrix for daily returns."""
91
+ sym_list = [s.strip() for s in symbols.split(",")] if symbols else svc.get_stock_universe()[:15]
92
+ return svc.compute_correlation_matrix(sym_list)
93
+
94
+
95
+ @router.get("/screener", response_model=ScreenerResponse)
96
+ def screener(
97
+ sector: Optional[str] = Query(None),
98
+ signal: Optional[str] = Query(None, description="BUY | HOLD | SELL"),
99
+ min_sharpe: Optional[float] = Query(None),
100
+ max_drawdown: Optional[float] = Query(None, description="Max acceptable drawdown magnitude (e.g. 20 means -20%)"),
101
+ sort_by: str = Query("composite_score"),
102
+ limit: int = Query(50, ge=1, le=500),
103
+ ):
104
+ """Filter and sort tracked stocks by signal, risk metrics and fundamentals."""
105
+ return svc.screen_stocks(sector, signal, min_sharpe, max_drawdown, sort_by, limit)
106
+
107
+
108
+ @router.get("/report", response_model=AnalyticsReport)
109
+ def analytics_report(force_refresh: bool = Query(False)):
110
+ """Full ML analytics report covering all stocks. First call may take a few minutes."""
111
+ return svc.get_analytics_report(force_refresh)
112
+
113
+
114
+ @router.get("/backtest/{symbol}", response_model=BacktestResult)
115
+ def backtest(symbol: str):
116
+ """Backtest the technical-signal strategy vs Nifty 50 benchmark."""
117
+ return svc.backtest_strategy(symbol)
118
+
119
+
120
+ @router.post("/smart-portfolio", response_model=SmartPortfolioResponse)
121
+ def smart_portfolio(body: SmartPortfolioRequest):
122
+ """Auto-select best stocks, optimise portfolio, and forecast each pick."""
123
+ return svc.build_smart_portfolio(body.risk_profile, body.top_n, body.n_portfolios)
124
+
125
+
126
+ @router.get("/timeseries/{symbol}", response_model=TimeSeriesAnalysisResult)
127
+ def timeseries_analysis(symbol: str, horizon: int = Query(30, ge=7, le=90)):
128
+ """ARIMA + ETS time-series analysis with decomposition and stationarity tests."""
129
+ result = ts_svc.run_timeseries_analysis(symbol, horizon)
130
+ if result is None:
131
+ raise HTTPException(status_code=404, detail=f"Not enough data for {symbol} (need ≥120 observations)")
132
+ return result
133
+
134
+
135
+ @router.get("/timeseries-symbols")
136
+ def timeseries_symbols():
137
+ """Return list of symbols available for time-series analysis."""
138
+ return ts_svc.get_available_symbols()
139
+
140
+
app/api/routes/planner.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from ...schemas.financial import (
3
+ ForwardPlannerRequest, ForwardPlannerResponse,
4
+ GoalPlannerRequest, GoalPlannerResponse,
5
+ )
6
+ from ...services.financial_engine import (
7
+ calculate_investable_surplus,
8
+ recommend_monthly_investment,
9
+ get_return_assumptions,
10
+ calculate_sip_future_value,
11
+ calculate_total_invested,
12
+ solve_required_sip,
13
+ build_sensitivity_table,
14
+ )
15
+ from ...services.monte_carlo import run_simulation
16
+
17
+ router = APIRouter(prefix="/planner", tags=["Planner"])
18
+
19
+
20
+ @router.post("/forward", response_model=ForwardPlannerResponse)
21
+ def forward_planner(req: ForwardPlannerRequest):
22
+ """
23
+ Given monthly SIP + horizon → project wealth with Monte Carlo simulation.
24
+ """
25
+ assumptions = get_return_assumptions(req.profile.risk_profile)
26
+ return_pct = req.expected_annual_return_pct or assumptions["expected"]
27
+ std_dev = assumptions["std_dev"]
28
+
29
+ investable_surplus = calculate_investable_surplus(req.profile)
30
+ recommended_sip = recommend_monthly_investment(req.profile)
31
+ total_invested = calculate_total_invested(req.monthly_investment, req.horizon_years, req.annual_stepup_pct)
32
+
33
+ mc = run_simulation(
34
+ monthly_investment=req.monthly_investment,
35
+ annual_return_pct=return_pct,
36
+ annual_std_dev_pct=std_dev,
37
+ years=req.horizon_years,
38
+ annual_stepup_pct=req.annual_stepup_pct,
39
+ existing_corpus=req.profile.current_savings,
40
+ simulations=req.simulations,
41
+ )
42
+
43
+ return ForwardPlannerResponse(
44
+ monthly_investment=req.monthly_investment,
45
+ annual_stepup_pct=req.annual_stepup_pct,
46
+ horizon_years=req.horizon_years,
47
+ expected_annual_return_pct=return_pct,
48
+ investable_surplus=investable_surplus,
49
+ recommended_monthly_investment=recommended_sip,
50
+ total_invested=total_invested,
51
+ monte_carlo=mc,
52
+ asset_allocation=assumptions["allocation"],
53
+ )
54
+
55
+
56
+ @router.post("/goal", response_model=GoalPlannerResponse)
57
+ def goal_planner(req: GoalPlannerRequest):
58
+ """
59
+ Given a target corpus + horizon → calculate required monthly SIP.
60
+ """
61
+ assumptions = get_return_assumptions(req.profile.risk_profile)
62
+ return_pct = req.expected_annual_return_pct or assumptions["expected"]
63
+
64
+ investable_surplus = calculate_investable_surplus(req.profile)
65
+ required_sip = solve_required_sip(
66
+ target_amount=req.target_amount,
67
+ annual_return_pct=return_pct,
68
+ years=req.horizon_years,
69
+ annual_stepup_pct=req.annual_stepup_pct,
70
+ existing_corpus=req.profile.current_savings,
71
+ )
72
+ total_invested = calculate_total_invested(required_sip, req.horizon_years, req.annual_stepup_pct)
73
+ sensitivity = build_sensitivity_table(
74
+ target_amount=req.target_amount,
75
+ horizon_years=req.horizon_years,
76
+ annual_stepup_pct=req.annual_stepup_pct,
77
+ existing_corpus=req.profile.current_savings,
78
+ base_return_pct=return_pct,
79
+ )
80
+
81
+ return GoalPlannerResponse(
82
+ target_amount=req.target_amount,
83
+ horizon_years=req.horizon_years,
84
+ required_monthly_investment=required_sip,
85
+ total_invested=total_invested,
86
+ expected_annual_return_pct=return_pct,
87
+ is_achievable_within_surplus=required_sip <= investable_surplus,
88
+ investable_surplus=investable_surplus,
89
+ sensitivity=sensitivity,
90
+ asset_allocation=assumptions["allocation"],
91
+ )
app/api/routes/portfolio.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """API routes for Watchlist, Portfolio Tracker, and News Sentiment."""
2
+
3
+ from fastapi import APIRouter, HTTPException, Query
4
+
5
+ from ...schemas.portfolio import (
6
+ WatchlistResponse, WatchlistAddRequest, WatchlistItem,
7
+ PortfolioResponse, HoldingInput, PortfolioHolding,
8
+ NewsSentimentResponse,
9
+ AIBuildRequest, AIBuildResponse,
10
+ )
11
+ from ...services.portfolio import (
12
+ get_watchlist, add_to_watchlist, remove_from_watchlist,
13
+ get_portfolio, add_holding, remove_holding,
14
+ )
15
+ from ...services.news_sentiment import get_news_sentiment
16
+
17
+ router = APIRouter(prefix="/portfolio", tags=["Portfolio & Watchlist"])
18
+
19
+
20
+ # ── Watchlist ────────────────────────────────────────────────────────────────
21
+
22
+ @router.get("/watchlist", response_model=WatchlistResponse)
23
+ async def list_watchlist():
24
+ """Get all watchlist items with live prices."""
25
+ try:
26
+ return await get_watchlist()
27
+ except Exception as e:
28
+ raise HTTPException(status_code=500, detail=str(e))
29
+
30
+
31
+ @router.post("/watchlist", response_model=WatchlistItem)
32
+ async def add_watchlist(req: WatchlistAddRequest):
33
+ """Add a stock to the watchlist."""
34
+ try:
35
+ return await add_to_watchlist(req)
36
+ except Exception as e:
37
+ detail = str(e)
38
+ if "duplicate" in detail.lower() or "unique" in detail.lower() or "409" in detail:
39
+ raise HTTPException(status_code=409, detail="Stock already in watchlist")
40
+ raise HTTPException(status_code=500, detail=detail)
41
+
42
+
43
+ @router.delete("/watchlist/{item_id}")
44
+ async def delete_watchlist(item_id: int):
45
+ """Remove a stock from the watchlist."""
46
+ ok = await remove_from_watchlist(item_id)
47
+ if not ok:
48
+ raise HTTPException(status_code=404, detail="Item not found")
49
+ return {"ok": True}
50
+
51
+
52
+ # ── Portfolio Holdings ───────────────────────────────────────────────────────
53
+
54
+ @router.get("/holdings", response_model=PortfolioResponse)
55
+ async def list_holdings():
56
+ """Get all portfolio holdings with live P&L."""
57
+ try:
58
+ return await get_portfolio()
59
+ except Exception as e:
60
+ raise HTTPException(status_code=500, detail=str(e))
61
+
62
+
63
+ @router.post("/holdings", response_model=PortfolioHolding)
64
+ async def create_holding(req: HoldingInput):
65
+ """Add a new holding to the portfolio."""
66
+ try:
67
+ return await add_holding(req)
68
+ except Exception as e:
69
+ raise HTTPException(status_code=500, detail=str(e))
70
+
71
+
72
+ @router.delete("/holdings/{holding_id}")
73
+ async def delete_holding(holding_id: int):
74
+ """Remove a holding from the portfolio."""
75
+ ok = await remove_holding(holding_id)
76
+ if not ok:
77
+ raise HTTPException(status_code=404, detail="Holding not found")
78
+ return {"ok": True}
79
+
80
+
81
+ # ── AI Portfolio Builder ─────────────────────────────────────────────────────
82
+
83
+ @router.post("/ai-build", response_model=AIBuildResponse)
84
+ async def ai_build(req: AIBuildRequest):
85
+ """Use AI to select stocks and allocate quantities for a portfolio."""
86
+ from ...services.ai_portfolio import ai_build_portfolio
87
+ try:
88
+ return await ai_build_portfolio(req.investment_amount, req.risk_profile)
89
+ except RuntimeError as e:
90
+ raise HTTPException(status_code=503, detail=str(e))
91
+ except Exception as e:
92
+ raise HTTPException(status_code=500, detail=str(e))
93
+
94
+
95
+ # ── News Sentiment ───────────────────────────────────────────────────────────
96
+
97
+ @router.get("/news-sentiment", response_model=NewsSentimentResponse)
98
+ async def news_sentiment(force: bool = Query(False)):
99
+ """Aggregated news sentiment for Indian stocks."""
100
+ try:
101
+ return await get_news_sentiment(force=force)
102
+ except Exception as e:
103
+ raise HTTPException(status_code=500, detail=str(e))
app/api/routes/stocks.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import logging
3
+ from fastapi import APIRouter, Query, HTTPException
4
+ from ...core.database import get_db
5
+
6
+ logger = logging.getLogger(__name__)
7
+ router = APIRouter(prefix="/stocks", tags=["Stocks"])
8
+
9
+ # ─── Live indices cache ──────────────────────────────────────────────────────
10
+ _indices_cache: tuple[list[dict], float] = ([], 0.0)
11
+ _INDICES_TTL = 300 # 5 minutes
12
+
13
+
14
+ @router.get("/search")
15
+ def search_stocks(q: str = Query(..., min_length=1)):
16
+ """Search Indian stocks by symbol or company name, with latest prices."""
17
+ db = get_db()
18
+ result = (
19
+ db.table("stocks")
20
+ .select("symbol, company_name, exchange, sector, current_price, daily_change_pct, market_cap")
21
+ .or_(f"symbol.ilike.%{q}%,company_name.ilike.%{q}%")
22
+ .limit(20)
23
+ .execute()
24
+ )
25
+ stocks = result.data or []
26
+
27
+ # Enrich with latest prices from stock_prices for any stock missing current_price
28
+ for stock in stocks:
29
+ if stock.get("current_price") is not None:
30
+ continue
31
+ try:
32
+ price_result = (
33
+ db.table("stock_prices")
34
+ .select("close, date")
35
+ .eq("symbol", stock["symbol"])
36
+ .order("date", desc=True)
37
+ .limit(2)
38
+ .execute()
39
+ )
40
+ rows = price_result.data or []
41
+ if rows:
42
+ stock["current_price"] = rows[0]["close"]
43
+ if len(rows) >= 2 and rows[1]["close"] and rows[1]["close"] > 0:
44
+ change = (rows[0]["close"] - rows[1]["close"]) / rows[1]["close"] * 100
45
+ stock["daily_change_pct"] = round(change, 2)
46
+ else:
47
+ stock["daily_change_pct"] = 0.0
48
+ except Exception:
49
+ pass
50
+
51
+ return stocks
52
+
53
+
54
+ @router.get("/{symbol}")
55
+ def get_stock(symbol: str):
56
+ """Get full details for a stock symbol."""
57
+ db = get_db()
58
+ result = db.table("stocks").select("*").eq("symbol", symbol.upper()).single().execute()
59
+ if not result.data:
60
+ raise HTTPException(status_code=404, detail="Stock not found")
61
+ return result.data
62
+
63
+
64
+ @router.get("/{symbol}/history")
65
+ def get_stock_history(
66
+ symbol: str,
67
+ period: str = Query("1y", description="1m, 3m, 6m, 1y, 3y, 5y"),
68
+ ):
69
+ """Get historical OHLCV data for a stock."""
70
+ db = get_db()
71
+ period_days = {"1m": 30, "3m": 90, "6m": 180, "1y": 365, "3y": 1095, "5y": 1825}
72
+ days = period_days.get(period, 365)
73
+
74
+ result = (
75
+ db.table("stock_prices")
76
+ .select("date, open, high, low, close, volume")
77
+ .eq("symbol", symbol.upper())
78
+ .order("date", desc=False)
79
+ .limit(days)
80
+ .execute()
81
+ )
82
+ return result.data
83
+
84
+
85
+ @router.get("/indices/summary")
86
+ def get_indices_summary():
87
+ """Get current values for major Indian indices (Nifty 50, Sensex, Bank Nifty)."""
88
+ global _indices_cache
89
+ cached, ts = _indices_cache
90
+ if cached and time.time() - ts < _INDICES_TTL:
91
+ return cached
92
+
93
+ import yfinance as yf
94
+
95
+ INDEX_MAP = {
96
+ "^NSEI": "Nifty 50",
97
+ "^BSESN": "Sensex",
98
+ "^NSEBANK": "Bank Nifty",
99
+ }
100
+
101
+ results = []
102
+ for symbol, name in INDEX_MAP.items():
103
+ try:
104
+ ticker = yf.Ticker(symbol)
105
+ hist = ticker.history(period="5d")
106
+ if hist.empty:
107
+ continue
108
+ current = float(hist["Close"].iloc[-1])
109
+ prev = float(hist["Close"].iloc[-2]) if len(hist) >= 2 else current
110
+ change = current - prev
111
+ change_pct = (change / prev * 100) if prev > 0 else 0.0
112
+ results.append({
113
+ "symbol": symbol,
114
+ "name": name,
115
+ "current_value": round(current, 2),
116
+ "change": round(change, 2),
117
+ "change_pct": round(change_pct, 2),
118
+ })
119
+ except Exception as exc:
120
+ logger.warning("Failed to fetch index %s: %s", symbol, exc)
121
+
122
+ _indices_cache = (results, time.time())
123
+ return results
124
+
125
+
126
+ @router.get("/sectors/performance")
127
+ def get_sector_performance():
128
+ """Get average performance by sector for Indian stocks."""
129
+ db = get_db()
130
+ result = db.rpc("get_sector_performance").execute()
131
+ return result.data
app/core/__init__.py ADDED
File without changes
app/core/config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from pydantic_settings import BaseSettings
3
+ from functools import lru_cache
4
+
5
+ _ENV_FILE = Path(__file__).resolve().parents[3] / ".env"
6
+
7
+
8
+ class Settings(BaseSettings):
9
+ # App
10
+ app_env: str = "development"
11
+ backend_port: int = 8000
12
+ frontend_url: str = "http://localhost:5173"
13
+
14
+ # Supabase
15
+ supabase_url: str
16
+ supabase_anon_key: str
17
+ supabase_service_role_key: str
18
+
19
+ # Groq (LLM provider)
20
+ groq_api_key: str
21
+
22
+ # Alpha Vantage
23
+ alpha_vantage_api_key: str = ""
24
+
25
+ # Pipeline
26
+ nse_data_start_year: int = 2019
27
+
28
+ class Config:
29
+ env_file = str(_ENV_FILE) if _ENV_FILE.exists() else None
30
+ env_file_encoding = "utf-8"
31
+ extra = "ignore"
32
+
33
+
34
+ @lru_cache
35
+ def get_settings() -> Settings:
36
+ return Settings()
app/core/database.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Supabase REST API client using httpx (no supabase Python package needed).
3
+ Wraps PostgREST endpoints with a simple query builder.
4
+ """
5
+
6
+ import httpx
7
+ from .config import get_settings
8
+
9
+
10
+ class QueryBuilder:
11
+ def __init__(self, client: "SupabaseClient", table: str):
12
+ self._client = client
13
+ self._table = table
14
+ self._select_cols = "*"
15
+ self._filters: list[str] = []
16
+ self._order_col: str | None = None
17
+ self._order_desc = False
18
+ self._limit_val: int | None = None
19
+ self._single = False
20
+
21
+ def select(self, cols: str) -> "QueryBuilder":
22
+ self._select_cols = cols
23
+ return self
24
+
25
+ def eq(self, col: str, val: str) -> "QueryBuilder":
26
+ self._filters.append(f"{col}=eq.{val}")
27
+ return self
28
+
29
+ def or_(self, expr: str) -> "QueryBuilder":
30
+ self._filters.append(f"or=({expr})")
31
+ return self
32
+
33
+ def order(self, col: str, desc: bool = False) -> "QueryBuilder":
34
+ self._order_col = col
35
+ self._order_desc = desc
36
+ return self
37
+
38
+ def limit(self, n: int) -> "QueryBuilder":
39
+ self._limit_val = n
40
+ return self
41
+
42
+ def single(self) -> "QueryBuilder":
43
+ self._single = True
44
+ return self
45
+
46
+ def execute(self) -> "Result":
47
+ params: dict[str, str] = {"select": self._select_cols}
48
+ for f in self._filters:
49
+ if f.startswith("or="):
50
+ params["or"] = f[3:]
51
+ else:
52
+ k, v = f.split("=", 1)
53
+ params[k] = v
54
+ if self._order_col:
55
+ params["order"] = f"{self._order_col}.{'desc' if self._order_desc else 'asc'}"
56
+ if self._limit_val is not None:
57
+ params["limit"] = str(self._limit_val)
58
+
59
+ headers = dict(self._client._headers)
60
+ if self._single:
61
+ headers["Accept"] = "application/vnd.pgrst.object+json"
62
+
63
+ resp = httpx.get(
64
+ f"{self._client._base_url}/{self._table}",
65
+ headers=headers,
66
+ params=params,
67
+ timeout=15,
68
+ )
69
+ resp.raise_for_status()
70
+ data = resp.json()
71
+ return Result(data if not self._single else [data] if data else [])
72
+
73
+
74
+ class RpcBuilder:
75
+ def __init__(self, client: "SupabaseClient", fn: str):
76
+ self._client = client
77
+ self._fn = fn
78
+
79
+ def execute(self) -> "Result":
80
+ resp = httpx.post(
81
+ f"{self._client._base_url}/rpc/{self._fn}",
82
+ headers=self._client._headers,
83
+ timeout=15,
84
+ )
85
+ resp.raise_for_status()
86
+ return Result(resp.json())
87
+
88
+
89
+ class Result:
90
+ def __init__(self, data):
91
+ self.data = data
92
+
93
+
94
+ class SupabaseClient:
95
+ def __init__(self, url: str, key: str):
96
+ self._base_url = f"{url}/rest/v1"
97
+ self._headers = {
98
+ "apikey": key,
99
+ "Authorization": f"Bearer {key}",
100
+ "Content-Type": "application/json",
101
+ }
102
+
103
+ def table(self, name: str) -> QueryBuilder:
104
+ return QueryBuilder(self, name)
105
+
106
+ def rpc(self, fn: str) -> RpcBuilder:
107
+ return RpcBuilder(self, fn)
108
+
109
+
110
+ _client: SupabaseClient | None = None
111
+
112
+
113
+ def get_db() -> SupabaseClient:
114
+ global _client
115
+ if _client is None:
116
+ settings = get_settings()
117
+ _client = SupabaseClient(settings.supabase_url, settings.supabase_service_role_key)
118
+ return _client
app/main.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import threading
3
+ from contextlib import asynccontextmanager
4
+
5
+ from fastapi import FastAPI
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from .core.config import get_settings
8
+ from .api.routes import planner, advisor, stocks, analytics, advanced_analytics, portfolio
9
+
10
+ logger = logging.getLogger(__name__)
11
+ settings = get_settings()
12
+
13
+
14
+ def _prewarm_cache():
15
+ """Pre-warm: load all stock data from Supabase, then build analytics report."""
16
+ try:
17
+ from .services.analytics import preload_stock_data, get_analytics_report
18
+ logger.info("Pre-warming: loading stock data from Supabase…")
19
+ count = preload_stock_data()
20
+ logger.info("Loaded %d stocks into cache. Building analytics report…", count)
21
+ get_analytics_report(force_refresh=False)
22
+ logger.info("Analytics cache pre-warmed successfully.")
23
+ except Exception as exc:
24
+ logger.warning("Cache pre-warm failed (non-fatal): %s", exc)
25
+
26
+
27
+ @asynccontextmanager
28
+ async def lifespan(app: FastAPI):
29
+ from .scheduler import start_scheduler, stop_scheduler
30
+
31
+ # Startup: cache warm + scheduler
32
+ thread = threading.Thread(target=_prewarm_cache, daemon=True)
33
+ thread.start()
34
+ start_scheduler()
35
+
36
+ yield
37
+
38
+ # Shutdown
39
+ stop_scheduler()
40
+
41
+
42
+ app = FastAPI(
43
+ title="AI Investment Advisor",
44
+ description="Indian market investment planning with Monte Carlo simulations and AI advisory",
45
+ version="1.0.0",
46
+ lifespan=lifespan,
47
+ )
48
+
49
+ _origins = [settings.frontend_url, "http://localhost:5173", "https://paisapro.netlify.app"]
50
+ # Allow Hugging Face Spaces preview URLs
51
+ if settings.app_env == "production":
52
+ _origins.append("https://huggingface.co")
53
+
54
+ app.add_middleware(
55
+ CORSMiddleware,
56
+ allow_origins=_origins,
57
+ allow_credentials=True,
58
+ allow_methods=["*"],
59
+ allow_headers=["*"],
60
+ )
61
+
62
+ app.include_router(planner.router, prefix="/api/v1")
63
+ app.include_router(advisor.router, prefix="/api/v1")
64
+ app.include_router(stocks.router, prefix="/api/v1")
65
+ app.include_router(analytics.router, prefix="/api/v1")
66
+ app.include_router(advanced_analytics.router, prefix="/api/v1")
67
+ app.include_router(portfolio.router, prefix="/api/v1")
68
+
69
+
70
+ @app.get("/health")
71
+ def health():
72
+ return {"status": "ok", "service": "AI Investment Advisor Backend", "version": "1.1.0"}
app/scheduler.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Daily data refresh scheduler.
3
+
4
+ Runs at 6 PM IST (12:30 UTC) on weekdays to:
5
+ 1. Fetch today's prices for all tracked stocks via yfinance → Supabase
6
+ 2. Clear the analytics in-memory cache so next request rebuilds with fresh data
7
+ """
8
+
9
+ import logging
10
+ from apscheduler.schedulers.background import BackgroundScheduler
11
+ from apscheduler.triggers.cron import CronTrigger
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ _scheduler: BackgroundScheduler | None = None
16
+
17
+
18
+ def _daily_refresh():
19
+ """Fetch latest prices and invalidate analytics cache."""
20
+ try:
21
+ from .services.analytics import (
22
+ get_stock_universe, _get_cached_df, _df_cache, _report_cache,
23
+ get_analytics_report,
24
+ )
25
+
26
+ universe = get_stock_universe()
27
+ logger.info("Daily refresh: fetching latest prices for %d stocks…", len(universe))
28
+
29
+ # 1. Clear the in-memory cache so _get_cached_df re-fetches from yfinance
30
+ _df_cache.clear()
31
+
32
+ # 2. Force-fetch fresh data for each stock (saves to Supabase automatically)
33
+ success = 0
34
+ for sym in universe:
35
+ try:
36
+ df = _get_cached_df(sym, "1y")
37
+ if df is not None and not df.empty:
38
+ success += 1
39
+ except Exception as exc:
40
+ logger.warning("Refresh failed for %s: %s", sym, exc)
41
+
42
+ logger.info("Daily refresh: %d/%d stocks updated.", success, len(universe))
43
+
44
+ # 3. Invalidate the report cache so next request rebuilds
45
+ import app.services.analytics as svc
46
+ svc._report_cache = (None, 0.0)
47
+
48
+ # 4. Pre-warm the report cache
49
+ logger.info("Daily refresh: rebuilding analytics report…")
50
+ get_analytics_report(force_refresh=True)
51
+ logger.info("Daily refresh complete.")
52
+
53
+ except Exception as exc:
54
+ logger.error("Daily refresh error: %s", exc, exc_info=True)
55
+
56
+
57
+ def start_scheduler():
58
+ """Start the background scheduler. Safe to call multiple times."""
59
+ global _scheduler
60
+ if _scheduler is not None:
61
+ return
62
+
63
+ _scheduler = BackgroundScheduler(daemon=True)
64
+ # 6 PM IST = 12:30 UTC, weekdays only
65
+ _scheduler.add_job(
66
+ _daily_refresh,
67
+ trigger=CronTrigger(hour=12, minute=30, day_of_week="mon-fri"),
68
+ id="daily_price_refresh",
69
+ name="Daily price refresh (6 PM IST)",
70
+ replace_existing=True,
71
+ )
72
+ _scheduler.start()
73
+ logger.info("Scheduler started — daily refresh at 6 PM IST (12:30 UTC) on weekdays.")
74
+
75
+
76
+ def stop_scheduler():
77
+ """Shutdown the scheduler gracefully."""
78
+ global _scheduler
79
+ if _scheduler:
80
+ _scheduler.shutdown(wait=False)
81
+ _scheduler = None
app/schemas/__init__.py ADDED
File without changes
app/schemas/advanced_analytics.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic schemas for advanced analytics: Sector Rotation, GARCH, Macro, Risk Factors."""
2
+
3
+ from typing import Optional
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ # ── Sector Rotation ──────────────────────────────────────────────────────────
8
+
9
+ class SectorMomentum(BaseModel):
10
+ sector: str
11
+ stock_count: int
12
+ return_1m: float
13
+ return_3m: float
14
+ return_6m: float
15
+ return_12m: float
16
+ momentum_score: float # composite momentum rank
17
+ relative_strength: float # vs Nifty 50
18
+ signal: str # "OVERWEIGHT" | "UNDERWEIGHT" | "NEUTRAL"
19
+ avg_rsi: float
20
+ avg_volatility: float
21
+
22
+
23
+ class SectorRotationHistory(BaseModel):
24
+ date: str
25
+ sector: str
26
+ cumulative_return: float
27
+
28
+
29
+ class SectorRotationResponse(BaseModel):
30
+ sectors: list[SectorMomentum]
31
+ rotation_history: list[SectorRotationHistory] # last 12 months
32
+ leading_sectors: list[str] # top 3 by momentum
33
+ lagging_sectors: list[str] # bottom 3
34
+ market_phase: str # "EXPANSION" | "PEAK" | "CONTRACTION" | "TROUGH"
35
+ generated_at: str
36
+
37
+
38
+ # ── Volatility Forecasting (GARCH) ──────────────────────────────────────────
39
+
40
+ class VolatilityPoint(BaseModel):
41
+ date: str
42
+ realized_vol: Optional[float] = None # historical
43
+ forecast_vol: Optional[float] = None # GARCH forecast
44
+ lower: Optional[float] = None
45
+ upper: Optional[float] = None
46
+
47
+
48
+ class VolatilityConePoint(BaseModel):
49
+ horizon_days: int # 5, 10, 21, 63, 126, 252
50
+ current_vol: float
51
+ percentile_10: float
52
+ percentile_25: float
53
+ percentile_50: float
54
+ percentile_75: float
55
+ percentile_90: float
56
+
57
+
58
+ class VolatilityForecastResponse(BaseModel):
59
+ symbol: str
60
+ company_name: str
61
+ sector: str
62
+ current_price: float
63
+ current_realized_vol: float # 30-day annualized
64
+ garch_forecast_vol: float # next 30-day annualized
65
+ vol_regime: str # "LOW" | "NORMAL" | "HIGH" | "EXTREME"
66
+ entry_signal: str # "LOW_VOL_ENTRY" | "HIGH_VOL_CAUTION" | "NEUTRAL"
67
+ vol_percentile: float # current vol vs 1yr range (0-100)
68
+ history: list[VolatilityPoint] # last 6 months realized + 30 day forecast
69
+ vol_cone: list[VolatilityConePoint]
70
+ garch_params: dict # omega, alpha, beta, persistence
71
+ generated_at: str
72
+
73
+
74
+ class VolSymbol(BaseModel):
75
+ symbol: str
76
+ company_name: str
77
+ sector: str
78
+
79
+
80
+ # ── Macro Dashboard ──────────────────────────────────────────────────────────
81
+
82
+ class MacroIndicator(BaseModel):
83
+ name: str # "India VIX", "USD/INR", "Nifty 50", "10Y Gilt"
84
+ value: float
85
+ change_pct: float
86
+ trend: str # "UP" | "DOWN" | "FLAT"
87
+ description: str
88
+
89
+
90
+ class MacroTimeSeriesPoint(BaseModel):
91
+ date: str
92
+ value: float
93
+
94
+
95
+ class MacroTimeSeries(BaseModel):
96
+ name: str
97
+ data: list[MacroTimeSeriesPoint]
98
+
99
+
100
+ class MacroCorrelation(BaseModel):
101
+ indicator1: str
102
+ indicator2: str
103
+ correlation: float
104
+
105
+
106
+ class MacroDashboardResponse(BaseModel):
107
+ indicators: list[MacroIndicator]
108
+ time_series: list[MacroTimeSeries] # 1 year history for each indicator
109
+ correlations: list[MacroCorrelation] # pairwise correlations
110
+ market_regime: str # "RISK_ON" | "RISK_OFF" | "NEUTRAL"
111
+ regime_description: str
112
+ generated_at: str
113
+
114
+
115
+ # ── Risk Factor Decomposition ────────────────────────────────────────────────
116
+
117
+ class FactorExposure(BaseModel):
118
+ factor: str # "Market", "Size", "Value", "Momentum", "Low_Vol", "Quality"
119
+ beta: float # factor loading / exposure
120
+ t_stat: float
121
+ p_value: float
122
+ contribution_pct: float # % of return explained by this factor
123
+
124
+
125
+ class FactorTimeSeries(BaseModel):
126
+ date: str
127
+ market: float
128
+ size: float
129
+ value: float
130
+ momentum: float
131
+
132
+
133
+ class StockFactorResult(BaseModel):
134
+ symbol: str
135
+ company_name: str
136
+ sector: str
137
+ factor_exposures: list[FactorExposure]
138
+ r_squared: float # model fit (0-1)
139
+ alpha: float # unexplained return (annualized %)
140
+ alpha_t_stat: float
141
+ residual_vol: float # idiosyncratic risk (annualized %)
142
+ dominant_factor: str
143
+
144
+
145
+ class RiskFactorRequest(BaseModel):
146
+ symbols: list[str] = Field(..., min_length=1, max_length=20)
147
+
148
+
149
+ class RiskFactorResponse(BaseModel):
150
+ stocks: list[StockFactorResult]
151
+ factor_returns: list[FactorTimeSeries] # factor return history
152
+ factor_descriptions: dict[str, str]
153
+ generated_at: str
app/schemas/analytics.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic schemas for ML analytics endpoints."""
2
+
3
+ from enum import Enum
4
+ from typing import Optional
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ # ── Enums ──────────────────────────────────────────────────────────────────────
9
+
10
+ class SignalDirection(str, Enum):
11
+ BUY = "BUY"
12
+ HOLD = "HOLD"
13
+ SELL = "SELL"
14
+
15
+
16
+ class AnomalyType(str, Enum):
17
+ VOLUME_SPIKE = "VOLUME_SPIKE"
18
+ PRICE_SPIKE = "PRICE_SPIKE"
19
+ ISOLATION_FOREST = "ISOLATION_FOREST"
20
+
21
+
22
+ class AnomalySeverity(str, Enum):
23
+ HIGH = "HIGH"
24
+ MEDIUM = "MEDIUM"
25
+
26
+
27
+ class ClusterLabel(str, Enum):
28
+ DEFENSIVE = "DEFENSIVE"
29
+ VALUE = "VALUE"
30
+ MOMENTUM = "MOMENTUM"
31
+ HIGH_VOLATILITY = "HIGH_VOLATILITY"
32
+
33
+
34
+ # ── Technical Signals ──────────────────────────────────────────────────────────
35
+
36
+ class IndicatorSignal(BaseModel):
37
+ name: str
38
+ direction: SignalDirection
39
+ score: float
40
+ value: float
41
+
42
+
43
+ class TechnicalSignal(BaseModel):
44
+ symbol: str
45
+ company_name: str
46
+ sector: str
47
+ current_price: float
48
+ composite_signal: SignalDirection
49
+ composite_score: float
50
+ confidence_score: float # 0–100
51
+ signals: list[IndicatorSignal]
52
+
53
+
54
+ # ── Risk Metrics ───────────────────────────────────────────────────────────────
55
+
56
+ class RiskMetrics(BaseModel):
57
+ symbol: str
58
+ sharpe_ratio: float
59
+ sortino_ratio: float
60
+ max_drawdown: float # negative percentage, e.g. -15.3
61
+ var_95: float # daily VaR at 95% confidence, negative percentage
62
+ beta: float
63
+ volatility: float # annualised, positive percentage
64
+ alpha: float # annualised Jensen's alpha, percentage
65
+ annualized_return: float # percentage
66
+
67
+
68
+ # ── Anomaly Detection ──────────────────────────────────────────────────────────
69
+
70
+ class AnomalyAlert(BaseModel):
71
+ symbol: str
72
+ anomaly_type: AnomalyType
73
+ severity: AnomalySeverity
74
+ z_score: float
75
+ description: str
76
+
77
+
78
+ # ── Per-stock Analysis ─────────────────────────────────────────────────────────
79
+
80
+ class StockAnalysis(BaseModel):
81
+ symbol: str
82
+ company_name: str
83
+ sector: str
84
+ technical_signals: TechnicalSignal
85
+ risk_metrics: RiskMetrics
86
+ rf_probability: float # probability price up in 5 days
87
+ rf_signal: SignalDirection
88
+ anomalies: list[AnomalyAlert]
89
+
90
+
91
+ # ── Portfolio Optimisation ─────────────────────────────────────────────────────
92
+
93
+ class PortfolioStats(BaseModel):
94
+ expected_return: float
95
+ volatility: float
96
+ sharpe: float
97
+
98
+
99
+ class EfficientFrontierPoint(BaseModel):
100
+ vol: float
101
+ ret: float
102
+ sharpe: float
103
+
104
+
105
+ class PortfolioOptimizationResult(BaseModel):
106
+ symbols: list[str]
107
+ min_variance_weights: dict[str, float]
108
+ max_sharpe_weights: dict[str, float]
109
+ risk_profile_weights: dict[str, float]
110
+ risk_profile: str
111
+ efficient_frontier: list[EfficientFrontierPoint]
112
+ correlation_matrix: list[list[float]]
113
+ mc_results: list[EfficientFrontierPoint]
114
+ min_variance_stats: PortfolioStats
115
+ max_sharpe_stats: PortfolioStats
116
+ risk_profile_stats: PortfolioStats
117
+
118
+
119
+ class PortfolioOptimizeRequest(BaseModel):
120
+ symbols: list[str] = Field(..., min_length=2, max_length=20)
121
+ risk_profile: str = "moderate"
122
+ n_portfolios: int = Field(2000, ge=500, le=5000)
123
+
124
+
125
+ # ── Clustering ─────────────────────────────────────────────────────────────────
126
+
127
+ class StockCluster(BaseModel):
128
+ symbol: str
129
+ cluster_id: int
130
+ cluster_label: ClusterLabel
131
+ volatility: float
132
+ momentum_30d: float
133
+ beta: float
134
+
135
+
136
+ class ClusteringResult(BaseModel):
137
+ clusters: list[StockCluster]
138
+
139
+
140
+ # ── Correlation ────────────────────────────────────────────────────────────────
141
+
142
+ class CorrelationPair(BaseModel):
143
+ symbol1: str
144
+ symbol2: str
145
+ correlation: float
146
+
147
+
148
+ class CorrelationMatrix(BaseModel):
149
+ symbols: list[str]
150
+ matrix: list[list[float]]
151
+ high_correlation_pairs: list[CorrelationPair]
152
+
153
+
154
+ # ── Screener ───────────────────────────────────────────────────────────────────
155
+
156
+ class ScreenerStock(BaseModel):
157
+ symbol: str
158
+ company_name: str
159
+ sector: str
160
+ current_price: float
161
+ daily_change_pct: float
162
+ composite_signal: SignalDirection
163
+ confidence_score: float
164
+ composite_score: float
165
+ rsi: float
166
+ sharpe_ratio: float
167
+ max_drawdown: float
168
+ volatility: float
169
+ beta: float
170
+
171
+
172
+ class ScreenerResponse(BaseModel):
173
+ stocks: list[ScreenerStock]
174
+ total: int
175
+ buy_count: int
176
+ sell_count: int
177
+ hold_count: int
178
+
179
+
180
+ # ── Backtest ───────────────────────────────────────────────────────────────────
181
+
182
+ class EquityPoint(BaseModel):
183
+ date: str
184
+ strategy: float
185
+ benchmark: float
186
+
187
+
188
+ class BacktestResult(BaseModel):
189
+ symbol: str
190
+ equity_curve: list[EquityPoint]
191
+ total_return: float
192
+ benchmark_return: float
193
+ alpha: float
194
+ sharpe_ratio: float
195
+ num_trades: int
196
+ win_rate: float
197
+
198
+
199
+ # ── Market Overview ────────────────────────────────────────────────────────────
200
+
201
+ class SectorHeatmapItem(BaseModel):
202
+ sector: str
203
+ avg_change_pct: float
204
+ stock_count: int
205
+
206
+
207
+ class TrendingStock(BaseModel):
208
+ symbol: str
209
+ company_name: str
210
+ change_pct: float
211
+
212
+
213
+ class MarketOverview(BaseModel):
214
+ sector_heatmap: list[SectorHeatmapItem]
215
+ top_gainers: list[TrendingStock]
216
+ top_losers: list[TrendingStock]
217
+ anomaly_alerts: list[AnomalyAlert]
218
+ market_breadth: dict[str, int]
219
+
220
+
221
+ # ── Full Analytics Report ──────────────────────────────────────────────────────
222
+
223
+ class AnalyticsReport(BaseModel):
224
+ generated_at: str
225
+ stocks_analyzed: int
226
+ stock_analyses: list[StockAnalysis]
227
+ market_overview: MarketOverview
228
+ clustering: ClusteringResult
229
+ correlation: CorrelationMatrix
230
+ buy_count: int
231
+ sell_count: int
232
+ hold_count: int
233
+ anomaly_count: int
234
+
235
+
236
+ # ── Smart Portfolio + Forecast ────────────────────────────────────────────────
237
+
238
+ class ForecastPoint(BaseModel):
239
+ date: str
240
+ price: float
241
+ lower: float
242
+ upper: float
243
+
244
+
245
+ class StockForecast(BaseModel):
246
+ symbol: str
247
+ company_name: str
248
+ sector: str
249
+ current_price: float
250
+ forecast_30d: list[ForecastPoint]
251
+ predicted_return_pct: float # expected 30-day return
252
+ confidence: float # 0-100
253
+ trend: str # "BULLISH" | "BEARISH" | "NEUTRAL"
254
+ support_level: float
255
+ resistance_level: float
256
+ volatility_30d: float # annualised vol
257
+
258
+
259
+ class SmartPortfolioRequest(BaseModel):
260
+ risk_profile: str = "moderate"
261
+ top_n: int = Field(15, ge=5, le=30)
262
+ n_portfolios: int = Field(2000, ge=500, le=5000)
263
+
264
+
265
+ class SmartPortfolioResponse(BaseModel):
266
+ # Auto-selected stocks
267
+ selected_symbols: list[str]
268
+ selection_reasoning: list[str] # why each stock was picked
269
+
270
+ # Portfolio optimisation (same as before)
271
+ optimization: PortfolioOptimizationResult
272
+
273
+ # Forecasts for each stock in the portfolio
274
+ forecasts: list[StockForecast]
275
+
276
+ # Aggregate stats
277
+ portfolio_predicted_return: float # weighted 30-day forecast
278
+ portfolio_risk_score: float # 0-100
279
+
280
+
281
+ # ── Time Series Analysis ─────────────────────────────────────────────────────
282
+
283
+ class ModelForecast(BaseModel):
284
+ """Forecast output from a single model."""
285
+ model_name: str # "ARIMA", "ETS", "Linear Trend"
286
+ forecast: list[ForecastPoint]
287
+ rmse: float # root-mean-square error on validation set
288
+ aic: Optional[float] = None # Akaike info criterion (ARIMA/ETS)
289
+ order: Optional[str] = None # e.g. "(1,1,1)" for ARIMA
290
+
291
+
292
+ class SeasonalDecomposition(BaseModel):
293
+ date: str
294
+ observed: float
295
+ trend: Optional[float] = None
296
+ seasonal: Optional[float] = None
297
+ residual: Optional[float] = None
298
+
299
+
300
+ class StationarityTest(BaseModel):
301
+ test_name: str # "ADF" or "KPSS"
302
+ statistic: float
303
+ p_value: float
304
+ is_stationary: bool
305
+ interpretation: str
306
+
307
+
308
+ class AutocorrelationPoint(BaseModel):
309
+ lag: int
310
+ acf: float
311
+ pacf: float
312
+
313
+
314
+ class TimeSeriesAnalysisResult(BaseModel):
315
+ symbol: str
316
+ company_name: str
317
+ sector: str
318
+ current_price: float
319
+ data_points: int # number of historical observations used
320
+
321
+ # Decomposition
322
+ decomposition: list[SeasonalDecomposition]
323
+
324
+ # Stationarity tests
325
+ stationarity_tests: list[StationarityTest]
326
+
327
+ # ACF / PACF
328
+ autocorrelation: list[AutocorrelationPoint]
329
+
330
+ # Model forecasts (multiple models compared)
331
+ model_forecasts: list[ModelForecast]
332
+ best_model: str # name of best-performing model
333
+
334
+ # Summary
335
+ predicted_return_pct: float
336
+ trend: str # "BULLISH" | "BEARISH" | "NEUTRAL"
337
+ volatility_30d: float
338
+ support_level: float
339
+ resistance_level: float
app/schemas/financial.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Literal, Optional
3
+ from enum import Enum
4
+
5
+
6
+ class RiskProfile(str, Enum):
7
+ conservative = "conservative"
8
+ moderate = "moderate"
9
+ aggressive = "aggressive"
10
+
11
+
12
+ class UserFinancialProfile(BaseModel):
13
+ monthly_income: float = Field(..., gt=0, description="Monthly gross income in INR")
14
+ monthly_expenses: float = Field(..., ge=0, description="Monthly expenses in INR")
15
+ current_savings: float = Field(0, ge=0, description="Existing savings/investments in INR")
16
+ age: int = Field(..., ge=18, le=80)
17
+ risk_profile: RiskProfile = RiskProfile.moderate
18
+ annual_income_growth_pct: float = Field(5.0, ge=0, le=50, description="Expected annual income growth %")
19
+
20
+
21
+ class ForwardPlannerRequest(BaseModel):
22
+ profile: UserFinancialProfile
23
+ monthly_investment: float = Field(..., gt=0, description="Monthly SIP amount in INR")
24
+ annual_stepup_pct: float = Field(10.0, ge=0, le=50, description="Yearly increase in SIP amount %")
25
+ horizon_years: int = Field(..., ge=1, le=40)
26
+ expected_annual_return_pct: Optional[float] = Field(None, description="Override return rate; auto-picked from risk profile if None")
27
+ simulations: int = Field(1000, ge=100, le=10000)
28
+
29
+
30
+ class GoalPlannerRequest(BaseModel):
31
+ profile: UserFinancialProfile
32
+ target_amount: float = Field(..., gt=0, description="Target corpus in INR")
33
+ horizon_years: int = Field(..., ge=1, le=40)
34
+ annual_stepup_pct: float = Field(10.0, ge=0, le=50)
35
+ expected_annual_return_pct: Optional[float] = None
36
+
37
+
38
+ class MonteCarloResult(BaseModel):
39
+ percentile_10: float
40
+ percentile_25: float
41
+ percentile_50: float
42
+ percentile_75: float
43
+ percentile_90: float
44
+ mean: float
45
+ std_dev: float
46
+ probability_of_loss: float
47
+ yearly_expected: list[float]
48
+ yearly_p10: list[float]
49
+ yearly_p90: list[float]
50
+
51
+
52
+ class ForwardPlannerResponse(BaseModel):
53
+ monthly_investment: float
54
+ annual_stepup_pct: float
55
+ horizon_years: int
56
+ expected_annual_return_pct: float
57
+ investable_surplus: float
58
+ recommended_monthly_investment: float
59
+ total_invested: float
60
+ monte_carlo: MonteCarloResult
61
+ asset_allocation: dict[str, float]
62
+
63
+
64
+ class GoalPlannerResponse(BaseModel):
65
+ target_amount: float
66
+ horizon_years: int
67
+ required_monthly_investment: float
68
+ total_invested: float
69
+ expected_annual_return_pct: float
70
+ is_achievable_within_surplus: bool
71
+ investable_surplus: float
72
+ sensitivity: list[dict]
73
+ asset_allocation: dict[str, float]
74
+
75
+
76
+ class AdvisorChatRequest(BaseModel):
77
+ message: str = Field(..., min_length=1, max_length=2000)
78
+ profile: Optional[UserFinancialProfile] = None
79
+ conversation_history: list[dict] = []
80
+
81
+
82
+ class AdvisorChatResponse(BaseModel):
83
+ reply: str
84
+ suggestions: list[str] = []
app/schemas/portfolio.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic schemas for Watchlist & Portfolio Tracker."""
2
+
3
+ from typing import Optional
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ # ── Watchlist ────────────────────────────────────────────────────────────────
8
+
9
+ class WatchlistItem(BaseModel):
10
+ id: int
11
+ symbol: str
12
+ company_name: str = ""
13
+ sector: str = ""
14
+ current_price: float = 0
15
+ daily_change_pct: float = 0
16
+ added_at: str
17
+ notes: Optional[str] = None
18
+
19
+
20
+ class WatchlistAddRequest(BaseModel):
21
+ symbol: str = Field(..., min_length=1)
22
+ notes: Optional[str] = None
23
+
24
+
25
+ class WatchlistResponse(BaseModel):
26
+ items: list[WatchlistItem]
27
+ total: int
28
+
29
+
30
+ # ── Portfolio Holdings ───────────────────────────────────────────────────────
31
+
32
+ class HoldingInput(BaseModel):
33
+ symbol: str = Field(..., min_length=1)
34
+ quantity: float = Field(..., gt=0)
35
+ buy_price: float = Field(..., gt=0)
36
+ buy_date: str = "" # YYYY-MM-DD, defaults to today
37
+ notes: Optional[str] = None
38
+
39
+
40
+ class PortfolioHolding(BaseModel):
41
+ id: int
42
+ symbol: str
43
+ company_name: str = ""
44
+ sector: str = ""
45
+ quantity: float
46
+ buy_price: float
47
+ buy_date: str
48
+ current_price: float = 0
49
+ daily_change_pct: float = 0
50
+ pnl: float = 0 # absolute P&L
51
+ pnl_pct: float = 0 # percentage P&L
52
+ market_value: float = 0 # current_price * quantity
53
+ invested_value: float = 0 # buy_price * quantity
54
+ notes: Optional[str] = None
55
+
56
+
57
+ class PortfolioSummary(BaseModel):
58
+ total_invested: float
59
+ total_market_value: float
60
+ total_pnl: float
61
+ total_pnl_pct: float
62
+ holdings_count: int
63
+ best_performer: Optional[str] = None
64
+ worst_performer: Optional[str] = None
65
+
66
+
67
+ class PortfolioResponse(BaseModel):
68
+ holdings: list[PortfolioHolding]
69
+ summary: PortfolioSummary
70
+
71
+
72
+ # ── News Sentiment ───────────────────────────────────────────────────────────
73
+
74
+ class NewsArticle(BaseModel):
75
+ title: str
76
+ source: str
77
+ url: str
78
+ published_at: str
79
+ sentiment: str # "POSITIVE" | "NEGATIVE" | "NEUTRAL"
80
+ sentiment_score: float # -1.0 to 1.0
81
+ symbols: list[str] = [] # related stock symbols
82
+
83
+
84
+ class SentimentSummary(BaseModel):
85
+ symbol: str
86
+ company_name: str
87
+ article_count: int
88
+ avg_sentiment: float # -1.0 to 1.0
89
+ positive_count: int
90
+ negative_count: int
91
+ neutral_count: int
92
+ sentiment_label: str # "BULLISH" | "BEARISH" | "NEUTRAL"
93
+
94
+
95
+ # ── AI Portfolio Builder ─────────────────────────────────────────────────────
96
+
97
+ class AIBuildRequest(BaseModel):
98
+ investment_amount: float = Field(..., gt=0, description="Total investment in INR")
99
+ risk_profile: str = Field("moderate", pattern="^(conservative|moderate|aggressive)$")
100
+
101
+
102
+ class AIPick(BaseModel):
103
+ symbol: str
104
+ company_name: str = ""
105
+ sector: str = ""
106
+ current_price: float = 0
107
+ daily_change_pct: float = 0
108
+ quantity: int = 0
109
+ allocation: float = 0
110
+ weight_pct: float = 0
111
+ reason: str = ""
112
+
113
+
114
+ class AIBuildResponse(BaseModel):
115
+ picks: list[AIPick]
116
+ strategy_summary: str = ""
117
+ risk_notes: str = ""
118
+ total_allocated: float = 0
119
+ cash_remaining: float = 0
120
+ investment_amount: float = 0
121
+ risk_profile: str = ""
122
+
123
+
124
+ class NewsSentimentResponse(BaseModel):
125
+ articles: list[NewsArticle]
126
+ summaries: list[SentimentSummary]
127
+ overall_sentiment: str # "BULLISH" | "BEARISH" | "NEUTRAL"
128
+ overall_score: float
129
+ generated_at: str
app/services/__init__.py ADDED
File without changes
app/services/ai_advisor.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI advisor service powered by Groq (Llama 3.3 70B).
3
+ Uses the OpenAI-compatible /chat/completions endpoint.
4
+ """
5
+
6
+ import httpx
7
+ from fastapi import HTTPException
8
+ from ..core.config import get_settings
9
+ from ..schemas.financial import UserFinancialProfile, AdvisorChatRequest, AdvisorChatResponse
10
+
11
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
12
+ GROQ_MODEL = "llama-3.3-70b-versatile"
13
+
14
+ SYSTEM_PROMPT = """You are an expert Indian investment advisor AI assistant built into a personal finance planning tool.
15
+ Your role is to help users understand their investment strategy, explain financial concepts, and provide actionable advice.
16
+
17
+ Key context:
18
+ - You are focused on the Indian financial market (NSE/BSE, Nifty, Sensex, Indian mutual funds, SIPs, PPF, NPS, ELSS)
19
+ - All monetary values are in Indian Rupees (INR / ₹)
20
+ - Regulatory context: SEBI regulations, Indian tax laws (LTCG, STCG, Section 80C)
21
+ - Be clear that your advice is educational and not a registered financial advisory service
22
+
23
+ Tone: Professional yet approachable. Use simple language. Avoid jargon unless explaining it.
24
+
25
+ Formatting rules (STRICT — your output is rendered as Markdown):
26
+ - Use ## for section headings. Never put headings inside list items.
27
+ - Use bullet lists (- item) for points. Use numbered lists (1. item) only for sequential steps.
28
+ - Each list item must be ONE short line. Never put multiple sentences or sub-points on a single list item.
29
+ - Put a blank line before and after every heading, list, and block.
30
+ - Use **bold** sparingly — only for key terms or amounts, never for entire sentences.
31
+ - Keep paragraphs to 2-3 sentences max.
32
+ - Use > blockquote for important callouts or final takeaways.
33
+ - Use markdown tables when comparing multiple items side by side. Keep columns concise.
34
+ - Do NOT mix prose paragraphs and list items without a blank line between them.
35
+
36
+ When the user provides their financial profile, use it to personalise your response."""
37
+
38
+
39
+ def _profile_context(profile: UserFinancialProfile | None) -> str:
40
+ if not profile:
41
+ return ""
42
+ surplus = profile.monthly_income - profile.monthly_expenses
43
+ return f"""
44
+ User Financial Profile:
45
+ - Monthly Income: ₹{profile.monthly_income:,.0f}
46
+ - Monthly Expenses: ₹{profile.monthly_expenses:,.0f}
47
+ - Investable Surplus: ₹{surplus:,.0f}/month
48
+ - Current Savings: ₹{profile.current_savings:,.0f}
49
+ - Age: {profile.age} years
50
+ - Risk Tolerance: {profile.risk_profile.value.capitalize()}
51
+ """
52
+
53
+
54
+ def _market_context() -> str:
55
+ """Inject live market intelligence from the analytics cache into the advisor."""
56
+ try:
57
+ from .analytics import get_market_overview, _report_cache
58
+ cached, _ = _report_cache
59
+ if cached is None:
60
+ return ""
61
+
62
+ overview = cached.market_overview
63
+ breadth = overview.market_breadth
64
+ buy_count = breadth.get("buy", 0)
65
+ sell_count = breadth.get("sell", 0)
66
+ hold_count = breadth.get("hold", 0)
67
+
68
+ lines = [
69
+ "\nLive Market Intelligence (from ML analytics engine):",
70
+ f"- Market Breadth: {buy_count} BUY signals, {hold_count} HOLD, {sell_count} SELL",
71
+ ]
72
+
73
+ # Top BUY signals
74
+ top_buys = [
75
+ a for a in cached.stock_analyses
76
+ if a.technical_signals.composite_signal.value == "BUY"
77
+ ]
78
+ top_buys.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
79
+ if top_buys:
80
+ names = [f"{a.symbol.replace('.NS','')} ({a.technical_signals.confidence_score:.0f}%)" for a in top_buys[:5]]
81
+ lines.append(f"- Top BUY signals: {', '.join(names)}")
82
+
83
+ # Top SELL signals
84
+ top_sells = [
85
+ a for a in cached.stock_analyses
86
+ if a.technical_signals.composite_signal.value == "SELL"
87
+ ]
88
+ top_sells.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
89
+ if top_sells:
90
+ names = [f"{a.symbol.replace('.NS','')} ({a.technical_signals.confidence_score:.0f}%)" for a in top_sells[:5]]
91
+ lines.append(f"- Top SELL signals: {', '.join(names)}")
92
+
93
+ # Anomalies
94
+ anomaly_count = cached.anomaly_count
95
+ if anomaly_count > 0:
96
+ lines.append(f"- Anomalies detected: {anomaly_count}")
97
+ for a in overview.anomaly_alerts[:3]:
98
+ lines.append(f" - {a.symbol.replace('.NS','')}: {a.description} [{a.severity}]")
99
+
100
+ # Sector highlights
101
+ if overview.sector_heatmap:
102
+ best = max(overview.sector_heatmap, key=lambda s: s.avg_change_pct)
103
+ worst = min(overview.sector_heatmap, key=lambda s: s.avg_change_pct)
104
+ lines.append(f"- Strongest sector: {best.sector} ({best.avg_change_pct:+.2f}%)")
105
+ lines.append(f"- Weakest sector: {worst.sector} ({worst.avg_change_pct:+.2f}%)")
106
+
107
+ lines.append("\nUse this data to give informed, current answers about the Indian market.")
108
+ return "\n".join(lines)
109
+ except Exception:
110
+ return ""
111
+
112
+
113
+ def _build_messages(request: AdvisorChatRequest) -> list[dict]:
114
+ system = SYSTEM_PROMPT
115
+ if request.profile:
116
+ system += "\n" + _profile_context(request.profile)
117
+ system += _market_context()
118
+
119
+ messages = [{"role": "system", "content": system}]
120
+ for msg in request.conversation_history[-10:]:
121
+ messages.append({"role": msg["role"], "content": msg["content"]})
122
+ messages.append({"role": "user", "content": request.message})
123
+ return messages
124
+
125
+
126
+ async def stream_advisor_response(request: AdvisorChatRequest):
127
+ """SSE generator — streams tokens from Groq to the client."""
128
+ import json as _json
129
+
130
+ settings = get_settings()
131
+ if not settings.groq_api_key:
132
+ yield f"data: {_json.dumps({'error': 'Groq API key is not configured.'})}\n\n"
133
+ return
134
+
135
+ messages = _build_messages(request)
136
+
137
+ try:
138
+ async with httpx.AsyncClient(timeout=30) as client:
139
+ async with client.stream(
140
+ "POST",
141
+ GROQ_URL,
142
+ headers={
143
+ "Authorization": f"Bearer {settings.groq_api_key}",
144
+ "Content-Type": "application/json",
145
+ },
146
+ json={
147
+ "model": GROQ_MODEL,
148
+ "messages": messages,
149
+ "max_tokens": 4096,
150
+ "temperature": 0.7,
151
+ "stream": True,
152
+ },
153
+ ) as resp:
154
+ if resp.status_code != 200:
155
+ yield f"data: {_json.dumps({'error': f'Groq error: {resp.status_code}'})}\n\n"
156
+ return
157
+
158
+ async for line in resp.aiter_lines():
159
+ if not line.startswith("data: "):
160
+ continue
161
+ payload = line[6:]
162
+ if payload.strip() == "[DONE]":
163
+ yield "data: [DONE]\n\n"
164
+ return
165
+ try:
166
+ chunk = _json.loads(payload)
167
+ delta = chunk["choices"][0].get("delta", {})
168
+ token = delta.get("content")
169
+ if token:
170
+ yield f"data: {_json.dumps({'token': token})}\n\n"
171
+ except (KeyError, _json.JSONDecodeError):
172
+ continue
173
+ except httpx.RequestError:
174
+ yield f"data: {_json.dumps({'error': 'Could not reach Groq. Please try again.'})}\n\n"
175
+
176
+
177
+ async def get_advisor_response(request: AdvisorChatRequest) -> AdvisorChatResponse:
178
+ """Non-streaming fallback."""
179
+ settings = get_settings()
180
+
181
+ if not settings.groq_api_key:
182
+ raise HTTPException(status_code=503, detail="Groq API key is not configured.")
183
+
184
+ messages = _build_messages(request)
185
+
186
+ try:
187
+ async with httpx.AsyncClient(timeout=30) as client:
188
+ resp = await client.post(
189
+ GROQ_URL,
190
+ headers={
191
+ "Authorization": f"Bearer {settings.groq_api_key}",
192
+ "Content-Type": "application/json",
193
+ },
194
+ json={
195
+ "model": GROQ_MODEL,
196
+ "messages": messages,
197
+ "max_tokens": 4096,
198
+ "temperature": 0.7,
199
+ },
200
+ )
201
+ resp.raise_for_status()
202
+ data = resp.json()
203
+ except httpx.HTTPStatusError as exc:
204
+ if exc.response.status_code == 429:
205
+ raise HTTPException(status_code=429, detail="Rate limited. Please wait a moment and try again.")
206
+ raise HTTPException(status_code=502, detail=f"Groq error: {exc.response.status_code}")
207
+ except httpx.RequestError:
208
+ raise HTTPException(status_code=503, detail="Could not reach Groq. Please try again.")
209
+
210
+ reply = (data["choices"][0]["message"].get("content") or "").strip()
211
+ while reply.endswith("---"):
212
+ reply = reply[:-3].rstrip()
213
+ if not reply:
214
+ raise HTTPException(status_code=502, detail="AI returned an empty response. Please try again.")
215
+
216
+ suggestions = []
217
+ for line in reply.split("\n"):
218
+ line = line.strip()
219
+ if line.startswith("- ") and len(line) < 100:
220
+ suggestions.append(line[2:])
221
+ if len(suggestions) >= 3:
222
+ break
223
+
224
+ return AdvisorChatResponse(reply=reply, suggestions=suggestions)
app/services/ai_portfolio.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI-powered portfolio builder.
3
+
4
+ Uses Groq LLM + live market intelligence to suggest stocks and quantities
5
+ based on the user's investment amount and risk tolerance.
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ import httpx
11
+ from ..core.config import get_settings
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
16
+ GROQ_MODEL = "llama-3.3-70b-versatile"
17
+
18
+
19
+ def _market_snapshot() -> str:
20
+ """Build a concise market snapshot for the LLM from the analytics cache."""
21
+ try:
22
+ from .analytics import _report_cache, _get_cached_df
23
+
24
+ cached, _ = _report_cache
25
+ if cached is None:
26
+ return "No market data available."
27
+
28
+ lines = []
29
+
30
+ # All stocks with BUY signal, sorted by confidence
31
+ buy_stocks = [
32
+ a for a in cached.stock_analyses
33
+ if a.technical_signals.composite_signal.value == "BUY"
34
+ ]
35
+ buy_stocks.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
36
+
37
+ hold_stocks = [
38
+ a for a in cached.stock_analyses
39
+ if a.technical_signals.composite_signal.value == "HOLD"
40
+ ]
41
+ hold_stocks.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
42
+
43
+ lines.append("=== STOCKS WITH BUY SIGNAL ===")
44
+ for a in buy_stocks:
45
+ sym = a.symbol.replace(".NS", "")
46
+ rm = a.risk_metrics
47
+ price = a.technical_signals.current_price
48
+ lines.append(
49
+ f"- {sym} ({a.company_name}) | Sector: {a.sector} | "
50
+ f"Price: {price:.2f} | Confidence: {a.technical_signals.confidence_score:.0f}% | "
51
+ f"Sharpe: {rm.sharpe_ratio:.2f} | MaxDD: {rm.max_drawdown:.1%} | "
52
+ f"Beta: {rm.beta:.2f} | Vol: {rm.volatility:.1%}"
53
+ )
54
+
55
+ lines.append("\n=== STOCKS WITH HOLD SIGNAL ===")
56
+ for a in hold_stocks[:10]:
57
+ sym = a.symbol.replace(".NS", "")
58
+ rm = a.risk_metrics
59
+ price = a.technical_signals.current_price
60
+ lines.append(
61
+ f"- {sym} ({a.company_name}) | Sector: {a.sector} | "
62
+ f"Price: {price:.2f} | Confidence: {a.technical_signals.confidence_score:.0f}% | "
63
+ f"Sharpe: {rm.sharpe_ratio:.2f} | MaxDD: {rm.max_drawdown:.1%} | "
64
+ f"Beta: {rm.beta:.2f} | Vol: {rm.volatility:.1%}"
65
+ )
66
+
67
+ # Sector performance
68
+ overview = cached.market_overview
69
+ if overview.sector_heatmap:
70
+ lines.append("\n=== SECTOR PERFORMANCE ===")
71
+ for s in sorted(overview.sector_heatmap, key=lambda x: x.avg_change_pct, reverse=True):
72
+ lines.append(f"- {s.sector}: {s.avg_change_pct:+.2f}% ({s.stock_count} stocks)")
73
+
74
+ # Anomalies as warnings
75
+ if overview.anomaly_alerts:
76
+ lines.append("\n=== ANOMALY WARNINGS ===")
77
+ for a in overview.anomaly_alerts[:5]:
78
+ lines.append(f"- {a.symbol.replace('.NS','')}: {a.description} [{a.severity}]")
79
+
80
+ return "\n".join(lines)
81
+ except Exception as e:
82
+ logger.warning("Failed to build market snapshot: %s", e)
83
+ return "Market data temporarily unavailable."
84
+
85
+
86
+ SYSTEM_PROMPT = """You are an expert Indian equity portfolio constructor built into PaisaPro.ai.
87
+ Your job: given the user's investment amount and risk profile, select the best stocks and allocate quantities to build an optimal portfolio.
88
+
89
+ Rules:
90
+ - ONLY pick from the stocks listed in the market data provided. Do NOT invent symbols.
91
+ - For conservative: prefer high-Sharpe, low-volatility, low-beta stocks. Pick 8-12 stocks. Diversify broadly across sectors.
92
+ - For moderate: balanced mix of growth and value. Pick 7-10 stocks. Diversify across at least 4 sectors.
93
+ - For aggressive: high-confidence BUY signals with strong momentum. Pick 5-8 stocks. At least 3 sectors.
94
+ - IMPORTANT: You MUST pick at least 5 stocks. Spread the allocation, do not over-concentrate.
95
+ - Allocate rupee amounts per stock, then calculate quantity = floor(allocation / current_price).
96
+ - No single stock should exceed 20% of total investment.
97
+ - Use current market prices from the data provided.
98
+ - The sum of all allocations must be between 90% and 98% of the investment amount.
99
+ - Prioritize stocks with BUY signal first, then HOLD stocks with high Sharpe ratios.
100
+
101
+ You MUST respond with ONLY valid JSON in this exact format — no markdown, no explanation outside JSON:
102
+ {
103
+ "picks": [
104
+ {
105
+ "symbol": "RELIANCE",
106
+ "company_name": "Reliance Industries",
107
+ "sector": "Energy",
108
+ "current_price": 1234.56,
109
+ "quantity": 10,
110
+ "allocation": 12345.60,
111
+ "weight_pct": 12.3,
112
+ "reason": "Strong BUY signal with 78% confidence, low volatility, sector leader"
113
+ }
114
+ ],
115
+ "strategy_summary": "Brief 2-3 sentence summary of the portfolio strategy",
116
+ "risk_notes": "Key risks to be aware of",
117
+ "expected_sectors": {"Energy": 25.0, "IT": 20.0},
118
+ "total_allocated": 95000,
119
+ "cash_remaining": 5000
120
+ }"""
121
+
122
+
123
+ async def ai_build_portfolio(
124
+ investment_amount: float,
125
+ risk_profile: str = "moderate",
126
+ ) -> dict:
127
+ """Call the LLM with market data to generate stock picks."""
128
+ settings = get_settings()
129
+ if not settings.groq_api_key:
130
+ raise RuntimeError("Groq API key is not configured.")
131
+
132
+ snapshot = _market_snapshot()
133
+
134
+ user_prompt = f"""Build me a portfolio with these parameters:
135
+ - Investment Amount: Rs {investment_amount:,.0f}
136
+ - Risk Profile: {risk_profile.upper()}
137
+
138
+ Here is the current market data for Indian stocks:
139
+
140
+ {snapshot}
141
+
142
+ Respond with ONLY the JSON object. No markdown fences, no extra text."""
143
+
144
+ messages = [
145
+ {"role": "system", "content": SYSTEM_PROMPT},
146
+ {"role": "user", "content": user_prompt},
147
+ ]
148
+
149
+ try:
150
+ async with httpx.AsyncClient(timeout=45) as client:
151
+ resp = await client.post(
152
+ GROQ_URL,
153
+ headers={
154
+ "Authorization": f"Bearer {settings.groq_api_key}",
155
+ "Content-Type": "application/json",
156
+ },
157
+ json={
158
+ "model": GROQ_MODEL,
159
+ "messages": messages,
160
+ "max_tokens": 4096,
161
+ "temperature": 0.3, # lower temp for structured output
162
+ },
163
+ )
164
+ resp.raise_for_status()
165
+ data = resp.json()
166
+ except httpx.HTTPStatusError as exc:
167
+ if exc.response.status_code == 429:
168
+ raise RuntimeError("Rate limited by Groq. Please wait a moment.")
169
+ raise RuntimeError(f"Groq API error: {exc.response.status_code}")
170
+ except httpx.RequestError:
171
+ raise RuntimeError("Could not reach Groq API. Please try again.")
172
+
173
+ raw = (data["choices"][0]["message"].get("content") or "").strip()
174
+
175
+ # Strip markdown fences if present
176
+ if raw.startswith("```"):
177
+ raw = raw.split("\n", 1)[1] if "\n" in raw else raw[3:]
178
+ if raw.endswith("```"):
179
+ raw = raw[:-3].rstrip()
180
+ if raw.startswith("json"):
181
+ raw = raw[4:].lstrip()
182
+
183
+ try:
184
+ result = json.loads(raw)
185
+ except json.JSONDecodeError:
186
+ # Try to extract JSON from the response
187
+ start = raw.find("{")
188
+ end = raw.rfind("}") + 1
189
+ if start >= 0 and end > start:
190
+ try:
191
+ result = json.loads(raw[start:end])
192
+ except json.JSONDecodeError:
193
+ raise RuntimeError("AI returned invalid JSON. Please try again.")
194
+ else:
195
+ raise RuntimeError("AI returned invalid response format. Please try again.")
196
+
197
+ # Validate and enrich picks with live prices
198
+ from .portfolio import _get_latest_price, _get_stock_meta
199
+
200
+ picks = result.get("picks", [])
201
+ validated_picks = []
202
+ for pick in picks:
203
+ sym = pick.get("symbol", "").upper().replace(".NS", "")
204
+ if not sym:
205
+ continue
206
+ price, change = _get_latest_price(sym)
207
+ name, sector = _get_stock_meta(sym)
208
+
209
+ if price <= 0:
210
+ price = pick.get("current_price", 0)
211
+
212
+ qty = int(pick.get("quantity", 0))
213
+ if qty <= 0 and price > 0:
214
+ alloc = pick.get("allocation", 0)
215
+ qty = int(alloc / price) if alloc > 0 else 0
216
+
217
+ if qty <= 0 or price <= 0:
218
+ continue
219
+
220
+ validated_picks.append({
221
+ "symbol": sym,
222
+ "company_name": name or pick.get("company_name", ""),
223
+ "sector": sector or pick.get("sector", ""),
224
+ "current_price": round(price, 2),
225
+ "daily_change_pct": change,
226
+ "quantity": qty,
227
+ "allocation": round(price * qty, 2),
228
+ "weight_pct": 0, # recalculated below
229
+ "reason": pick.get("reason", ""),
230
+ })
231
+
232
+ # Post-process: scale down if total exceeds budget
233
+ total_allocated = sum(p["allocation"] for p in validated_picks)
234
+ if total_allocated > investment_amount and validated_picks:
235
+ scale = investment_amount * 0.97 / total_allocated # 3% cash buffer
236
+ for p in validated_picks:
237
+ new_qty = max(1, int(p["quantity"] * scale))
238
+ p["quantity"] = new_qty
239
+ p["allocation"] = round(p["current_price"] * new_qty, 2)
240
+ total_allocated = sum(p["allocation"] for p in validated_picks)
241
+
242
+ # Cap any single stock at 25% of total
243
+ for p in validated_picks:
244
+ max_alloc = investment_amount * 0.25
245
+ if p["allocation"] > max_alloc and p["current_price"] > 0:
246
+ p["quantity"] = max(1, int(max_alloc / p["current_price"]))
247
+ p["allocation"] = round(p["current_price"] * p["quantity"], 2)
248
+ total_allocated = sum(p["allocation"] for p in validated_picks)
249
+
250
+ # Recalculate weights
251
+ for p in validated_picks:
252
+ p["weight_pct"] = round(p["allocation"] / investment_amount * 100, 1) if investment_amount > 0 else 0
253
+
254
+ return {
255
+ "picks": validated_picks,
256
+ "strategy_summary": result.get("strategy_summary", ""),
257
+ "risk_notes": result.get("risk_notes", ""),
258
+ "total_allocated": round(total_allocated, 2),
259
+ "cash_remaining": round(investment_amount - total_allocated, 2),
260
+ "investment_amount": investment_amount,
261
+ "risk_profile": risk_profile,
262
+ }
app/services/analytics.py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core ML analytics engine for Indian stock market analysis.
3
+
4
+ Data source:
5
+ - Yahoo Finance (yfinance) — NSE-listed stocks, 1-day interval, 1-year history.
6
+ No API key required, no rate limits.
7
+ Results persisted to Supabase (stock_prices table) so restarts are instant.
8
+ 24-hour in-memory cache on top of Supabase for hot-path performance.
9
+
10
+ ML: scikit-learn RandomForest, IsolationForest, KMeans; scipy optimisation.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import time
17
+ import logging
18
+ from typing import Optional
19
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
+
21
+ import httpx
22
+ import yfinance as yf
23
+ import numpy as np
24
+ import pandas as pd
25
+ from sklearn.ensemble import RandomForestClassifier, IsolationForest
26
+ from sklearn.preprocessing import StandardScaler
27
+ from sklearn.cluster import KMeans
28
+ from scipy.optimize import minimize
29
+
30
+ from ..schemas.analytics import (
31
+ SignalDirection,
32
+ IndicatorSignal,
33
+ TechnicalSignal,
34
+ RiskMetrics,
35
+ AnomalyAlert,
36
+ AnomalyType,
37
+ AnomalySeverity,
38
+ StockAnalysis,
39
+ PortfolioOptimizationResult,
40
+ PortfolioStats,
41
+ EfficientFrontierPoint,
42
+ StockCluster,
43
+ ClusteringResult,
44
+ ClusterLabel,
45
+ CorrelationMatrix,
46
+ CorrelationPair,
47
+ ScreenerStock,
48
+ ScreenerResponse,
49
+ EquityPoint,
50
+ BacktestResult,
51
+ SectorHeatmapItem,
52
+ TrendingStock,
53
+ MarketOverview,
54
+ AnalyticsReport,
55
+ ForecastPoint,
56
+ StockForecast,
57
+ SmartPortfolioResponse,
58
+ )
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+ # ── Constants ──────────────────────────────────────────────────────────────────
63
+
64
+ RISK_FREE_RATE = 0.065 # Indian 10-yr gilt
65
+ NIFTY_INDEX = "^NSEI"
66
+
67
+ # ── Dynamic stock universe (loaded from Supabase stocks table) ────────────────
68
+
69
+ _stock_universe: list[str] = [] # ["RELIANCE.NS", "TCS.NS", ...]
70
+ _stock_names: dict[str, str] = {} # {"RELIANCE.NS": "Reliance Industries"}
71
+ _stock_sectors: dict[str, str] = {} # {"RELIANCE.NS": "Energy"}
72
+ _universe_loaded = False
73
+
74
+
75
+ def _load_stock_universe() -> None:
76
+ """Fetch all stocks from Supabase stocks table and populate the universe."""
77
+ global _stock_universe, _stock_names, _stock_sectors, _universe_loaded
78
+
79
+ from ..core.config import get_settings
80
+ settings = get_settings()
81
+
82
+ try:
83
+ url = f"{settings.supabase_url}/rest/v1/stocks"
84
+ headers = {
85
+ "apikey": settings.supabase_service_role_key,
86
+ "Authorization": f"Bearer {settings.supabase_service_role_key}",
87
+ "Content-Type": "application/json",
88
+ }
89
+ resp = httpx.get(
90
+ url,
91
+ headers=headers,
92
+ params={
93
+ "select": "symbol,company_name,sector",
94
+ "order": "symbol.asc",
95
+ "limit": "1000",
96
+ },
97
+ timeout=15,
98
+ )
99
+ resp.raise_for_status()
100
+ data = resp.json()
101
+ except Exception as exc:
102
+ logger.warning(f"Failed to load stock universe from Supabase: {exc}")
103
+ _universe_loaded = True
104
+ return
105
+
106
+ symbols = []
107
+ names = {}
108
+ sectors = {}
109
+ for row in data:
110
+ bare = row["symbol"]
111
+ ns = f"{bare}.NS"
112
+ symbols.append(ns)
113
+ names[ns] = row.get("company_name") or bare
114
+ sectors[ns] = row.get("sector") or "Unknown"
115
+
116
+ _stock_universe = symbols
117
+ _stock_names = names
118
+ _stock_sectors = sectors
119
+ _universe_loaded = True
120
+ logger.info(f"Loaded stock universe: {len(symbols)} stocks from Supabase")
121
+
122
+
123
+ def get_stock_universe() -> list[str]:
124
+ """Return the full list of stock symbols (lazy-loaded from DB)."""
125
+ if not _universe_loaded:
126
+ _load_stock_universe()
127
+ return _stock_universe
128
+
129
+
130
+ def get_stock_name(symbol: str) -> str:
131
+ if not _universe_loaded:
132
+ _load_stock_universe()
133
+ return _stock_names.get(symbol, symbol)
134
+
135
+
136
+ def get_stock_sector(symbol: str) -> str:
137
+ if not _universe_loaded:
138
+ _load_stock_universe()
139
+ return _stock_sectors.get(symbol, "Unknown")
140
+
141
+ # ── In-memory caches ───────────────────────────────────────────────────────────
142
+
143
+ _df_cache: dict[str, tuple[pd.DataFrame, float]] = {} # historical OHLCV
144
+ _report_cache: tuple[Optional[AnalyticsReport], float] = (None, 0.0)
145
+
146
+ # Per-stock ML model + prediction cache (trained once per report build)
147
+ # { symbol: (RandomForestClassifier, prob_up, signal_direction) }
148
+ _rf_model_cache: dict[str, tuple[object, float, SignalDirection]] = {}
149
+
150
+ # Per-stock pre-computed analysis cache (built during report generation)
151
+ # { symbol: { "signals": TechnicalSignal, "risk": RiskMetrics, "rf_probability": float, ... } }
152
+ _analysis_cache: dict[str, dict] = {}
153
+ _analysis_cache_ts: float = 0.0
154
+
155
+ HIST_CACHE_TTL = 86400 # 24 hr — yfinance (once-a-day re-fetch)
156
+ REPORT_TTL = 7200 # 2 hr — full analytics report
157
+
158
+ # ── Supabase REST helpers ──────────────────────────────────────────────────────
159
+
160
+ def _db_symbol(symbol: str) -> str:
161
+ """Strip exchange suffix for DB storage: RELIANCE.NS → RELIANCE, ^NSEI → NSEI."""
162
+ return symbol.replace(".NS", "").replace(".BO", "").replace("^", "")
163
+
164
+
165
+ def _sb_headers() -> dict:
166
+ from ..core.config import get_settings
167
+ key = get_settings().supabase_service_role_key
168
+ return {
169
+ "apikey": key,
170
+ "Authorization": f"Bearer {key}",
171
+ "Content-Type": "application/json",
172
+ "Prefer": "resolution=merge-duplicates",
173
+ }
174
+
175
+
176
+ def _sb_url(table: str) -> str:
177
+ from ..core.config import get_settings
178
+ return f"{get_settings().supabase_url}/rest/v1/{table}"
179
+
180
+
181
+ def _safe_f(v) -> Optional[float]:
182
+ try:
183
+ f = float(v)
184
+ return None if (f != f) else round(f, 6) # NaN → None
185
+ except (TypeError, ValueError):
186
+ return None
187
+
188
+
189
+ def _upsert_stocks_meta(symbols: list[str]) -> None:
190
+ """Ensure every symbol has a row in the stocks table."""
191
+ rows = [
192
+ {
193
+ "symbol": _db_symbol(sym),
194
+ "company_name": get_stock_name(sym) or _db_symbol(sym),
195
+ "exchange": "NSE",
196
+ "sector": get_stock_sector(sym),
197
+ }
198
+ for sym in symbols
199
+ ]
200
+ try:
201
+ resp = httpx.post(_sb_url("stocks"), headers=_sb_headers(), json=rows, timeout=15)
202
+ resp.raise_for_status()
203
+ except Exception as exc:
204
+ logger.warning(f"Supabase stocks meta upsert failed: {exc}")
205
+
206
+
207
+ def _save_to_supabase(symbol: str, df: pd.DataFrame) -> None:
208
+ """Bulk-upsert OHLCV data to stock_prices (upsert on symbol+date)."""
209
+ db_sym = _db_symbol(symbol)
210
+ rows = []
211
+ for _, row in df.iterrows():
212
+ rows.append({
213
+ "symbol": db_sym,
214
+ "date": str(row["date"].date()),
215
+ "open": _safe_f(row.get("open")),
216
+ "high": _safe_f(row.get("high")),
217
+ "low": _safe_f(row.get("low")),
218
+ "close": _safe_f(row.get("close")),
219
+ "volume": int(row["volume"]) if row.get("volume") and not (row["volume"] != row["volume"]) else None,
220
+ })
221
+
222
+ for i in range(0, len(rows), 500):
223
+ batch = rows[i : i + 500]
224
+ try:
225
+ resp = httpx.post(
226
+ _sb_url("stock_prices") + "?on_conflict=symbol,date",
227
+ headers=_sb_headers(), json=batch, timeout=30,
228
+ )
229
+ resp.raise_for_status()
230
+ except Exception as exc:
231
+ logger.warning(f"Supabase write failed for {symbol} batch {i}: {exc}")
232
+
233
+ logger.info(f"Saved {len(rows)} rows for {symbol} to Supabase")
234
+
235
+
236
+ def _load_from_supabase(symbol: str) -> pd.DataFrame:
237
+ """Load recent OHLCV rows from stock_prices (last 750 rows ≈ 3 years)."""
238
+ db_sym = _db_symbol(symbol)
239
+ try:
240
+ resp = httpx.get(
241
+ _sb_url("stock_prices"),
242
+ headers=_sb_headers(),
243
+ params={
244
+ "symbol": f"eq.{db_sym}",
245
+ "select": "date,open,high,low,close,volume",
246
+ "order": "date.desc",
247
+ "limit": "750",
248
+ },
249
+ timeout=15,
250
+ )
251
+ resp.raise_for_status()
252
+ data = resp.json()
253
+ except Exception as exc:
254
+ logger.warning(f"Supabase read failed for {symbol}: {exc}")
255
+ return pd.DataFrame()
256
+
257
+ if not data:
258
+ return pd.DataFrame()
259
+
260
+ df = pd.DataFrame(data)
261
+ df["date"] = pd.to_datetime(df["date"])
262
+ for col in df.columns:
263
+ if col != "date":
264
+ df[col] = pd.to_numeric(df[col], errors="coerce")
265
+ df = df.sort_values("date").reset_index(drop=True)
266
+
267
+ logger.debug(f"Loaded {len(df)} rows for {symbol} from Supabase")
268
+ return df
269
+
270
+
271
+
272
+ # ── Data fetching & indicators ─────────────────────────────────────────────────
273
+
274
+ def _add_indicators(df: pd.DataFrame) -> pd.DataFrame:
275
+ close = df["close"]
276
+ high = df["high"]
277
+ low = df["low"]
278
+ volume = df["volume"]
279
+
280
+ df["sma_20"] = close.rolling(20).mean()
281
+ df["sma_50"] = close.rolling(50).mean()
282
+ df["sma_200"] = close.rolling(200).mean()
283
+ df["ema_12"] = close.ewm(span=12, adjust=False).mean()
284
+ df["ema_26"] = close.ewm(span=26, adjust=False).mean()
285
+ df["macd"] = df["ema_12"] - df["ema_26"]
286
+ df["macd_signal"] = df["macd"].ewm(span=9, adjust=False).mean()
287
+ df["macd_histogram"] = df["macd"] - df["macd_signal"]
288
+
289
+ delta = close.diff()
290
+ gain = delta.clip(lower=0).rolling(14).mean()
291
+ loss = (-delta.clip(upper=0)).rolling(14).mean()
292
+ rs = gain / loss.replace(0, np.nan)
293
+ df["rsi_14"] = 100 - (100 / (1 + rs))
294
+
295
+ bb_mid = close.rolling(20).mean()
296
+ bb_std = close.rolling(20).std()
297
+ df["bb_mid"] = bb_mid
298
+ df["bb_upper"] = bb_mid + 2 * bb_std
299
+ df["bb_lower"] = bb_mid - 2 * bb_std
300
+ df["bb_width"] = (df["bb_upper"] - df["bb_lower"]) / bb_mid
301
+
302
+ prev_close = close.shift(1)
303
+ tr = pd.concat(
304
+ [high - low, (high - prev_close).abs(), (low - prev_close).abs()], axis=1
305
+ ).max(axis=1)
306
+ df["atr_14"] = tr.rolling(14).mean()
307
+
308
+ df["vol_sma_20"] = volume.rolling(20).mean()
309
+ df["vol_ratio"] = volume / df["vol_sma_20"].replace(0, np.nan)
310
+ df["daily_return"] = close.pct_change()
311
+ df["price_vs_sma20"] = (close / df["sma_20"]) - 1
312
+ df["price_vs_sma50"] = (close / df["sma_50"]) - 1
313
+ df["atr_normalized"] = df["atr_14"] / close
314
+ df["return_5d"] = close.pct_change(5)
315
+ df["return_20d"] = close.pct_change(20)
316
+
317
+ return df
318
+
319
+
320
+ # ── Yahoo Finance data fetching ────────────────────────────────────────────────
321
+
322
+ def _fetch_yfinance(symbol: str, period: str = "1y") -> pd.DataFrame:
323
+ """
324
+ Fetch daily OHLCV from Yahoo Finance (1d interval).
325
+ Returns DataFrame with columns: date, open, high, low, close, volume.
326
+ Returns empty DataFrame on any error.
327
+ """
328
+ try:
329
+ raw = yf.Ticker(symbol).history(period=period, interval="1d", auto_adjust=True)
330
+ if raw is None or raw.empty:
331
+ logger.warning(f"yfinance: no data for {symbol}")
332
+ return pd.DataFrame()
333
+ df = raw.reset_index()
334
+ df.rename(columns={"Date": "date", "Open": "open", "High": "high",
335
+ "Low": "low", "Close": "close", "Volume": "volume"}, inplace=True)
336
+ df["date"] = pd.to_datetime(df["date"]).dt.tz_localize(None)
337
+ df = df[["date", "open", "high", "low", "close", "volume"]].copy()
338
+ df = df[df["close"] > 0].reset_index(drop=True)
339
+ logger.info(f"yfinance: fetched {len(df)} rows for {symbol}")
340
+ return df
341
+ except Exception as exc:
342
+ logger.error(f"yfinance error for {symbol}: {exc}")
343
+ return pd.DataFrame()
344
+
345
+
346
+ def _get_cached_df(symbol: str, period: str = "1y") -> Optional[pd.DataFrame]:
347
+ """
348
+ Return a DataFrame of historical OHLCV + indicators for the requested period.
349
+
350
+ Fetch priority:
351
+ 1. In-memory cache (24 hr TTL) — zero network cost.
352
+ 2. Supabase stock_prices (persistent across restarts) — zero network cost
353
+ if latest row is within 3 calendar days and ≥ 50 rows.
354
+ 3. Yahoo Finance — free, no rate limits. Result saved to Supabase.
355
+ """
356
+ raw_key = f"{symbol}_raw"
357
+ now = time.time()
358
+
359
+ # 1. In-memory cache
360
+ if raw_key in _df_cache:
361
+ raw_df, ts = _df_cache[raw_key]
362
+ if now - ts < HIST_CACHE_TTL:
363
+ return _trim_period(raw_df, period)
364
+
365
+ # 2. Supabase
366
+ sb_df = _load_from_supabase(symbol)
367
+ if not sb_df.empty:
368
+ latest_date = sb_df["date"].max()
369
+ days_stale = (pd.Timestamp.now() - latest_date).days
370
+ if days_stale <= 3 and len(sb_df) >= 50:
371
+ sb_df = _add_indicators(sb_df)
372
+ _df_cache[raw_key] = (sb_df, now)
373
+ return _trim_period(sb_df, period)
374
+
375
+ # 3. Yahoo Finance (full history)
376
+ raw_df = _fetch_yfinance(symbol, period="max")
377
+ if raw_df.empty:
378
+ if not sb_df.empty: # stale Supabase is better than nothing
379
+ sb_df = _add_indicators(sb_df)
380
+ _df_cache[raw_key] = (sb_df, now)
381
+ return _trim_period(sb_df, period)
382
+ return None
383
+
384
+ raw_df = _add_indicators(raw_df)
385
+ _upsert_stocks_meta([symbol])
386
+ _save_to_supabase(symbol, raw_df)
387
+ _df_cache[raw_key] = (raw_df, now)
388
+ return _trim_period(raw_df, period)
389
+
390
+
391
+ def _trim_period(df: pd.DataFrame, period: str) -> Optional[pd.DataFrame]:
392
+ """Trim a full-history DataFrame to the requested period."""
393
+ period_days = {"1mo": 30, "3mo": 92, "6mo": 183, "1y": 365, "2y": 730, "5y": 1825}
394
+ n_days = period_days.get(period, 365)
395
+ cutoff = pd.Timestamp.now() - pd.Timedelta(days=n_days)
396
+ trimmed = df[df["date"] >= cutoff].copy().reset_index(drop=True)
397
+ return trimmed if len(trimmed) >= 20 else None
398
+
399
+
400
+ def preload_stock_data() -> int:
401
+ """Bulk-load ALL stock price data from Supabase in one query, then split per symbol."""
402
+ universe = get_stock_universe()
403
+ if not universe:
404
+ return 0
405
+
406
+ already = sum(1 for sym in universe if f"{sym}_raw" in _df_cache)
407
+ if already == len(universe):
408
+ return already
409
+
410
+ logger.info(f"Bulk-loading stock prices from Supabase…")
411
+
412
+ # Single query: fetch last 750 rows per stock using a window function via RPC,
413
+ # or just fetch all recent data. With 500 stocks × 750 rows = 375K rows max.
414
+ # Supabase REST has no window function, so we fetch the last 3 years of data
415
+ # for ALL stocks in one paginated call.
416
+ from ..core.config import get_settings
417
+ settings = get_settings()
418
+ url = f"{settings.supabase_url}/rest/v1/stock_prices"
419
+ headers = {
420
+ "apikey": settings.supabase_service_role_key,
421
+ "Authorization": f"Bearer {settings.supabase_service_role_key}",
422
+ "Content-Type": "application/json",
423
+ }
424
+
425
+ cutoff = (pd.Timestamp.now() - pd.Timedelta(days=750)).strftime("%Y-%m-%d")
426
+ all_data: list[dict] = []
427
+ page_size = 10000
428
+ offset = 0
429
+
430
+ while True:
431
+ try:
432
+ resp = httpx.get(
433
+ url, headers=headers,
434
+ params={
435
+ "select": "symbol,date,open,high,low,close,volume",
436
+ "date": f"gte.{cutoff}",
437
+ "order": "symbol.asc,date.asc",
438
+ "limit": str(page_size),
439
+ "offset": str(offset),
440
+ },
441
+ timeout=30,
442
+ )
443
+ resp.raise_for_status()
444
+ page = resp.json()
445
+ except Exception as exc:
446
+ logger.warning(f"Bulk load page failed at offset {offset}: {exc}")
447
+ break
448
+
449
+ if not page:
450
+ break
451
+ all_data.extend(page)
452
+ logger.info(f" Fetched {len(all_data)} rows so far…")
453
+ if len(page) < page_size:
454
+ break
455
+ offset += page_size
456
+
457
+ if not all_data:
458
+ logger.warning("Bulk load returned no data")
459
+ return already
460
+
461
+ logger.info(f"Bulk load complete: {len(all_data)} rows. Splitting per symbol…")
462
+
463
+ # Build one big DataFrame, split by symbol
464
+ big_df = pd.DataFrame(all_data)
465
+ big_df["date"] = pd.to_datetime(big_df["date"])
466
+ for col in ["open", "high", "low", "close", "volume"]:
467
+ big_df[col] = pd.to_numeric(big_df[col], errors="coerce")
468
+
469
+ now = time.time()
470
+ loaded = 0
471
+
472
+ def _process_group(sym_bare: str, group_df: pd.DataFrame) -> bool:
473
+ ns = f"{sym_bare}.NS"
474
+ key = f"{ns}_raw"
475
+ if key in _df_cache:
476
+ return False
477
+ df = group_df.drop(columns=["symbol"]).reset_index(drop=True)
478
+ if len(df) < 20:
479
+ return False
480
+ df = _add_indicators(df)
481
+ _df_cache[key] = (df, now)
482
+ return True
483
+
484
+ # Process in parallel (indicator computation is CPU-bound)
485
+ groups = {sym: grp.copy() for sym, grp in big_df.groupby("symbol")}
486
+ with ThreadPoolExecutor(max_workers=16) as pool:
487
+ futs = {pool.submit(_process_group, sym, grp): sym for sym, grp in groups.items()}
488
+ for fut in as_completed(futs):
489
+ try:
490
+ if fut.result():
491
+ loaded += 1
492
+ except Exception:
493
+ pass
494
+
495
+ total = already + loaded
496
+ logger.info(f"Preload done: {loaded} newly cached, {total} total in cache")
497
+ return total
498
+
499
+
500
+ # ── 1. Technical signals ───────────────────────────────────────────────────────
501
+
502
+ def compute_technical_signals(symbol: str, df: pd.DataFrame) -> TechnicalSignal:
503
+ last = df.iloc[-1]
504
+ signals: list[IndicatorSignal] = []
505
+ score = 0.0
506
+
507
+ def _safe(col: str):
508
+ v = last.get(col, np.nan)
509
+ return float(v) if not (isinstance(v, float) and np.isnan(v)) else np.nan
510
+
511
+ # RSI
512
+ rsi = _safe("rsi_14")
513
+ if not np.isnan(rsi):
514
+ if rsi < 30:
515
+ d, s = SignalDirection.BUY, 2.0
516
+ elif rsi > 70:
517
+ d, s = SignalDirection.SELL, -2.0
518
+ else:
519
+ d, s = SignalDirection.HOLD, 0.0
520
+ signals.append(IndicatorSignal(name="RSI", direction=d, score=s, value=round(rsi, 2)))
521
+ score += s
522
+
523
+ # MACD
524
+ macd, macd_sig = _safe("macd"), _safe("macd_signal")
525
+ if not np.isnan(macd) and not np.isnan(macd_sig):
526
+ if macd > macd_sig:
527
+ d, s = SignalDirection.BUY, 1.5
528
+ else:
529
+ d, s = SignalDirection.SELL, -1.5
530
+ signals.append(IndicatorSignal(name="MACD", direction=d, score=s, value=round(macd, 4)))
531
+ score += s
532
+
533
+ # SMA crossover
534
+ sma20, sma50 = _safe("sma_20"), _safe("sma_50")
535
+ if not np.isnan(sma20) and not np.isnan(sma50):
536
+ if sma20 > sma50:
537
+ d, s = SignalDirection.BUY, 1.0
538
+ else:
539
+ d, s = SignalDirection.SELL, -1.0
540
+ signals.append(IndicatorSignal(name="SMA_Cross", direction=d, score=s, value=round(sma20, 2)))
541
+ score += s
542
+
543
+ # Bollinger Bands
544
+ close, bb_upper, bb_lower = _safe("close"), _safe("bb_upper"), _safe("bb_lower")
545
+ if not np.isnan(close) and not np.isnan(bb_upper) and not np.isnan(bb_lower):
546
+ if close < bb_lower:
547
+ d, s = SignalDirection.BUY, 1.5
548
+ elif close > bb_upper:
549
+ d, s = SignalDirection.SELL, -1.5
550
+ else:
551
+ d, s = SignalDirection.HOLD, 0.0
552
+ signals.append(IndicatorSignal(name="BB", direction=d, score=s, value=round(close, 2)))
553
+ score += s
554
+
555
+ if score > 0.5:
556
+ direction = SignalDirection.BUY
557
+ elif score < -0.5:
558
+ direction = SignalDirection.SELL
559
+ else:
560
+ direction = SignalDirection.HOLD
561
+
562
+ confidence = min(abs(score) / 6.0 * 100, 100)
563
+
564
+ return TechnicalSignal(
565
+ symbol=symbol,
566
+ company_name=get_stock_name(symbol),
567
+ sector=get_stock_sector(symbol),
568
+ current_price=round(close, 2) if not np.isnan(close) else 0.0,
569
+ composite_signal=direction,
570
+ composite_score=round(score, 2),
571
+ confidence_score=round(confidence, 1),
572
+ signals=signals,
573
+ )
574
+
575
+
576
+ # ── 2. Risk metrics ────────────────────────────────────────────────────────────
577
+
578
+ def compute_risk_metrics(
579
+ symbol: str, df: pd.DataFrame, nifty_df: pd.DataFrame
580
+ ) -> RiskMetrics:
581
+ returns = df["daily_return"].dropna()
582
+ ann_return = float(returns.mean() * 252)
583
+ ann_vol = float(returns.std() * np.sqrt(252))
584
+
585
+ sharpe = (ann_return - RISK_FREE_RATE) / ann_vol if ann_vol > 0 else 0.0
586
+ neg_ret = returns[returns < 0]
587
+ down_vol = float(neg_ret.std() * np.sqrt(252)) if len(neg_ret) > 1 else ann_vol
588
+ sortino = (ann_return - RISK_FREE_RATE) / down_vol if down_vol > 0 else 0.0
589
+
590
+ cum = (1 + returns).cumprod()
591
+ roll_max = cum.cummax()
592
+ drawdown = (cum - roll_max) / roll_max
593
+ max_dd = float(drawdown.min()) * 100
594
+
595
+ var_95 = float(np.percentile(returns, 5)) * 100
596
+
597
+ beta, alpha = 1.0, 0.0
598
+ if nifty_df is not None and not nifty_df.empty and "daily_return" in nifty_df.columns:
599
+ stock_s = df.set_index("date")["daily_return"].dropna()
600
+ nifty_s = nifty_df.set_index("date")["daily_return"].dropna()
601
+ common = stock_s.index.intersection(nifty_s.index)
602
+ if len(common) > 30:
603
+ s_vals = stock_s[common].values
604
+ n_vals = nifty_s[common].values
605
+ cov_mat = np.cov(s_vals, n_vals)
606
+ if cov_mat[1, 1] > 0:
607
+ beta = float(cov_mat[0, 1] / cov_mat[1, 1])
608
+ nifty_ann = float(n_vals.mean() * 252)
609
+ alpha = (ann_return - (RISK_FREE_RATE + beta * (nifty_ann - RISK_FREE_RATE))) * 100
610
+
611
+ return RiskMetrics(
612
+ symbol=symbol,
613
+ sharpe_ratio=round(sharpe, 3),
614
+ sortino_ratio=round(sortino, 3),
615
+ max_drawdown=round(max_dd, 2),
616
+ var_95=round(var_95, 3),
617
+ beta=round(beta, 3),
618
+ volatility=round(ann_vol * 100, 2),
619
+ alpha=round(alpha, 2),
620
+ annualized_return=round(ann_return * 100, 2),
621
+ )
622
+
623
+
624
+ # ── 3. Random Forest classifier ────────────────────────────────────────────────
625
+
626
+ _FEATURES = [
627
+ "rsi_14", "macd", "macd_signal", "bb_width", "vol_ratio",
628
+ "price_vs_sma20", "price_vs_sma50", "return_5d", "return_20d", "atr_normalized",
629
+ ]
630
+
631
+
632
+ def train_rf_classifier(df: pd.DataFrame, symbol: str = "") -> tuple[float, SignalDirection]:
633
+ # Use cached model if available (models are trained once per report build)
634
+ if symbol and symbol in _rf_model_cache:
635
+ clf, cached_prob, cached_sig = _rf_model_cache[symbol]
636
+ # Re-predict with latest features if model exists
637
+ try:
638
+ df_c = df.dropna(subset=_FEATURES + ["close"])
639
+ if len(df_c) >= 1:
640
+ prob_up = float(clf.predict_proba(df_c[_FEATURES].values[-1:, :])[0][1])
641
+ sig = SignalDirection.BUY if prob_up > 0.6 else (SignalDirection.SELL if prob_up < 0.4 else SignalDirection.HOLD)
642
+ return round(prob_up, 3), sig
643
+ except Exception:
644
+ pass
645
+ return cached_prob, cached_sig
646
+
647
+ df_c = df.dropna(subset=_FEATURES + ["close"]).copy()
648
+ if len(df_c) < 40:
649
+ return 0.5, SignalDirection.HOLD
650
+
651
+ df_c["target"] = (df_c["close"].shift(-5) > df_c["close"]).astype(int)
652
+ df_c = df_c.dropna(subset=["target"])
653
+
654
+ X = df_c[_FEATURES].values
655
+ y = df_c["target"].values.astype(int)
656
+
657
+ split = int(len(X) * 0.8)
658
+ X_train, y_train = X[:split], y[:split]
659
+
660
+ if len(X_train) < 30 or len(set(y_train)) < 2:
661
+ return 0.5, SignalDirection.HOLD
662
+
663
+ clf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42, n_jobs=1)
664
+ clf.fit(X_train, y_train)
665
+
666
+ prob_up = float(clf.predict_proba(df_c[_FEATURES].values[-1:, :])[0][1])
667
+
668
+ if prob_up > 0.6:
669
+ sig = SignalDirection.BUY
670
+ elif prob_up < 0.4:
671
+ sig = SignalDirection.SELL
672
+ else:
673
+ sig = SignalDirection.HOLD
674
+
675
+ # Cache the trained model
676
+ if symbol:
677
+ _rf_model_cache[symbol] = (clf, round(prob_up, 3), sig)
678
+
679
+ return round(prob_up, 3), sig
680
+
681
+
682
+ # ── 4. Portfolio optimisation ──────────────────────────────────────────────────
683
+
684
+ def optimize_portfolio(
685
+ symbols: list[str], risk_profile: str = "moderate", n_portfolios: int = 2000
686
+ ) -> Optional[PortfolioOptimizationResult]:
687
+ series_list: list[pd.Series] = []
688
+ valid: list[str] = []
689
+
690
+ for sym in symbols:
691
+ df = _get_cached_df(sym, "2y")
692
+ if df is not None and len(df) > 50:
693
+ s = df.set_index("date")["daily_return"].dropna()
694
+ s.name = sym
695
+ series_list.append(s)
696
+ valid.append(sym)
697
+
698
+ if len(valid) < 2:
699
+ return None
700
+
701
+ rets_df = pd.concat(series_list, axis=1).dropna()
702
+ n = len(valid)
703
+ mu = rets_df.mean().values * 252 # annualised mean returns
704
+ cov = rets_df.cov().values * 252 # annualised cov matrix
705
+
706
+ # Monte Carlo
707
+ mc: list[dict] = []
708
+ for _ in range(n_portfolios):
709
+ w = np.random.dirichlet(np.ones(n))
710
+ r = float(w @ mu)
711
+ v = float(np.sqrt(w @ cov @ w))
712
+ sh = (r - RISK_FREE_RATE) / v if v > 0 else 0.0
713
+ mc.append({"vol": v, "ret": r, "sharpe": sh, "w": w})
714
+
715
+ # scipy helpers
716
+ def port_vol(w: np.ndarray) -> float:
717
+ return float(np.sqrt(w @ cov @ w))
718
+
719
+ def neg_sharpe(w: np.ndarray) -> float:
720
+ r = float(w @ mu)
721
+ v = port_vol(w)
722
+ return -(r - RISK_FREE_RATE) / v if v > 0 else 0.0
723
+
724
+ cons = [{"type": "eq", "fun": lambda w: np.sum(w) - 1}]
725
+ bnds = [(0.0, 1.0)] * n
726
+ w0 = np.ones(n) / n
727
+
728
+ res_minv = minimize(port_vol, w0, method="SLSQP", bounds=bnds, constraints=cons)
729
+ res_maxs = minimize(neg_sharpe, w0, method="SLSQP", bounds=bnds, constraints=cons)
730
+
731
+ def w_to_dict(w_arr: np.ndarray) -> dict[str, float]:
732
+ return {sym: round(float(w), 4) for sym, w in zip(valid, w_arr)}
733
+
734
+ min_var_w = w_to_dict(res_minv.x if res_minv.success else w0)
735
+ max_shr_w = w_to_dict(res_maxs.x if res_maxs.success else w0)
736
+
737
+ # Risk-profile weights (minimise distance to target vol)
738
+ target_vols = {"conservative": 0.12, "moderate": 0.18, "aggressive": 0.25}
739
+ tv = target_vols.get(risk_profile, 0.18)
740
+
741
+ def vol_dist(w: np.ndarray) -> float:
742
+ return (port_vol(w) - tv) ** 2
743
+
744
+ res_rp = minimize(vol_dist, w0, method="SLSQP", bounds=bnds, constraints=cons)
745
+ rp_w = w_to_dict(res_rp.x if res_rp.success else w0)
746
+
747
+ # Efficient frontier: 50 vol bins
748
+ all_vols = [p["vol"] for p in mc]
749
+ v_bins = np.linspace(min(all_vols), max(all_vols), 51)
750
+ frontier: list[EfficientFrontierPoint] = []
751
+ for i in range(50):
752
+ bucket = [p for p in mc if v_bins[i] <= p["vol"] < v_bins[i + 1]]
753
+ if bucket:
754
+ best = max(bucket, key=lambda p: p["ret"])
755
+ frontier.append(
756
+ EfficientFrontierPoint(
757
+ vol=round(best["vol"] * 100, 2),
758
+ ret=round(best["ret"] * 100, 2),
759
+ sharpe=round(best["sharpe"], 3),
760
+ )
761
+ )
762
+
763
+ # Correlation matrix
764
+ corr = rets_df.corr()
765
+ corr_matrix = [[round(float(corr.iloc[i, j]), 3) for j in range(n)] for i in range(n)]
766
+
767
+ def port_stats(wd: dict) -> PortfolioStats:
768
+ w = np.array([wd[s] for s in valid])
769
+ r = float(w @ mu) * 100
770
+ v = port_vol(w) * 100
771
+ sh = (r / 100 - RISK_FREE_RATE) / (v / 100) if v > 0 else 0.0
772
+ return PortfolioStats(expected_return=round(r, 2), volatility=round(v, 2), sharpe=round(sh, 3))
773
+
774
+ mc_out = [
775
+ EfficientFrontierPoint(vol=round(p["vol"] * 100, 2), ret=round(p["ret"] * 100, 2), sharpe=round(p["sharpe"], 3))
776
+ for p in mc[:500] # cap response size
777
+ ]
778
+
779
+ return PortfolioOptimizationResult(
780
+ symbols=valid,
781
+ min_variance_weights=min_var_w,
782
+ max_sharpe_weights=max_shr_w,
783
+ risk_profile_weights=rp_w,
784
+ risk_profile=risk_profile,
785
+ efficient_frontier=frontier,
786
+ correlation_matrix=corr_matrix,
787
+ mc_results=mc_out,
788
+ min_variance_stats=port_stats(min_var_w),
789
+ max_sharpe_stats=port_stats(max_shr_w),
790
+ risk_profile_stats=port_stats(rp_w),
791
+ )
792
+
793
+
794
+ # ── 5. Clustering ──────────────────────────────────────────────────────────────
795
+
796
+ def cluster_stocks(symbols: list[str]) -> ClusteringResult:
797
+ nifty_df = _get_cached_df(NIFTY_INDEX, "1y")
798
+ feat_rows: list[list[float]] = []
799
+ valid: list[str] = []
800
+
801
+ for sym in symbols:
802
+ df = _get_cached_df(sym, "1y")
803
+ if df is None or len(df) < 30:
804
+ continue
805
+
806
+ rets = df["daily_return"].dropna()
807
+ ann_vol = float(rets.std() * np.sqrt(252))
808
+ mom30 = float((df["close"].iloc[-1] / df["close"].iloc[-30]) - 1)
809
+
810
+ beta = 1.0
811
+ if nifty_df is not None and not nifty_df.empty:
812
+ s_s = df.set_index("date")["daily_return"].dropna()
813
+ n_s = nifty_df.set_index("date")["daily_return"].dropna()
814
+ common = s_s.index.intersection(n_s.index)
815
+ if len(common) > 30:
816
+ c = np.cov(s_s[common].values, n_s[common].values)
817
+ if c[1, 1] > 0:
818
+ beta = float(c[0, 1] / c[1, 1])
819
+
820
+ feat_rows.append([ann_vol, mom30, beta])
821
+ valid.append(sym)
822
+
823
+ if len(valid) < 4:
824
+ return ClusteringResult(clusters=[])
825
+
826
+ X = np.array(feat_rows)
827
+ X_sc = StandardScaler().fit_transform(X)
828
+ km = KMeans(n_clusters=4, random_state=42, n_init=10)
829
+ labels = km.fit_predict(X_sc)
830
+
831
+ # Label clusters by centroid volatility (ascending)
832
+ vol_order = np.argsort(km.cluster_centers_[:, 0])
833
+ label_map = {
834
+ vol_order[0]: ClusterLabel.DEFENSIVE,
835
+ vol_order[1]: ClusterLabel.VALUE,
836
+ vol_order[2]: ClusterLabel.MOMENTUM,
837
+ vol_order[3]: ClusterLabel.HIGH_VOLATILITY,
838
+ }
839
+
840
+ clusters = [
841
+ StockCluster(
842
+ symbol=valid[i],
843
+ cluster_id=int(labels[i]),
844
+ cluster_label=label_map[int(labels[i])],
845
+ volatility=round(feat_rows[i][0] * 100, 2),
846
+ momentum_30d=round(feat_rows[i][1] * 100, 2),
847
+ beta=round(feat_rows[i][2], 3),
848
+ )
849
+ for i in range(len(valid))
850
+ ]
851
+ return ClusteringResult(clusters=clusters)
852
+
853
+
854
+ # ── 6. Anomaly detection ───────────────────────────────────────────────────────
855
+
856
+ def detect_anomalies(symbol: str, df: pd.DataFrame) -> list[AnomalyAlert]:
857
+ alerts: list[AnomalyAlert] = []
858
+ if len(df) < 60:
859
+ return alerts
860
+
861
+ recent = df.iloc[-60:].copy()
862
+ recent["abs_return"] = recent["daily_return"].abs()
863
+
864
+ # Volume z-score
865
+ vol_mean, vol_std = recent["volume"].mean(), recent["volume"].std()
866
+ last_vol = recent["volume"].iloc[-1]
867
+ vol_z = (last_vol - vol_mean) / vol_std if vol_std > 0 else 0.0
868
+ if abs(vol_z) > 2.5:
869
+ sev = AnomalySeverity.HIGH if abs(vol_z) > 3.5 else AnomalySeverity.MEDIUM
870
+ alerts.append(AnomalyAlert(
871
+ symbol=symbol, anomaly_type=AnomalyType.VOLUME_SPIKE, severity=sev,
872
+ z_score=round(float(vol_z), 2),
873
+ description=f"Unusual volume: {abs(vol_z):.1f}σ from 60-day mean",
874
+ ))
875
+
876
+ # Return z-score
877
+ ret_mean, ret_std = recent["abs_return"].mean(), recent["abs_return"].std()
878
+ last_ret = recent["abs_return"].iloc[-1]
879
+ ret_z = (last_ret - ret_mean) / ret_std if ret_std > 0 else 0.0
880
+ if abs(ret_z) > 2.5:
881
+ sev = AnomalySeverity.HIGH if abs(ret_z) > 3.5 else AnomalySeverity.MEDIUM
882
+ alerts.append(AnomalyAlert(
883
+ symbol=symbol, anomaly_type=AnomalyType.PRICE_SPIKE, severity=sev,
884
+ z_score=round(float(ret_z), 2),
885
+ description=f"Unusual price move: {abs(ret_z):.1f}σ from 60-day mean",
886
+ ))
887
+
888
+ # IsolationForest
889
+ try:
890
+ feat_df = recent[["daily_return", "vol_ratio", "bb_width"]].dropna()
891
+ if len(feat_df) >= 20:
892
+ arr = feat_df.values
893
+ iso = IsolationForest(contamination=0.05, random_state=42)
894
+ preds = iso.fit_predict(arr)
895
+ scores = iso.decision_function(arr)
896
+ for i in range(-5, 0):
897
+ if preds[i] == -1 and scores[i] < -0.15:
898
+ sev = AnomalySeverity.HIGH if scores[i] < -0.25 else AnomalySeverity.MEDIUM
899
+ alerts.append(AnomalyAlert(
900
+ symbol=symbol, anomaly_type=AnomalyType.ISOLATION_FOREST, severity=sev,
901
+ z_score=round(float(abs(scores[i]) * 10), 2),
902
+ description=f"IsolationForest anomaly (score={scores[i]:.3f})",
903
+ ))
904
+ break
905
+ except Exception as exc:
906
+ logger.debug(f"IsolationForest skipped for {symbol}: {exc}")
907
+
908
+ return alerts
909
+
910
+
911
+ # ── 7. Correlation matrix ──────────────────────────────────────────────────────
912
+
913
+ def compute_correlation_matrix(symbols: list[str]) -> CorrelationMatrix:
914
+ series_list: list[pd.Series] = []
915
+ valid: list[str] = []
916
+
917
+ for sym in symbols:
918
+ df = _get_cached_df(sym, "1y")
919
+ if df is not None and len(df) > 50:
920
+ s = df.set_index("date")["daily_return"].dropna()
921
+ s.name = sym
922
+ series_list.append(s)
923
+ valid.append(sym)
924
+
925
+ if len(valid) < 2:
926
+ return CorrelationMatrix(symbols=[], matrix=[], high_correlation_pairs=[])
927
+
928
+ rets_df = pd.concat(series_list, axis=1).dropna()
929
+ corr = rets_df.corr()
930
+ n = len(valid)
931
+ matrix = [[round(float(corr.iloc[i, j]), 3) for j in range(n)] for i in range(n)]
932
+
933
+ pairs = [
934
+ CorrelationPair(symbol1=valid[i], symbol2=valid[j], correlation=round(float(corr.iloc[i, j]), 3))
935
+ for i in range(n)
936
+ for j in range(i + 1, n)
937
+ if abs(float(corr.iloc[i, j])) > 0.8
938
+ ]
939
+
940
+ return CorrelationMatrix(symbols=valid, matrix=matrix, high_correlation_pairs=pairs)
941
+
942
+
943
+ # ── 8. Screener ────────────────────────────────────────────────────────────────
944
+
945
+ def screen_stocks(
946
+ sector: Optional[str] = None,
947
+ signal: Optional[str] = None,
948
+ min_sharpe: Optional[float] = None,
949
+ max_drawdown_threshold: Optional[float] = None,
950
+ sort_by: str = "composite_score",
951
+ limit: int = 30,
952
+ ) -> ScreenerResponse:
953
+ stocks: list[ScreenerStock] = []
954
+
955
+ # Fast path: use pre-computed analysis cache from report build
956
+ use_cache = bool(_analysis_cache) and time.time() - _analysis_cache_ts < REPORT_TTL
957
+
958
+ if use_cache:
959
+ for sym, cached in _analysis_cache.items():
960
+ try:
961
+ sig = cached["signals"]
962
+ risk = cached["risk"]
963
+
964
+ df = _get_cached_df(sym, "1y")
965
+ current_price = float(df.iloc[-1]["close"]) if df is not None and not df.empty else 0.0
966
+ rsi_val = float(df.iloc[-1].get("rsi_14", 50)) if df is not None and not df.empty else 50.0
967
+ if np.isnan(rsi_val):
968
+ rsi_val = 50.0
969
+
970
+ stock = ScreenerStock(
971
+ symbol=sym,
972
+ company_name=get_stock_name(sym),
973
+ sector=get_stock_sector(sym),
974
+ current_price=round(current_price, 2),
975
+ daily_change_pct=round(cached["daily_change_pct"], 2),
976
+ composite_signal=sig.composite_signal,
977
+ confidence_score=sig.confidence_score,
978
+ composite_score=sig.composite_score,
979
+ rsi=round(rsi_val, 1),
980
+ sharpe_ratio=risk.sharpe_ratio,
981
+ max_drawdown=risk.max_drawdown,
982
+ volatility=risk.volatility,
983
+ beta=risk.beta,
984
+ )
985
+
986
+ if sector and stock.sector != sector:
987
+ continue
988
+ if signal and stock.composite_signal.value != signal:
989
+ continue
990
+ if min_sharpe is not None and stock.sharpe_ratio < min_sharpe:
991
+ continue
992
+ if max_drawdown_threshold is not None and stock.max_drawdown < -abs(max_drawdown_threshold):
993
+ continue
994
+
995
+ stocks.append(stock)
996
+ except Exception as exc:
997
+ logger.warning(f"Screener (cached) failed for {sym}: {exc}")
998
+ else:
999
+ # Slow path: compute from scratch (only on first load before report is built)
1000
+ _nifty = _get_cached_df(NIFTY_INDEX, "1y")
1001
+ nifty_df = _nifty if _nifty is not None else pd.DataFrame()
1002
+
1003
+ for sym in get_stock_universe():
1004
+ try:
1005
+ df = _get_cached_df(sym, "1y")
1006
+ if df is None or df.empty:
1007
+ continue
1008
+
1009
+ sig = compute_technical_signals(sym, df)
1010
+ risk = compute_risk_metrics(sym, df, nifty_df)
1011
+
1012
+ current_price = float(df.iloc[-1]["close"])
1013
+ prev = df.iloc[-2] if len(df) >= 2 else df.iloc[-1]
1014
+ change_pct = float((df.iloc[-1]["close"] - prev["close"]) / prev["close"] * 100) if prev["close"] > 0 else 0.0
1015
+
1016
+ rsi_val = float(df.iloc[-1].get("rsi_14", 50))
1017
+ if np.isnan(rsi_val):
1018
+ rsi_val = 50.0
1019
+
1020
+ stock = ScreenerStock(
1021
+ symbol=sym,
1022
+ company_name=get_stock_name(sym),
1023
+ sector=get_stock_sector(sym),
1024
+ current_price=round(current_price, 2),
1025
+ daily_change_pct=round(change_pct, 2),
1026
+ composite_signal=sig.composite_signal,
1027
+ confidence_score=sig.confidence_score,
1028
+ composite_score=sig.composite_score,
1029
+ rsi=round(rsi_val, 1),
1030
+ sharpe_ratio=risk.sharpe_ratio,
1031
+ max_drawdown=risk.max_drawdown,
1032
+ volatility=risk.volatility,
1033
+ beta=risk.beta,
1034
+ )
1035
+
1036
+ if sector and stock.sector != sector:
1037
+ continue
1038
+ if signal and stock.composite_signal.value != signal:
1039
+ continue
1040
+ if min_sharpe is not None and stock.sharpe_ratio < min_sharpe:
1041
+ continue
1042
+ if max_drawdown_threshold is not None and stock.max_drawdown < -abs(max_drawdown_threshold):
1043
+ continue
1044
+
1045
+ stocks.append(stock)
1046
+ except Exception as exc:
1047
+ logger.warning(f"Screener failed for {sym}: {exc}")
1048
+
1049
+ # Sort — most fields descending, volatility/drawdown ascending
1050
+ reverse = sort_by not in ["max_drawdown", "volatility"]
1051
+ stocks.sort(key=lambda s: getattr(s, sort_by, 0), reverse=reverse)
1052
+ stocks = stocks[:limit]
1053
+
1054
+ buy = sum(1 for s in stocks if s.composite_signal == SignalDirection.BUY)
1055
+ sell = sum(1 for s in stocks if s.composite_signal == SignalDirection.SELL)
1056
+ return ScreenerResponse(stocks=stocks, total=len(stocks), buy_count=buy, sell_count=sell, hold_count=len(stocks) - buy - sell)
1057
+
1058
+
1059
+ # ── 9. Backtest ────────────────────────────────────────────────────────────────
1060
+
1061
+ def backtest_strategy(symbol: str) -> BacktestResult:
1062
+ df = _get_cached_df(symbol, "2y")
1063
+ nifty_df = _get_cached_df(NIFTY_INDEX, "2y")
1064
+
1065
+ if df is None or len(df) < 100:
1066
+ return BacktestResult(
1067
+ symbol=symbol, equity_curve=[], total_return=0.0,
1068
+ benchmark_return=0.0, alpha=0.0, sharpe_ratio=0.0, num_trades=0, win_rate=0.0,
1069
+ )
1070
+
1071
+ df = df.copy()
1072
+
1073
+ # Compute composite score per row (vectorised approximation)
1074
+ rsi = df["rsi_14"].fillna(50)
1075
+ macd = df["macd"].fillna(0)
1076
+ macd_sig = df["macd_signal"].fillna(0)
1077
+ sma20 = df["sma_20"].fillna(df["close"])
1078
+ sma50 = df["sma_50"].fillna(df["close"])
1079
+ close = df["close"]
1080
+ bb_upper = df["bb_upper"].fillna(close * 1.1)
1081
+ bb_lower = df["bb_lower"].fillna(close * 0.9)
1082
+
1083
+ score = (
1084
+ np.where(rsi < 30, 2.0, np.where(rsi > 70, -2.0, 0.0))
1085
+ + np.where(macd > macd_sig, 1.5, -1.5)
1086
+ + np.where(sma20 > sma50, 1.0, -1.0)
1087
+ + np.where(close < bb_lower, 1.5, np.where(close > bb_upper, -1.5, 0.0))
1088
+ )
1089
+
1090
+ df["composite_score"] = score
1091
+ df["position"] = (score > 0.5).astype(float)
1092
+ df["position_lag"] = df["position"].shift(1).fillna(0)
1093
+ df["strategy_return"] = df["position_lag"] * df["daily_return"]
1094
+
1095
+ clean = df.dropna(subset=["strategy_return", "daily_return"]).copy()
1096
+ if len(clean) < 20:
1097
+ return BacktestResult(
1098
+ symbol=symbol, equity_curve=[], total_return=0.0,
1099
+ benchmark_return=0.0, alpha=0.0, sharpe_ratio=0.0, num_trades=0, win_rate=0.0,
1100
+ )
1101
+
1102
+ strat_eq = (1 + clean["strategy_return"]).cumprod()
1103
+ bench_eq = (1 + clean["daily_return"]).cumprod()
1104
+
1105
+ # Align benchmark to Nifty if available
1106
+ if nifty_df is not None and not nifty_df.empty:
1107
+ nifty_s = nifty_df.set_index("date")["daily_return"].dropna()
1108
+ aligned = nifty_s.reindex(clean["date"].values).fillna(0)
1109
+ bench_eq = (1 + aligned.values).cumprod()
1110
+
1111
+ # Normalise to start at 100
1112
+ strat_eq = strat_eq / strat_eq.iloc[0] * 100
1113
+ bench_eq_vals = (bench_eq / bench_eq[0] * 100) if hasattr(bench_eq, "iloc") else (bench_eq / bench_eq[0] * 100)
1114
+
1115
+ total_return = float(strat_eq.iloc[-1] - 100)
1116
+ bench_return = float(bench_eq_vals[-1] - 100) if not hasattr(bench_eq_vals, "iloc") else float(bench_eq_vals.iloc[-1] - 100)
1117
+
1118
+ strat_ann_ret = float(clean["strategy_return"].mean() * 252)
1119
+ strat_ann_vol = float(clean["strategy_return"].std() * np.sqrt(252))
1120
+ sharpe = (strat_ann_ret - RISK_FREE_RATE) / strat_ann_vol if strat_ann_vol > 0 else 0.0
1121
+
1122
+ bench_ann_ret = float(clean["daily_return"].mean() * 252)
1123
+ alpha = (strat_ann_ret - bench_ann_ret) * 100
1124
+
1125
+ num_trades = int(clean["position_lag"].diff().abs().sum())
1126
+ active = clean["strategy_return"] != 0
1127
+ win_rate = float((clean.loc[active, "strategy_return"] > 0).mean() * 100) if active.any() else 0.0
1128
+
1129
+ # Equity curve (every 5 days)
1130
+ dates = clean["date"].values
1131
+ bench_arr = bench_eq_vals if not hasattr(bench_eq_vals, "values") else bench_eq_vals.values
1132
+ strat_arr = strat_eq.values
1133
+
1134
+ equity_curve = [
1135
+ EquityPoint(
1136
+ date=str(dates[i])[:10],
1137
+ strategy=round(float(strat_arr[i]), 2),
1138
+ benchmark=round(float(bench_arr[i]), 2),
1139
+ )
1140
+ for i in range(0, len(clean), 5)
1141
+ ]
1142
+
1143
+ return BacktestResult(
1144
+ symbol=symbol,
1145
+ equity_curve=equity_curve,
1146
+ total_return=round(total_return, 2),
1147
+ benchmark_return=round(bench_return, 2),
1148
+ alpha=round(alpha, 2),
1149
+ sharpe_ratio=round(sharpe, 3),
1150
+ num_trades=num_trades,
1151
+ win_rate=round(win_rate, 1),
1152
+ )
1153
+
1154
+
1155
+ # ── 10. Full analytics report ──────────────────────────────────────────────────
1156
+
1157
+ def _analyze_stock_worker(symbol: str, nifty_df: pd.DataFrame) -> Optional[dict]:
1158
+ try:
1159
+ df = _get_cached_df(symbol, "1y")
1160
+ if df is None or df.empty:
1161
+ return None
1162
+ signals = compute_technical_signals(symbol, df)
1163
+ risk = compute_risk_metrics(symbol, df, nifty_df)
1164
+ prob_up, rf_sig = train_rf_classifier(df, symbol=symbol)
1165
+ anomalies = detect_anomalies(symbol, df)
1166
+ last = df.iloc[-1]
1167
+ prev = df.iloc[-2] if len(df) >= 2 else last
1168
+ chg = float((last["close"] - prev["close"]) / prev["close"] * 100) if prev["close"] > 0 else 0.0
1169
+ result = {
1170
+ "symbol": symbol,
1171
+ "signals": signals,
1172
+ "risk": risk,
1173
+ "rf_probability": prob_up,
1174
+ "rf_signal": rf_sig,
1175
+ "anomalies": anomalies,
1176
+ "daily_change_pct": chg,
1177
+ }
1178
+ # Cache per-stock analysis for fast access by screener / smart portfolio
1179
+ _analysis_cache[symbol] = result
1180
+ return result
1181
+ except Exception as exc:
1182
+ logger.warning(f"Worker failed for {symbol}: {exc}")
1183
+ return None
1184
+
1185
+
1186
+ def get_analytics_report(force_refresh: bool = False) -> AnalyticsReport:
1187
+ global _report_cache
1188
+ cached, ts = _report_cache
1189
+ if not force_refresh and cached is not None and time.time() - ts < REPORT_TTL:
1190
+ return cached
1191
+
1192
+ logger.info("Building full analytics report for %d stocks…", len(get_stock_universe()))
1193
+ _nifty = _get_cached_df(NIFTY_INDEX, "1y")
1194
+ nifty_df = _nifty if _nifty is not None else pd.DataFrame()
1195
+
1196
+ results: dict[str, dict] = {}
1197
+ universe = get_stock_universe()
1198
+ with ThreadPoolExecutor(max_workers=20) as pool:
1199
+ fmap = {pool.submit(_analyze_stock_worker, sym, nifty_df): sym for sym in universe}
1200
+ for fut in as_completed(fmap):
1201
+ sym = fmap[fut]
1202
+ try:
1203
+ res = fut.result()
1204
+ if res:
1205
+ results[sym] = res
1206
+ except Exception as exc:
1207
+ logger.warning(f"Report worker error for {sym}: {exc}")
1208
+
1209
+ # Market breadth
1210
+ buy_count = sum(1 for r in results.values() if r["signals"].composite_signal == SignalDirection.BUY)
1211
+ sell_count = sum(1 for r in results.values() if r["signals"].composite_signal == SignalDirection.SELL)
1212
+ hold_count = len(results) - buy_count - sell_count
1213
+
1214
+ # Sector heatmap
1215
+ sector_data: dict[str, list[float]] = {}
1216
+ for r in results.values():
1217
+ sec = get_stock_sector(r["symbol"])
1218
+ sector_data.setdefault(sec, []).append(r["daily_change_pct"])
1219
+ sector_heatmap = [
1220
+ SectorHeatmapItem(sector=s, avg_change_pct=round(sum(v) / len(v), 2), stock_count=len(v))
1221
+ for s, v in sector_data.items()
1222
+ ]
1223
+
1224
+ # Top gainers / losers
1225
+ by_chg = sorted(results.values(), key=lambda r: r["daily_change_pct"], reverse=True)
1226
+ top_gainers = [
1227
+ TrendingStock(symbol=r["symbol"], company_name=get_stock_name(r["symbol"]), change_pct=round(r["daily_change_pct"], 2))
1228
+ for r in by_chg[:5]
1229
+ ]
1230
+ top_losers = [
1231
+ TrendingStock(symbol=r["symbol"], company_name=get_stock_name(r["symbol"]), change_pct=round(r["daily_change_pct"], 2))
1232
+ for r in by_chg[-5:]
1233
+ ]
1234
+
1235
+ all_anomalies = [a for r in results.values() for a in r["anomalies"]]
1236
+
1237
+ stock_analyses = [
1238
+ StockAnalysis(
1239
+ symbol=r["symbol"],
1240
+ company_name=get_stock_name(r["symbol"]),
1241
+ sector=get_stock_sector(r["symbol"]),
1242
+ technical_signals=r["signals"],
1243
+ risk_metrics=r["risk"],
1244
+ rf_probability=r["rf_probability"],
1245
+ rf_signal=r["rf_signal"],
1246
+ anomalies=r["anomalies"],
1247
+ )
1248
+ for r in results.values()
1249
+ ]
1250
+
1251
+ clustering = cluster_stocks(list(results.keys()))
1252
+ correlation = compute_correlation_matrix(list(results.keys())[:15])
1253
+
1254
+ market_overview = MarketOverview(
1255
+ sector_heatmap=sector_heatmap,
1256
+ top_gainers=top_gainers,
1257
+ top_losers=top_losers,
1258
+ anomaly_alerts=all_anomalies[:10],
1259
+ market_breadth={"buy": buy_count, "hold": hold_count, "sell": sell_count},
1260
+ )
1261
+
1262
+ report = AnalyticsReport(
1263
+ generated_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
1264
+ stocks_analyzed=len(results),
1265
+ stock_analyses=stock_analyses,
1266
+ market_overview=market_overview,
1267
+ clustering=clustering,
1268
+ correlation=correlation,
1269
+ buy_count=buy_count,
1270
+ sell_count=sell_count,
1271
+ hold_count=hold_count,
1272
+ anomaly_count=len(all_anomalies),
1273
+ )
1274
+
1275
+ _report_cache = (report, time.time())
1276
+ global _analysis_cache_ts
1277
+ _analysis_cache_ts = time.time()
1278
+ logger.info("Analytics report built: %d stocks, %d BUY, %d SELL, %d models cached",
1279
+ len(results), buy_count, sell_count, len(_rf_model_cache))
1280
+ return report
1281
+
1282
+
1283
+ def get_market_overview() -> MarketOverview:
1284
+ """
1285
+ Fast market overview — uses cached report or analysis cache.
1286
+ """
1287
+ cached, ts = _report_cache
1288
+ if cached is not None and time.time() - ts < REPORT_TTL:
1289
+ return cached.market_overview
1290
+
1291
+ # Use analysis cache if available (faster than recomputing)
1292
+ if _analysis_cache and time.time() - _analysis_cache_ts < REPORT_TTL:
1293
+ quick_results = list(_analysis_cache.values())
1294
+ else:
1295
+ quick_results = []
1296
+ for sym in get_stock_universe():
1297
+ try:
1298
+ df = _get_cached_df(sym, "1y")
1299
+ if df is None or df.empty:
1300
+ quick_results.append({"symbol": sym, "daily_change_pct": 0.0, "signals": None, "anomalies": []})
1301
+ continue
1302
+ prev = df.iloc[-2] if len(df) >= 2 else df.iloc[-1]
1303
+ chg = float((df.iloc[-1]["close"] - prev["close"]) / prev["close"] * 100) if prev["close"] > 0 else 0.0
1304
+ signals = compute_technical_signals(sym, df)
1305
+ anomalies = detect_anomalies(sym, df)
1306
+ quick_results.append({"symbol": sym, "daily_change_pct": chg, "signals": signals, "anomalies": anomalies})
1307
+ except Exception:
1308
+ pass
1309
+
1310
+ sector_data: dict[str, list[float]] = {}
1311
+ for r in quick_results:
1312
+ sec = get_stock_sector(r["symbol"])
1313
+ sector_data.setdefault(sec, []).append(r.get("daily_change_pct", 0.0))
1314
+
1315
+ sector_heatmap = [
1316
+ SectorHeatmapItem(sector=s, avg_change_pct=round(sum(v) / len(v), 2), stock_count=len(v))
1317
+ for s, v in sector_data.items()
1318
+ ]
1319
+
1320
+ by_chg = sorted(quick_results, key=lambda r: r.get("daily_change_pct", 0.0), reverse=True)
1321
+ top_gainers = [TrendingStock(symbol=r["symbol"], company_name=get_stock_name(r["symbol"]), change_pct=round(r.get("daily_change_pct", 0.0), 2)) for r in by_chg[:5]]
1322
+ top_losers = [TrendingStock(symbol=r["symbol"], company_name=get_stock_name(r["symbol"]), change_pct=round(r.get("daily_change_pct", 0.0), 2)) for r in by_chg[-5:]]
1323
+
1324
+ all_anomalies = [a for r in quick_results for a in r.get("anomalies", [])]
1325
+ buy = sum(1 for r in quick_results if r.get("signals") and r["signals"].composite_signal == SignalDirection.BUY)
1326
+ sell = sum(1 for r in quick_results if r.get("signals") and r["signals"].composite_signal == SignalDirection.SELL)
1327
+ hold = len(quick_results) - buy - sell
1328
+
1329
+ return MarketOverview(
1330
+ sector_heatmap=sector_heatmap,
1331
+ top_gainers=top_gainers,
1332
+ top_losers=top_losers,
1333
+ anomaly_alerts=all_anomalies[:10],
1334
+ market_breadth={"buy": buy, "hold": hold, "sell": sell},
1335
+ )
1336
+
1337
+
1338
+ # ── 12. Time-series forecasting ──────────────────────────────────────────────
1339
+
1340
+ def forecast_stock(symbol: str, horizon: int = 30) -> Optional[StockForecast]:
1341
+ """
1342
+ 30-day price forecast using exponential smoothing + linear trend.
1343
+ Returns ForecastPoints with confidence bands.
1344
+ """
1345
+ df = _get_cached_df(symbol, "2y")
1346
+ if df is None or len(df) < 120:
1347
+ return None
1348
+
1349
+ close = df["close"].values.astype(float)
1350
+ dates = pd.to_datetime(df["date"].values)
1351
+
1352
+ # --- Exponential smoothing (Holt's linear trend) ---
1353
+ alpha, beta_hl = 0.3, 0.1
1354
+ level = close[0]
1355
+ trend = 0.0
1356
+ for p in close[1:]:
1357
+ prev_level = level
1358
+ level = alpha * p + (1 - alpha) * (level + trend)
1359
+ trend = beta_hl * (level - prev_level) + (1 - beta_hl) * trend
1360
+
1361
+ # Generate forecast
1362
+ forecast_prices: list[float] = []
1363
+ for h in range(1, horizon + 1):
1364
+ forecast_prices.append(level + trend * h)
1365
+
1366
+ # Confidence bands based on recent residual volatility
1367
+ fitted = []
1368
+ l, t = close[0], 0.0
1369
+ for p in close[1:]:
1370
+ prev_l = l
1371
+ l = alpha * p + (1 - alpha) * (l + t)
1372
+ t = beta_hl * (l - prev_l) + (1 - beta_hl) * t
1373
+ fitted.append(l)
1374
+ residuals = close[1:] - np.array(fitted)
1375
+ sigma = float(np.std(residuals))
1376
+
1377
+ last_date = dates[-1]
1378
+ forecast_points: list[ForecastPoint] = []
1379
+ for h in range(1, horizon + 1):
1380
+ d = last_date + pd.Timedelta(days=h)
1381
+ band = 1.96 * sigma * np.sqrt(h)
1382
+ forecast_points.append(ForecastPoint(
1383
+ date=d.strftime("%Y-%m-%d"),
1384
+ price=round(forecast_prices[h - 1], 2),
1385
+ lower=round(forecast_prices[h - 1] - band, 2),
1386
+ upper=round(forecast_prices[h - 1] + band, 2),
1387
+ ))
1388
+
1389
+ current_price = float(close[-1])
1390
+ predicted_price = forecast_prices[-1]
1391
+ predicted_return = (predicted_price - current_price) / current_price * 100
1392
+
1393
+ # Trend classification
1394
+ if predicted_return > 3:
1395
+ trend_label = "BULLISH"
1396
+ elif predicted_return < -3:
1397
+ trend_label = "BEARISH"
1398
+ else:
1399
+ trend_label = "NEUTRAL"
1400
+
1401
+ # Confidence: based on R² of recent trend + volatility
1402
+ recent_60 = close[-60:]
1403
+ x_idx = np.arange(len(recent_60))
1404
+ corr_coef = np.corrcoef(x_idx, recent_60)[0, 1]
1405
+ r_squared = corr_coef ** 2
1406
+ vol_30 = float(np.std(np.diff(np.log(close[-30:]))) * np.sqrt(252) * 100)
1407
+ confidence = min(95, max(15, r_squared * 80 + (1 - min(vol_30, 60) / 60) * 20))
1408
+
1409
+ # Support / resistance from recent 90 days
1410
+ recent_90 = close[-90:]
1411
+ support = float(np.min(recent_90))
1412
+ resistance = float(np.max(recent_90))
1413
+
1414
+ return StockForecast(
1415
+ symbol=symbol,
1416
+ company_name=get_stock_name(symbol),
1417
+ sector=get_stock_sector(symbol),
1418
+ current_price=round(current_price, 2),
1419
+ forecast_30d=forecast_points,
1420
+ predicted_return_pct=round(predicted_return, 2),
1421
+ confidence=round(confidence, 1),
1422
+ trend=trend_label,
1423
+ support_level=round(support, 2),
1424
+ resistance_level=round(resistance, 2),
1425
+ volatility_30d=round(vol_30, 2),
1426
+ )
1427
+
1428
+
1429
+ # ── 13. Smart portfolio builder ──────────────────────────────────────────────
1430
+
1431
+ def build_smart_portfolio(
1432
+ risk_profile: str = "moderate",
1433
+ top_n: int = 15,
1434
+ n_portfolios: int = 2000,
1435
+ ) -> SmartPortfolioResponse:
1436
+ """
1437
+ Auto-select the best stocks, optimise the portfolio, then forecast each pick.
1438
+ Selection uses the cached analytics report (signals + risk + RF scores).
1439
+ """
1440
+ report = get_analytics_report(force_refresh=False)
1441
+ analyses = report.stock_analyses
1442
+
1443
+ # ── Score each stock for selection ──
1444
+ scored: list[tuple[float, StockAnalysis, str]] = []
1445
+ for a in analyses:
1446
+ # Composite selection score
1447
+ sig_score = a.technical_signals.composite_score # -6 to +6
1448
+ conf = a.technical_signals.confidence_score / 100 # 0-1
1449
+ sharpe = a.risk_metrics.sharpe_ratio
1450
+ rf_prob = a.rf_probability # 0-1, higher = more bullish
1451
+ vol = a.risk_metrics.volatility / 100 # annualised as decimal
1452
+
1453
+ # Risk-adjusted selection score
1454
+ selection = (
1455
+ sig_score * 2.0
1456
+ + conf * 3.0
1457
+ + sharpe * 2.0
1458
+ + (rf_prob - 0.5) * 6.0 # center on 0, scale up
1459
+ - vol * 3.0 # penalise high vol
1460
+ )
1461
+
1462
+ # Risk profile adjustments
1463
+ if risk_profile == "conservative":
1464
+ selection += (1 - vol) * 2 # reward low vol
1465
+ selection += min(sharpe, 2) * 1.5 # extra reward for good risk-adjusted returns
1466
+ reason = f"Sharpe {sharpe:.2f}, Vol {a.risk_metrics.volatility:.1f}%, Signal {a.technical_signals.composite_signal.value}"
1467
+ elif risk_profile == "aggressive":
1468
+ selection += sig_score * 1.5 # extra weight on momentum signals
1469
+ selection += rf_prob * 3 # extra weight on ML bullish probability
1470
+ reason = f"RF prob {rf_prob:.0%} up, Signal {sig_score:+.1f}, Confidence {conf:.0%}"
1471
+ else:
1472
+ reason = f"Score {sig_score:+.1f}, Sharpe {sharpe:.2f}, RF {rf_prob:.0%} bullish"
1473
+
1474
+ scored.append((selection, a, reason))
1475
+
1476
+ # Sort descending and pick top_n, ensuring sector diversity
1477
+ scored.sort(key=lambda x: x[0], reverse=True)
1478
+ selected: list[StockAnalysis] = []
1479
+ reasons: list[str] = []
1480
+ sector_count: dict[str, int] = {}
1481
+ max_per_sector = max(3, top_n // 4)
1482
+
1483
+ for score_val, analysis, reason in scored:
1484
+ sec = analysis.sector
1485
+ if sector_count.get(sec, 0) >= max_per_sector:
1486
+ continue
1487
+ selected.append(analysis)
1488
+ reasons.append(f"{get_stock_name(analysis.symbol).split(' ')[0]} — {reason}")
1489
+ sector_count[sec] = sector_count.get(sec, 0) + 1
1490
+ if len(selected) >= top_n:
1491
+ break
1492
+
1493
+ symbols = [a.symbol for a in selected]
1494
+
1495
+ # ── Optimise portfolio ──
1496
+ opt_result = optimize_portfolio(symbols, risk_profile, n_portfolios)
1497
+ if opt_result is None:
1498
+ # Fallback: equal weight
1499
+ from ..schemas.analytics import PortfolioOptimizationResult, PortfolioStats, EfficientFrontierPoint
1500
+ eq_w = {s: round(1.0 / len(symbols), 4) for s in symbols}
1501
+ opt_result = PortfolioOptimizationResult(
1502
+ symbols=symbols,
1503
+ min_variance_weights=eq_w,
1504
+ max_sharpe_weights=eq_w,
1505
+ risk_profile_weights=eq_w,
1506
+ risk_profile=risk_profile,
1507
+ efficient_frontier=[],
1508
+ correlation_matrix=[],
1509
+ mc_results=[],
1510
+ min_variance_stats=PortfolioStats(expected_return=0, volatility=0, sharpe=0),
1511
+ max_sharpe_stats=PortfolioStats(expected_return=0, volatility=0, sharpe=0),
1512
+ risk_profile_stats=PortfolioStats(expected_return=0, volatility=0, sharpe=0),
1513
+ )
1514
+
1515
+ # ── Forecast each selected stock ──
1516
+ forecasts: list[StockForecast] = []
1517
+ with ThreadPoolExecutor(max_workers=10) as pool:
1518
+ fmap = {pool.submit(forecast_stock, sym): sym for sym in symbols}
1519
+ for fut in as_completed(fmap):
1520
+ try:
1521
+ fc = fut.result()
1522
+ if fc is not None:
1523
+ forecasts.append(fc)
1524
+ except Exception as exc:
1525
+ logger.warning(f"Forecast failed for {fmap[fut]}: {exc}")
1526
+
1527
+ # Sort forecasts to match symbols order
1528
+ fc_map = {f.symbol: f for f in forecasts}
1529
+ forecasts = [fc_map[s] for s in symbols if s in fc_map]
1530
+
1531
+ # ── Aggregate portfolio-level metrics ──
1532
+ weights = opt_result.risk_profile_weights
1533
+ total_weight = sum(weights.get(s, 0) for s in symbols if s in fc_map)
1534
+
1535
+ portfolio_return = 0.0
1536
+ portfolio_risk = 0.0
1537
+ for fc in forecasts:
1538
+ w = weights.get(fc.symbol, 0)
1539
+ if total_weight > 0:
1540
+ w_norm = w / total_weight
1541
+ else:
1542
+ w_norm = 1.0 / len(forecasts)
1543
+ portfolio_return += fc.predicted_return_pct * w_norm
1544
+ portfolio_risk += fc.volatility_30d * w_norm
1545
+
1546
+ # Risk score: 0-100 (higher = riskier)
1547
+ risk_score = min(100, max(0, portfolio_risk * 1.5))
1548
+
1549
+ return SmartPortfolioResponse(
1550
+ selected_symbols=symbols,
1551
+ selection_reasoning=reasons,
1552
+ optimization=opt_result,
1553
+ forecasts=forecasts,
1554
+ portfolio_predicted_return=round(portfolio_return, 2),
1555
+ portfolio_risk_score=round(risk_score, 1),
1556
+ )
app/services/financial_engine.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core financial calculation engine.
3
+ Handles SIP calculations, investable surplus, and asset allocation.
4
+ """
5
+
6
+ from ..schemas.financial import RiskProfile, UserFinancialProfile
7
+
8
+ # Historical average annual returns for Indian markets (post-inflation adjusted)
9
+ RETURN_ASSUMPTIONS = {
10
+ RiskProfile.conservative: {
11
+ "expected": 9.0, # FDs + debt mutual funds + some equity
12
+ "std_dev": 4.0,
13
+ "allocation": {"Large Cap Equity": 20, "Debt Funds": 50, "Gold": 15, "Liquid Funds": 15},
14
+ },
15
+ RiskProfile.moderate: {
16
+ "expected": 12.0, # Diversified equity + debt mix
17
+ "std_dev": 8.0,
18
+ "allocation": {"Large Cap Equity": 40, "Mid Cap Equity": 15, "Debt Funds": 30, "Gold": 10, "Liquid Funds": 5},
19
+ },
20
+ RiskProfile.aggressive: {
21
+ "expected": 15.0, # Heavy equity, Nifty-like returns
22
+ "std_dev": 14.0,
23
+ "allocation": {"Large Cap Equity": 40, "Mid Cap Equity": 25, "Small Cap Equity": 20, "Debt Funds": 10, "Gold": 5},
24
+ },
25
+ }
26
+
27
+ # 50/30/20 rule - invest at least 20% of income
28
+ MINIMUM_INVESTMENT_RATIO = 0.20
29
+ RECOMMENDED_INVESTMENT_RATIO = 0.30
30
+
31
+
32
+ def calculate_investable_surplus(profile: UserFinancialProfile) -> float:
33
+ """Returns how much the user can invest monthly after expenses."""
34
+ surplus = profile.monthly_income - profile.monthly_expenses
35
+ return max(0.0, surplus)
36
+
37
+
38
+ def recommend_monthly_investment(profile: UserFinancialProfile) -> float:
39
+ """
40
+ Recommends a monthly SIP amount using the 30% rule,
41
+ capped by actual investable surplus.
42
+ """
43
+ surplus = calculate_investable_surplus(profile)
44
+ recommended = profile.monthly_income * RECOMMENDED_INVESTMENT_RATIO
45
+ # Don't suggest more than what they can afford
46
+ return min(recommended, surplus)
47
+
48
+
49
+ def get_return_assumptions(risk_profile: RiskProfile) -> dict:
50
+ return RETURN_ASSUMPTIONS[risk_profile]
51
+
52
+
53
+ def calculate_sip_future_value(
54
+ monthly_investment: float,
55
+ annual_return_pct: float,
56
+ years: int,
57
+ annual_stepup_pct: float = 0.0,
58
+ existing_corpus: float = 0.0,
59
+ ) -> float:
60
+ """
61
+ Calculates the future value of a SIP with optional step-up.
62
+ Formula: Standard SIP FV with yearly step-up compound.
63
+ """
64
+ monthly_return = annual_return_pct / 100 / 12
65
+ total_months = years * 12
66
+ fv = existing_corpus * ((1 + monthly_return) ** total_months)
67
+
68
+ current_sip = monthly_investment
69
+ for year in range(years):
70
+ year_fv = current_sip * (
71
+ ((1 + monthly_return) ** 12 - 1) / monthly_return
72
+ ) * (1 + monthly_return) ** ((years - year - 1) * 12)
73
+ fv += year_fv
74
+ current_sip *= (1 + annual_stepup_pct / 100)
75
+
76
+ return round(fv, 2)
77
+
78
+
79
+ def calculate_total_invested(
80
+ monthly_investment: float,
81
+ years: int,
82
+ annual_stepup_pct: float = 0.0,
83
+ ) -> float:
84
+ """Total principal invested over the period (accounting for step-up)."""
85
+ total = 0.0
86
+ current_sip = monthly_investment
87
+ for _ in range(years):
88
+ total += current_sip * 12
89
+ current_sip *= (1 + annual_stepup_pct / 100)
90
+ return round(total, 2)
91
+
92
+
93
+ def solve_required_sip(
94
+ target_amount: float,
95
+ annual_return_pct: float,
96
+ years: int,
97
+ annual_stepup_pct: float = 0.0,
98
+ existing_corpus: float = 0.0,
99
+ ) -> float:
100
+ """
101
+ Binary search to find the monthly SIP needed to reach target_amount.
102
+ Returns required monthly investment in INR.
103
+ """
104
+ # Subtract existing corpus growth from target
105
+ monthly_return = annual_return_pct / 100 / 12
106
+ total_months = years * 12
107
+ corpus_growth = existing_corpus * ((1 + monthly_return) ** total_months)
108
+ adjusted_target = max(0, target_amount - corpus_growth)
109
+
110
+ if adjusted_target <= 0:
111
+ return 0.0
112
+
113
+ lo, hi = 1.0, adjusted_target
114
+ for _ in range(100):
115
+ mid = (lo + hi) / 2
116
+ fv = calculate_sip_future_value(mid, annual_return_pct, years, annual_stepup_pct, 0)
117
+ if fv < adjusted_target:
118
+ lo = mid
119
+ else:
120
+ hi = mid
121
+ if abs(hi - lo) < 1:
122
+ break
123
+
124
+ return round((lo + hi) / 2, 2)
125
+
126
+
127
+ def build_sensitivity_table(
128
+ target_amount: float,
129
+ horizon_years: int,
130
+ annual_stepup_pct: float,
131
+ existing_corpus: float,
132
+ base_return_pct: float,
133
+ ) -> list[dict]:
134
+ """
135
+ Returns a sensitivity table showing required SIP at ±2%, ±4% return rates.
136
+ """
137
+ offsets = [-4, -2, 0, 2, 4]
138
+ rows = []
139
+ for offset in offsets:
140
+ rate = max(1.0, base_return_pct + offset)
141
+ required = solve_required_sip(target_amount, rate, horizon_years, annual_stepup_pct, existing_corpus)
142
+ rows.append({
143
+ "annual_return_pct": rate,
144
+ "required_monthly_sip": required,
145
+ "total_invested": calculate_total_invested(required, horizon_years, annual_stepup_pct),
146
+ })
147
+ return rows
app/services/macro.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Macro Dashboard — FII/DII proxy, India VIX, USD/INR, 10Y yield, Nifty 50.
3
+
4
+ Uses yfinance for market data. FII/DII flows approximated via ETF proxy.
5
+ Correlates macro indicators against Nifty 50 returns.
6
+ """
7
+
8
+ import time
9
+ import numpy as np
10
+ import pandas as pd
11
+ import yfinance as yf
12
+ from datetime import datetime, timezone
13
+
14
+ from ..schemas.advanced_analytics import (
15
+ MacroIndicator, MacroTimeSeries, MacroTimeSeriesPoint,
16
+ MacroCorrelation, MacroDashboardResponse,
17
+ )
18
+
19
+ _cache: tuple[MacroDashboardResponse | None, float] = (None, 0.0)
20
+ _CACHE_TTL = 1800 # 30 minutes
21
+
22
+
23
+ # Yahoo Finance tickers for Indian macro
24
+ MACRO_TICKERS = {
25
+ "India VIX": "^INDIAVIX",
26
+ "USD/INR": "INR=X",
27
+ "Nifty 50": "^NSEI",
28
+ "Gold (INR)": "GC=F",
29
+ "Crude Oil": "CL=F",
30
+ "Bank Nifty": "^NSEBANK",
31
+ }
32
+
33
+ DESCRIPTIONS = {
34
+ "India VIX": "Volatility index — fear gauge for Indian markets",
35
+ "USD/INR": "Dollar-Rupee exchange rate — rupee strength indicator",
36
+ "Nifty 50": "Benchmark Indian equity index — 50 large caps",
37
+ "Gold (INR)": "Gold futures — safe-haven proxy (USD, converted mentally)",
38
+ "Crude Oil": "WTI crude oil — import cost driver for India",
39
+ "Bank Nifty": "Banking sector index — financial sector health",
40
+ }
41
+
42
+
43
+ def _fetch_ticker_history(ticker: str, period: str = "1y") -> pd.DataFrame:
44
+ try:
45
+ data = yf.Ticker(ticker).history(period=period, interval="1d", auto_adjust=True)
46
+ if data.empty:
47
+ return pd.DataFrame()
48
+ data = data.reset_index()
49
+ data.rename(columns={"Date": "date", "Close": "close"}, inplace=True)
50
+ data["date"] = pd.to_datetime(data["date"]).dt.tz_localize(None)
51
+ return data[["date", "close"]].dropna()
52
+ except Exception:
53
+ return pd.DataFrame()
54
+
55
+
56
+ def _trend(change_pct: float) -> str:
57
+ if change_pct > 0.5:
58
+ return "UP"
59
+ elif change_pct < -0.5:
60
+ return "DOWN"
61
+ return "FLAT"
62
+
63
+
64
+ def _determine_regime(indicators: list[MacroIndicator]) -> tuple[str, str]:
65
+ """Determine market regime from macro indicators."""
66
+ vix_val = next((i for i in indicators if i.name == "India VIX"), None)
67
+ nifty = next((i for i in indicators if i.name == "Nifty 50"), None)
68
+ oil = next((i for i in indicators if i.name == "Crude Oil"), None)
69
+
70
+ risk_score = 0 # positive = risk-on, negative = risk-off
71
+
72
+ if vix_val:
73
+ if vix_val.value < 14:
74
+ risk_score += 2
75
+ elif vix_val.value < 18:
76
+ risk_score += 1
77
+ elif vix_val.value > 22:
78
+ risk_score -= 2
79
+ else:
80
+ risk_score -= 1
81
+
82
+ if nifty:
83
+ if nifty.change_pct > 2:
84
+ risk_score += 2
85
+ elif nifty.change_pct > 0:
86
+ risk_score += 1
87
+ elif nifty.change_pct < -2:
88
+ risk_score -= 2
89
+ else:
90
+ risk_score -= 1
91
+
92
+ if oil:
93
+ if oil.change_pct > 5:
94
+ risk_score -= 1 # rising oil = headwind for India
95
+
96
+ if risk_score >= 2:
97
+ return "RISK_ON", "Macro conditions favor equities — low VIX, positive market momentum. Consider increasing equity allocation."
98
+ elif risk_score <= -2:
99
+ return "RISK_OFF", "Elevated uncertainty — high VIX or falling markets. Consider defensive positioning with gold and debt."
100
+ return "NEUTRAL", "Mixed signals — VIX and market trends are not strongly directional. Maintain balanced allocation."
101
+
102
+
103
+ async def get_macro_dashboard(force: bool = False) -> MacroDashboardResponse:
104
+ global _cache
105
+ cached, ts = _cache
106
+ if cached and not force and time.time() - ts < _CACHE_TTL:
107
+ return cached
108
+
109
+ indicators: list[MacroIndicator] = []
110
+ all_series: list[MacroTimeSeries] = []
111
+ returns_dict: dict[str, pd.Series] = {}
112
+
113
+ for name, ticker in MACRO_TICKERS.items():
114
+ df = _fetch_ticker_history(ticker, "1y")
115
+ if df.empty or len(df) < 5:
116
+ continue
117
+
118
+ current = float(df["close"].iloc[-1])
119
+ prev_month = df["close"].iloc[-22] if len(df) > 22 else df["close"].iloc[0]
120
+ change_pct = float((current - prev_month) / prev_month * 100)
121
+
122
+ indicators.append(MacroIndicator(
123
+ name=name,
124
+ value=round(current, 2),
125
+ change_pct=round(change_pct, 2),
126
+ trend=_trend(change_pct),
127
+ description=DESCRIPTIONS.get(name, ""),
128
+ ))
129
+
130
+ # Time series data
131
+ ts_points = []
132
+ for _, row in df.iterrows():
133
+ ts_points.append(MacroTimeSeriesPoint(
134
+ date=row["date"].strftime("%Y-%m-%d"),
135
+ value=round(float(row["close"]), 2),
136
+ ))
137
+ all_series.append(MacroTimeSeries(name=name, data=ts_points))
138
+
139
+ # Store returns for correlation
140
+ ret = df.set_index("date")["close"].pct_change().dropna()
141
+ ret.name = name
142
+ returns_dict[name] = ret
143
+
144
+ # Correlations
145
+ correlations: list[MacroCorrelation] = []
146
+ names = list(returns_dict.keys())
147
+ if len(names) >= 2:
148
+ combined = pd.DataFrame(returns_dict)
149
+ combined = combined.dropna()
150
+ if len(combined) > 20:
151
+ corr_matrix = combined.corr()
152
+ for i, n1 in enumerate(names):
153
+ for j, n2 in enumerate(names):
154
+ if i < j:
155
+ c = float(corr_matrix.loc[n1, n2])
156
+ correlations.append(MacroCorrelation(
157
+ indicator1=n1, indicator2=n2,
158
+ correlation=round(c, 3),
159
+ ))
160
+
161
+ regime, desc = _determine_regime(indicators)
162
+
163
+ result = MacroDashboardResponse(
164
+ indicators=indicators,
165
+ time_series=all_series,
166
+ correlations=correlations,
167
+ market_regime=regime,
168
+ regime_description=desc,
169
+ generated_at=datetime.now(timezone.utc).isoformat(),
170
+ )
171
+ _cache = (result, time.time())
172
+ return result
app/services/monte_carlo.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Monte Carlo simulation engine for investment projections.
3
+ Runs N simulations with randomized annual returns drawn from a normal distribution.
4
+ """
5
+
6
+ import numpy as np
7
+ from ..schemas.financial import MonteCarloResult
8
+
9
+
10
+ def run_simulation(
11
+ monthly_investment: float,
12
+ annual_return_pct: float,
13
+ annual_std_dev_pct: float,
14
+ years: int,
15
+ annual_stepup_pct: float = 0.0,
16
+ existing_corpus: float = 0.0,
17
+ simulations: int = 1000,
18
+ seed: int = 42,
19
+ ) -> MonteCarloResult:
20
+ """
21
+ Runs Monte Carlo simulation for SIP investments.
22
+
23
+ Each simulation draws a random annual return (normal distribution) per year.
24
+ Returns percentile outcomes and year-by-year trajectory arrays.
25
+ """
26
+ rng = np.random.default_rng(seed)
27
+ final_values = np.zeros(simulations)
28
+
29
+ # Store yearly medians for trajectory chart
30
+ yearly_matrix = np.zeros((simulations, years))
31
+
32
+ for sim in range(simulations):
33
+ corpus = existing_corpus
34
+ current_sip = monthly_investment
35
+
36
+ # Draw annual returns for all years at once
37
+ annual_returns = rng.normal(
38
+ loc=annual_return_pct / 100,
39
+ scale=annual_std_dev_pct / 100,
40
+ size=years,
41
+ )
42
+
43
+ for year_idx, annual_r in enumerate(annual_returns):
44
+ monthly_r = annual_r / 12
45
+ for _ in range(12):
46
+ corpus = corpus * (1 + monthly_r) + current_sip
47
+ # Apply step-up at year end
48
+ current_sip *= (1 + annual_stepup_pct / 100)
49
+ yearly_matrix[sim, year_idx] = corpus
50
+
51
+ final_values[sim] = corpus
52
+
53
+ # Compute percentiles for final year
54
+ p10, p25, p50, p75, p90 = np.percentile(final_values, [10, 25, 50, 75, 90])
55
+
56
+ # Year-by-year percentile trajectories
57
+ yearly_expected = np.mean(yearly_matrix, axis=0).tolist()
58
+ yearly_p10 = np.percentile(yearly_matrix, 10, axis=0).tolist()
59
+ yearly_p90 = np.percentile(yearly_matrix, 90, axis=0).tolist()
60
+
61
+ probability_of_loss = float(np.mean(final_values < existing_corpus)) * 100
62
+
63
+ return MonteCarloResult(
64
+ percentile_10=round(float(p10), 2),
65
+ percentile_25=round(float(p25), 2),
66
+ percentile_50=round(float(p50), 2),
67
+ percentile_75=round(float(p75), 2),
68
+ percentile_90=round(float(p90), 2),
69
+ mean=round(float(np.mean(final_values)), 2),
70
+ std_dev=round(float(np.std(final_values)), 2),
71
+ probability_of_loss=round(probability_of_loss, 2),
72
+ yearly_expected=[round(v, 2) for v in yearly_expected],
73
+ yearly_p10=[round(v, 2) for v in yearly_p10],
74
+ yearly_p90=[round(v, 2) for v in yearly_p90],
75
+ )
app/services/news_sentiment.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ News Sentiment Analysis service.
3
+
4
+ Fetches financial headlines from Google News RSS (free, no API key),
5
+ scores sentiment using a keyword-based approach, and aggregates by stock.
6
+ """
7
+
8
+ import re
9
+ import time
10
+ import xml.etree.ElementTree as ET
11
+ from datetime import datetime, timezone
12
+ from urllib.parse import quote
13
+
14
+ import httpx
15
+
16
+ from .analytics import get_stock_universe, get_stock_name, get_stock_sector
17
+ from ..schemas.portfolio import (
18
+ NewsArticle, SentimentSummary, NewsSentimentResponse,
19
+ )
20
+
21
+ _cache: tuple[NewsSentimentResponse | None, float] = (None, 0.0)
22
+ _CACHE_TTL = 1800 # 30 minutes
23
+
24
+ # ── Sentiment keyword lists ──────────────────────────────────────────────────
25
+
26
+ POSITIVE_WORDS = {
27
+ "surge", "surges", "surging", "rally", "rallies", "rallied", "gain", "gains",
28
+ "jump", "jumps", "jumped", "rise", "rises", "rose", "soar", "soars",
29
+ "bullish", "upgrade", "upgraded", "outperform", "buy", "growth", "profit",
30
+ "profitable", "positive", "boost", "boosted", "record", "high", "strong",
31
+ "strength", "recovery", "recover", "recovered", "beat", "beats", "exceeds",
32
+ "dividend", "bonus", "breakout", "uptick", "uptrend", "optimistic",
33
+ "momentum", "expand", "expansion", "robust",
34
+ }
35
+
36
+ NEGATIVE_WORDS = {
37
+ "crash", "crashes", "crashed", "fall", "falls", "fell", "drop", "drops",
38
+ "dropped", "plunge", "plunges", "plunged", "decline", "declines", "declined",
39
+ "bearish", "downgrade", "downgraded", "sell", "loss", "losses", "negative",
40
+ "weak", "weakness", "slump", "slumps", "slumped", "cut", "cuts",
41
+ "concern", "risk", "risky", "warning", "warn", "warns", "crisis",
42
+ "default", "fraud", "scam", "penalty", "fine", "fined", "debt",
43
+ "downturn", "recession", "volatility", "correction", "tank", "tanks",
44
+ "underperform", "miss", "misses", "missed", "disappointing",
45
+ }
46
+
47
+ # Top Indian stocks to track news for
48
+ TOP_SYMBOLS = [
49
+ "RELIANCE", "TCS", "HDFCBANK", "INFY", "ICICIBANK",
50
+ "HINDUNILVR", "ITC", "SBIN", "BHARTIARTL", "KOTAKBANK",
51
+ "LT", "AXISBANK", "BAJFINANCE", "MARUTI", "TITAN",
52
+ "SUNPHARMA", "TATAMOTORS", "WIPRO", "ADANIENT", "HCLTECH",
53
+ "NTPC", "POWERGRID", "ONGC", "TATASTEEL", "JSWSTEEL",
54
+ ]
55
+
56
+ SYMBOL_ALIASES = {
57
+ "RELIANCE": ["reliance", "reliance industries", "ril"],
58
+ "TCS": ["tcs", "tata consultancy"],
59
+ "HDFCBANK": ["hdfc bank", "hdfc"],
60
+ "INFY": ["infosys", "infy"],
61
+ "ICICIBANK": ["icici bank", "icici"],
62
+ "HINDUNILVR": ["hindustan unilever", "hul"],
63
+ "ITC": ["itc"],
64
+ "SBIN": ["sbi", "state bank"],
65
+ "BHARTIARTL": ["bharti airtel", "airtel"],
66
+ "KOTAKBANK": ["kotak", "kotak mahindra"],
67
+ "LT": ["larsen", "l&t"],
68
+ "AXISBANK": ["axis bank"],
69
+ "BAJFINANCE": ["bajaj finance", "bajaj finserv"],
70
+ "MARUTI": ["maruti", "maruti suzuki"],
71
+ "TITAN": ["titan"],
72
+ "SUNPHARMA": ["sun pharma", "sun pharmaceutical"],
73
+ "TATAMOTORS": ["tata motors"],
74
+ "WIPRO": ["wipro"],
75
+ "ADANIENT": ["adani", "adani enterprises"],
76
+ "HCLTECH": ["hcl tech", "hcl technologies"],
77
+ "NTPC": ["ntpc"],
78
+ "POWERGRID": ["power grid"],
79
+ "ONGC": ["ongc"],
80
+ "TATASTEEL": ["tata steel"],
81
+ "JSWSTEEL": ["jsw steel", "jsw"],
82
+ }
83
+
84
+
85
+ def _score_sentiment(text: str) -> tuple[str, float]:
86
+ """Score sentiment of a text using keyword matching. Returns (label, score)."""
87
+ words = set(re.findall(r'[a-z]+', text.lower()))
88
+ pos = len(words & POSITIVE_WORDS)
89
+ neg = len(words & NEGATIVE_WORDS)
90
+
91
+ if pos == 0 and neg == 0:
92
+ return "NEUTRAL", 0.0
93
+
94
+ total = pos + neg
95
+ score = (pos - neg) / total # -1.0 to 1.0
96
+
97
+ if score > 0.15:
98
+ return "POSITIVE", round(score, 3)
99
+ elif score < -0.15:
100
+ return "NEGATIVE", round(score, 3)
101
+ return "NEUTRAL", round(score, 3)
102
+
103
+
104
+ def _match_symbols(text: str) -> list[str]:
105
+ """Match stock symbols mentioned in text."""
106
+ text_lower = text.lower()
107
+ matched = []
108
+ for sym, aliases in SYMBOL_ALIASES.items():
109
+ for alias in aliases:
110
+ if alias in text_lower:
111
+ matched.append(sym)
112
+ break
113
+ return matched
114
+
115
+
116
+ def _fetch_google_news_rss(query: str, num: int = 15) -> list[dict]:
117
+ """Fetch news from Google News RSS (free, no API key)."""
118
+ url = f"https://news.google.com/rss/search?q={quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
119
+ try:
120
+ resp = httpx.get(url, timeout=10, follow_redirects=True)
121
+ if resp.status_code != 200:
122
+ return []
123
+
124
+ root = ET.fromstring(resp.content)
125
+ items = root.findall(".//item")
126
+ articles = []
127
+
128
+ for item in items[:num]:
129
+ title = item.findtext("title", "")
130
+ source = item.findtext("source", "Unknown")
131
+ link = item.findtext("link", "")
132
+ pub_date = item.findtext("pubDate", "")
133
+
134
+ if title:
135
+ articles.append({
136
+ "title": title,
137
+ "source": source,
138
+ "url": link,
139
+ "published_at": pub_date,
140
+ })
141
+ return articles
142
+ except Exception:
143
+ return []
144
+
145
+
146
+ async def get_news_sentiment(force: bool = False) -> NewsSentimentResponse:
147
+ global _cache
148
+ cached, ts = _cache
149
+ if cached and not force and time.time() - ts < _CACHE_TTL:
150
+ return cached
151
+
152
+ all_articles: list[NewsArticle] = []
153
+ seen_titles: set[str] = set()
154
+
155
+ # Fetch news for Indian stock market + individual top stocks
156
+ queries = [
157
+ "Indian stock market Nifty BSE NSE",
158
+ "Nifty 50 Sensex today",
159
+ "Indian stocks earnings results",
160
+ ]
161
+ # Add top 10 stocks individually
162
+ for sym in TOP_SYMBOLS[:10]:
163
+ aliases = SYMBOL_ALIASES.get(sym, [sym.lower()])
164
+ queries.append(f"{aliases[0]} stock NSE")
165
+
166
+ for query in queries:
167
+ raw_articles = _fetch_google_news_rss(query, num=10)
168
+ for art in raw_articles:
169
+ title = art["title"]
170
+ if title in seen_titles:
171
+ continue
172
+ seen_titles.add(title)
173
+
174
+ sentiment, score = _score_sentiment(title)
175
+ symbols = _match_symbols(title)
176
+
177
+ all_articles.append(NewsArticle(
178
+ title=title,
179
+ source=art["source"],
180
+ url=art["url"],
181
+ published_at=art["published_at"],
182
+ sentiment=sentiment,
183
+ sentiment_score=score,
184
+ symbols=symbols,
185
+ ))
186
+
187
+ # Sort by recency (most recent first)
188
+ all_articles.sort(key=lambda a: a.published_at, reverse=True)
189
+
190
+ # Limit to 50 articles
191
+ all_articles = all_articles[:50]
192
+
193
+ # Build per-symbol sentiment summaries
194
+ sym_articles: dict[str, list[NewsArticle]] = {}
195
+ for art in all_articles:
196
+ for sym in art.symbols:
197
+ sym_articles.setdefault(sym, []).append(art)
198
+
199
+ summaries: list[SentimentSummary] = []
200
+ for sym in TOP_SYMBOLS:
201
+ arts = sym_articles.get(sym, [])
202
+ if not arts:
203
+ continue
204
+
205
+ pos = sum(1 for a in arts if a.sentiment == "POSITIVE")
206
+ neg = sum(1 for a in arts if a.sentiment == "NEGATIVE")
207
+ neu = sum(1 for a in arts if a.sentiment == "NEUTRAL")
208
+ avg_score = sum(a.sentiment_score for a in arts) / len(arts)
209
+
210
+ label = "BULLISH" if avg_score > 0.1 else "BEARISH" if avg_score < -0.1 else "NEUTRAL"
211
+
212
+ name = get_stock_name(f"{sym}.NS") or sym
213
+ summaries.append(SentimentSummary(
214
+ symbol=sym,
215
+ company_name=name,
216
+ article_count=len(arts),
217
+ avg_sentiment=round(avg_score, 3),
218
+ positive_count=pos,
219
+ negative_count=neg,
220
+ neutral_count=neu,
221
+ sentiment_label=label,
222
+ ))
223
+
224
+ # Sort by article count (most mentioned first)
225
+ summaries.sort(key=lambda s: s.article_count, reverse=True)
226
+
227
+ # Overall sentiment
228
+ if all_articles:
229
+ overall_score = sum(a.sentiment_score for a in all_articles) / len(all_articles)
230
+ else:
231
+ overall_score = 0.0
232
+ overall = "BULLISH" if overall_score > 0.1 else "BEARISH" if overall_score < -0.1 else "NEUTRAL"
233
+
234
+ result = NewsSentimentResponse(
235
+ articles=all_articles,
236
+ summaries=summaries,
237
+ overall_sentiment=overall,
238
+ overall_score=round(overall_score, 3),
239
+ generated_at=datetime.now(timezone.utc).isoformat(),
240
+ )
241
+ _cache = (result, time.time())
242
+ return result
app/services/portfolio.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Watchlist & Portfolio Tracker service.
3
+
4
+ CRUD operations on Supabase watchlist + portfolio_holdings tables,
5
+ enriched with live prices from the analytics cache.
6
+ """
7
+
8
+ import httpx
9
+ from datetime import datetime, timezone, date
10
+
11
+ from ..core.config import get_settings
12
+ from ..core.database import get_db
13
+ from ..schemas.portfolio import (
14
+ WatchlistItem, WatchlistResponse, WatchlistAddRequest,
15
+ HoldingInput, PortfolioHolding, PortfolioSummary, PortfolioResponse,
16
+ )
17
+
18
+ USER_ID = "default" # single-user for now
19
+
20
+
21
+ def _sb_headers(prefer: str = "return=representation"):
22
+ key = get_settings().supabase_service_role_key
23
+ return {
24
+ "apikey": key,
25
+ "Authorization": f"Bearer {key}",
26
+ "Content-Type": "application/json",
27
+ "Prefer": prefer,
28
+ }
29
+
30
+
31
+ def _sb_url(table: str) -> str:
32
+ return f"{get_settings().supabase_url}/rest/v1/{table}"
33
+
34
+
35
+ def _get_latest_price(symbol: str) -> tuple[float, float]:
36
+ """Return (current_price, daily_change_pct) from cache or Supabase."""
37
+ try:
38
+ from .analytics import _get_cached_df
39
+ df = _get_cached_df(f"{symbol}.NS" if not symbol.endswith(".NS") else symbol, "1y")
40
+ if df is not None and len(df) >= 2:
41
+ current = float(df["close"].iloc[-1])
42
+ prev = float(df["close"].iloc[-2])
43
+ change = (current - prev) / prev * 100 if prev > 0 else 0
44
+ return current, round(change, 2)
45
+ except Exception:
46
+ pass
47
+
48
+ # Fallback: fetch from Supabase stock_prices
49
+ try:
50
+ db_sym = symbol.replace(".NS", "")
51
+ resp = httpx.get(
52
+ _sb_url("stock_prices"),
53
+ headers=_sb_headers(""),
54
+ params={
55
+ "symbol": f"eq.{db_sym}",
56
+ "select": "close",
57
+ "order": "date.desc",
58
+ "limit": "2",
59
+ },
60
+ timeout=10,
61
+ )
62
+ rows = resp.json()
63
+ if len(rows) >= 2:
64
+ current = float(rows[0]["close"])
65
+ prev = float(rows[1]["close"])
66
+ change = (current - prev) / prev * 100 if prev > 0 else 0
67
+ return current, round(change, 2)
68
+ elif len(rows) == 1:
69
+ return float(rows[0]["close"]), 0.0
70
+ except Exception:
71
+ pass
72
+ return 0.0, 0.0
73
+
74
+
75
+ def _get_stock_meta(symbol: str) -> tuple[str, str]:
76
+ """Return (company_name, sector) from cache or Supabase."""
77
+ try:
78
+ from .analytics import get_stock_name, get_stock_sector
79
+ yf_sym = f"{symbol}.NS" if not symbol.endswith(".NS") else symbol
80
+ name = get_stock_name(yf_sym)
81
+ sector = get_stock_sector(yf_sym)
82
+ if name:
83
+ return name, sector
84
+ except Exception:
85
+ pass
86
+
87
+ try:
88
+ db_sym = symbol.replace(".NS", "")
89
+ db = get_db()
90
+ result = db.table("stocks").select("company_name,sector").eq("symbol", db_sym).limit(1).execute()
91
+ if result.data:
92
+ return result.data[0].get("company_name", ""), result.data[0].get("sector", "")
93
+ except Exception:
94
+ pass
95
+ return "", ""
96
+
97
+
98
+ # ── Watchlist CRUD ───────────────────────────────────────────────────────────
99
+
100
+ async def get_watchlist() -> WatchlistResponse:
101
+ resp = httpx.get(
102
+ _sb_url("watchlist"),
103
+ headers=_sb_headers(""),
104
+ params={
105
+ "user_id": f"eq.{USER_ID}",
106
+ "select": "id,symbol,added_at,notes",
107
+ "order": "added_at.desc",
108
+ },
109
+ timeout=10,
110
+ )
111
+ resp.raise_for_status()
112
+ rows = resp.json()
113
+
114
+ items: list[WatchlistItem] = []
115
+ for row in rows:
116
+ sym = row["symbol"]
117
+ price, change = _get_latest_price(sym)
118
+ name, sector = _get_stock_meta(sym)
119
+ items.append(WatchlistItem(
120
+ id=row["id"],
121
+ symbol=sym,
122
+ company_name=name,
123
+ sector=sector,
124
+ current_price=round(price, 2),
125
+ daily_change_pct=change,
126
+ added_at=row["added_at"],
127
+ notes=row.get("notes"),
128
+ ))
129
+
130
+ return WatchlistResponse(items=items, total=len(items))
131
+
132
+
133
+ async def add_to_watchlist(req: WatchlistAddRequest) -> WatchlistItem:
134
+ sym = req.symbol.upper().replace(".NS", "")
135
+ resp = httpx.post(
136
+ _sb_url("watchlist"),
137
+ headers=_sb_headers("return=representation"),
138
+ json={"user_id": USER_ID, "symbol": sym, "notes": req.notes},
139
+ timeout=10,
140
+ )
141
+ resp.raise_for_status()
142
+ row = resp.json()[0]
143
+ price, change = _get_latest_price(sym)
144
+ name, sector = _get_stock_meta(sym)
145
+ return WatchlistItem(
146
+ id=row["id"], symbol=sym, company_name=name, sector=sector,
147
+ current_price=round(price, 2), daily_change_pct=change,
148
+ added_at=row["added_at"], notes=row.get("notes"),
149
+ )
150
+
151
+
152
+ async def remove_from_watchlist(item_id: int) -> bool:
153
+ resp = httpx.delete(
154
+ _sb_url("watchlist"),
155
+ headers=_sb_headers(""),
156
+ params={"id": f"eq.{item_id}", "user_id": f"eq.{USER_ID}"},
157
+ timeout=10,
158
+ )
159
+ return resp.status_code in (200, 204)
160
+
161
+
162
+ # ── Portfolio CRUD ───────────────────────────────────────────────────────────
163
+
164
+ async def get_portfolio() -> PortfolioResponse:
165
+ resp = httpx.get(
166
+ _sb_url("portfolio_holdings"),
167
+ headers=_sb_headers(""),
168
+ params={
169
+ "user_id": f"eq.{USER_ID}",
170
+ "select": "id,symbol,quantity,buy_price,buy_date,notes,created_at",
171
+ "order": "created_at.desc",
172
+ },
173
+ timeout=10,
174
+ )
175
+ resp.raise_for_status()
176
+ rows = resp.json()
177
+
178
+ holdings: list[PortfolioHolding] = []
179
+ total_invested = 0.0
180
+ total_market = 0.0
181
+ best: tuple[str, float] = ("", -999)
182
+ worst: tuple[str, float] = ("", 999)
183
+
184
+ for row in rows:
185
+ sym = row["symbol"]
186
+ qty = float(row["quantity"])
187
+ buy_px = float(row["buy_price"])
188
+ price, change = _get_latest_price(sym)
189
+ name, sector = _get_stock_meta(sym)
190
+
191
+ invested = buy_px * qty
192
+ market = price * qty
193
+ pnl = market - invested
194
+ pnl_pct = (pnl / invested * 100) if invested > 0 else 0
195
+
196
+ total_invested += invested
197
+ total_market += market
198
+
199
+ if pnl_pct > best[1]:
200
+ best = (sym, pnl_pct)
201
+ if pnl_pct < worst[1]:
202
+ worst = (sym, pnl_pct)
203
+
204
+ holdings.append(PortfolioHolding(
205
+ id=row["id"], symbol=sym, company_name=name, sector=sector,
206
+ quantity=qty, buy_price=buy_px,
207
+ buy_date=str(row["buy_date"]),
208
+ current_price=round(price, 2), daily_change_pct=change,
209
+ pnl=round(pnl, 2), pnl_pct=round(pnl_pct, 2),
210
+ market_value=round(market, 2), invested_value=round(invested, 2),
211
+ notes=row.get("notes"),
212
+ ))
213
+
214
+ total_pnl = total_market - total_invested
215
+ total_pnl_pct = (total_pnl / total_invested * 100) if total_invested > 0 else 0
216
+
217
+ summary = PortfolioSummary(
218
+ total_invested=round(total_invested, 2),
219
+ total_market_value=round(total_market, 2),
220
+ total_pnl=round(total_pnl, 2),
221
+ total_pnl_pct=round(total_pnl_pct, 2),
222
+ holdings_count=len(holdings),
223
+ best_performer=best[0] if best[0] else None,
224
+ worst_performer=worst[0] if worst[0] else None,
225
+ )
226
+
227
+ return PortfolioResponse(holdings=holdings, summary=summary)
228
+
229
+
230
+ async def add_holding(req: HoldingInput) -> PortfolioHolding:
231
+ sym = req.symbol.upper().replace(".NS", "")
232
+ buy_date = req.buy_date if req.buy_date else str(date.today())
233
+
234
+ resp = httpx.post(
235
+ _sb_url("portfolio_holdings"),
236
+ headers=_sb_headers("return=representation"),
237
+ json={
238
+ "user_id": USER_ID,
239
+ "symbol": sym,
240
+ "quantity": req.quantity,
241
+ "buy_price": req.buy_price,
242
+ "buy_date": buy_date,
243
+ "notes": req.notes,
244
+ },
245
+ timeout=10,
246
+ )
247
+ resp.raise_for_status()
248
+ row = resp.json()[0]
249
+
250
+ price, change = _get_latest_price(sym)
251
+ name, sector = _get_stock_meta(sym)
252
+ invested = req.buy_price * req.quantity
253
+ market = price * req.quantity
254
+ pnl = market - invested
255
+
256
+ return PortfolioHolding(
257
+ id=row["id"], symbol=sym, company_name=name, sector=sector,
258
+ quantity=req.quantity, buy_price=req.buy_price, buy_date=buy_date,
259
+ current_price=round(price, 2), daily_change_pct=change,
260
+ pnl=round(pnl, 2), pnl_pct=round(pnl / invested * 100 if invested > 0 else 0, 2),
261
+ market_value=round(market, 2), invested_value=round(invested, 2),
262
+ notes=req.notes,
263
+ )
264
+
265
+
266
+ async def remove_holding(holding_id: int) -> bool:
267
+ resp = httpx.delete(
268
+ _sb_url("portfolio_holdings"),
269
+ headers=_sb_headers(""),
270
+ params={"id": f"eq.{holding_id}", "user_id": f"eq.{USER_ID}"},
271
+ timeout=10,
272
+ )
273
+ return resp.status_code in (200, 204)
app/services/risk_factors.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Risk Factor Decomposition — Fama-French-style factor analysis.
3
+
4
+ Constructs Market, Size, Value, Momentum factors from the stock universe
5
+ and regresses individual stock returns against them.
6
+ """
7
+
8
+ import time
9
+ import numpy as np
10
+ import pandas as pd
11
+ from datetime import datetime, timezone
12
+
13
+ from .analytics import (
14
+ get_stock_universe, _get_cached_df, get_stock_name, get_stock_sector,
15
+ NIFTY_INDEX, RISK_FREE_RATE,
16
+ )
17
+ from ..schemas.advanced_analytics import (
18
+ FactorExposure, FactorTimeSeries, StockFactorResult,
19
+ RiskFactorResponse,
20
+ )
21
+
22
+ _factor_cache: tuple[pd.DataFrame | None, float] = (None, 0.0)
23
+ _CACHE_TTL = 3600
24
+
25
+
26
+ FACTOR_DESCRIPTIONS = {
27
+ "Market": "Excess return of Nifty 50 over risk-free rate. Captures systematic equity risk.",
28
+ "Size": "Small-cap minus large-cap returns. Positive exposure = tilts toward smaller companies.",
29
+ "Value": "High book-yield minus low book-yield proxy (low-price vs high-price stocks). Positive = value tilt.",
30
+ "Momentum": "Past winners minus past losers (6-month return). Positive = trend-following exposure.",
31
+ }
32
+
33
+
34
+ def _build_factor_returns() -> pd.DataFrame:
35
+ """Construct daily factor returns from the stock universe."""
36
+ global _factor_cache
37
+ cached, ts = _factor_cache
38
+ if cached is not None and time.time() - ts < _CACHE_TTL:
39
+ return cached
40
+
41
+ universe = get_stock_universe()
42
+ nifty_df = _get_cached_df(NIFTY_INDEX, "2y")
43
+
44
+ if nifty_df is None or len(nifty_df) < 200:
45
+ raise ValueError("Cannot build factors: Nifty 50 data unavailable")
46
+
47
+ # Collect daily returns for all stocks
48
+ stock_returns: dict[str, pd.Series] = {}
49
+ stock_meta: dict[str, dict] = {} # price level, 6m return for sorting
50
+
51
+ for sym in universe:
52
+ df = _get_cached_df(sym, "2y")
53
+ if df is None or len(df) < 200:
54
+ continue
55
+ ret = df.set_index("date")["close"].pct_change().dropna()
56
+ if len(ret) < 200:
57
+ continue
58
+ stock_returns[sym] = ret
59
+
60
+ # Metadata for factor construction
61
+ close_vals = df["close"].values
62
+ price = float(close_vals[-1])
63
+ mom_6m = float((close_vals[-1] / close_vals[-126] - 1) * 100) if len(close_vals) > 126 else 0.0
64
+ stock_meta[sym] = {"price": price, "momentum_6m": mom_6m}
65
+
66
+ if len(stock_returns) < 20:
67
+ raise ValueError("Too few stocks with sufficient data for factor construction")
68
+
69
+ # Align all returns to common date index
70
+ all_ret = pd.DataFrame(stock_returns)
71
+ all_ret = all_ret.dropna(axis=1, thresh=int(len(all_ret) * 0.7)) # drop stocks with >30% missing
72
+ all_ret = all_ret.fillna(0)
73
+ syms = list(all_ret.columns)
74
+
75
+ # ── Market Factor ──
76
+ nifty_ret = nifty_df.set_index("date")["close"].pct_change().dropna()
77
+ rf_daily = RISK_FREE_RATE / 252
78
+ market_factor = nifty_ret - rf_daily
79
+
80
+ # ── Size Factor (Small minus Big) ──
81
+ prices = {s: stock_meta[s]["price"] for s in syms if s in stock_meta}
82
+ median_price = np.median(list(prices.values())) if prices else 1000
83
+ small = [s for s in syms if s in prices and prices[s] < median_price]
84
+ big = [s for s in syms if s in prices and prices[s] >= median_price]
85
+ smb = all_ret[small].mean(axis=1) - all_ret[big].mean(axis=1) if small and big else pd.Series(0, index=all_ret.index)
86
+
87
+ # ── Value Factor (proxy: low-price minus high-price, rebalanced) ──
88
+ sorted_by_price = sorted(prices.items(), key=lambda x: x[1])
89
+ n = len(sorted_by_price)
90
+ value_stocks = [s for s, _ in sorted_by_price[:n // 3]]
91
+ growth_stocks = [s for s, _ in sorted_by_price[-(n // 3):]]
92
+ hml = all_ret[value_stocks].mean(axis=1) - all_ret[growth_stocks].mean(axis=1) if value_stocks and growth_stocks else pd.Series(0, index=all_ret.index)
93
+
94
+ # ── Momentum Factor (Winners minus Losers on 6M return) ──
95
+ mom_data = {s: stock_meta[s]["momentum_6m"] for s in syms if s in stock_meta}
96
+ sorted_by_mom = sorted(mom_data.items(), key=lambda x: x[1], reverse=True)
97
+ n_mom = len(sorted_by_mom)
98
+ winners = [s for s, _ in sorted_by_mom[:n_mom // 3]]
99
+ losers = [s for s, _ in sorted_by_mom[-(n_mom // 3):]]
100
+ wml = all_ret[winners].mean(axis=1) - all_ret[losers].mean(axis=1) if winners and losers else pd.Series(0, index=all_ret.index)
101
+
102
+ # Combine into factor DataFrame
103
+ factors = pd.DataFrame({
104
+ "Market": market_factor,
105
+ "Size": smb,
106
+ "Value": hml,
107
+ "Momentum": wml,
108
+ }).dropna()
109
+
110
+ _factor_cache = (factors, time.time())
111
+ return factors
112
+
113
+
114
+ def _regress_stock(stock_ret: pd.Series, factors: pd.DataFrame) -> StockFactorResult | None:
115
+ """OLS regression of stock returns on factor returns."""
116
+ from scipy import stats as sp_stats
117
+
118
+ common_idx = stock_ret.index.intersection(factors.index)
119
+ if len(common_idx) < 60:
120
+ return None
121
+
122
+ y = stock_ret.loc[common_idx].values
123
+ X = factors.loc[common_idx].values
124
+ # Add constant (intercept = alpha)
125
+ X_with_const = np.column_stack([np.ones(len(X)), X])
126
+
127
+ try:
128
+ # OLS via numpy
129
+ betas, residuals, _, _ = np.linalg.lstsq(X_with_const, y, rcond=None)
130
+ y_hat = X_with_const @ betas
131
+ resid = y - y_hat
132
+
133
+ n, k = X_with_const.shape
134
+ ss_res = float(np.sum(resid ** 2))
135
+ ss_tot = float(np.sum((y - y.mean()) ** 2))
136
+ r_squared = 1 - ss_res / ss_tot if ss_tot > 0 else 0
137
+
138
+ # Standard errors
139
+ mse = ss_res / (n - k) if n > k else 1e-10
140
+ var_beta = mse * np.linalg.inv(X_with_const.T @ X_with_const).diagonal()
141
+ se = np.sqrt(np.maximum(var_beta, 1e-12))
142
+ t_stats = betas / se
143
+ p_values = [float(2 * (1 - sp_stats.t.cdf(abs(t), df=n - k))) for t in t_stats]
144
+
145
+ alpha = float(betas[0]) * 252 * 100 # annualized alpha in %
146
+ alpha_t = float(t_stats[0])
147
+
148
+ factor_names = list(factors.columns)
149
+ exposures = []
150
+ total_var_explained = max(ss_tot - ss_res, 0)
151
+
152
+ for i, fname in enumerate(factor_names):
153
+ beta_i = float(betas[i + 1])
154
+ # Factor contribution approximation
155
+ factor_var_contribution = abs(beta_i) * float(np.std(factors[fname])) * np.sqrt(252) * 100
156
+ contribution_pct = (factor_var_contribution / (total_var_explained ** 0.5 * 100 + 1e-6)) * 100
157
+
158
+ exposures.append(FactorExposure(
159
+ factor=fname,
160
+ beta=round(beta_i, 4),
161
+ t_stat=round(float(t_stats[i + 1]), 2),
162
+ p_value=round(p_values[i + 1], 4),
163
+ contribution_pct=round(min(contribution_pct, 100), 1),
164
+ ))
165
+
166
+ residual_vol = float(np.std(resid) * np.sqrt(252) * 100)
167
+ dominant = max(exposures, key=lambda e: abs(e.beta))
168
+
169
+ return {
170
+ "factor_exposures": exposures,
171
+ "r_squared": round(r_squared, 4),
172
+ "alpha": round(alpha, 2),
173
+ "alpha_t_stat": round(alpha_t, 2),
174
+ "residual_vol": round(residual_vol, 2),
175
+ "dominant_factor": dominant.factor,
176
+ }
177
+ except Exception:
178
+ return None
179
+
180
+
181
+ async def get_risk_factors(symbols: list[str]) -> RiskFactorResponse:
182
+ factors = _build_factor_returns()
183
+
184
+ results: list[StockFactorResult] = []
185
+ for sym in symbols:
186
+ yf_sym = sym if sym.endswith(".NS") else f"{sym}.NS"
187
+ df = _get_cached_df(yf_sym, "2y")
188
+ if df is None or len(df) < 200:
189
+ continue
190
+
191
+ stock_ret = df.set_index("date")["close"].pct_change().dropna()
192
+ reg = _regress_stock(stock_ret, factors)
193
+ if reg is None:
194
+ continue
195
+
196
+ results.append(StockFactorResult(
197
+ symbol=sym,
198
+ company_name=get_stock_name(yf_sym),
199
+ sector=get_stock_sector(yf_sym),
200
+ **reg,
201
+ ))
202
+
203
+ # Factor return history (monthly)
204
+ factor_ts: list[FactorTimeSeries] = []
205
+ monthly = factors.resample("ME").sum() * 100 # cumulative monthly in %
206
+ for dt, row in monthly.tail(12).iterrows():
207
+ factor_ts.append(FactorTimeSeries(
208
+ date=pd.Timestamp(dt).strftime("%Y-%m-%d"),
209
+ market=round(float(row["Market"]), 2),
210
+ size=round(float(row["Size"]), 2),
211
+ value=round(float(row["Value"]), 2),
212
+ momentum=round(float(row["Momentum"]), 2),
213
+ ))
214
+
215
+ return RiskFactorResponse(
216
+ stocks=results,
217
+ factor_returns=factor_ts,
218
+ factor_descriptions=FACTOR_DESCRIPTIONS,
219
+ generated_at=datetime.now(timezone.utc).isoformat(),
220
+ )
app/services/sector_rotation.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sector Rotation Analysis — momentum-based sector rotation signals.
3
+
4
+ Calculates 1M/3M/6M/12M sector returns, relative strength vs Nifty 50,
5
+ and identifies leading/lagging sectors to determine market phase.
6
+ """
7
+
8
+ import time
9
+ import numpy as np
10
+ import pandas as pd
11
+ from datetime import datetime, timezone
12
+
13
+ from .analytics import (
14
+ get_stock_universe, _get_cached_df, get_stock_sector, get_stock_name,
15
+ NIFTY_INDEX,
16
+ )
17
+ from ..schemas.advanced_analytics import (
18
+ SectorMomentum, SectorRotationHistory, SectorRotationResponse,
19
+ )
20
+
21
+ _cache: tuple[SectorRotationResponse | None, float] = (None, 0.0)
22
+ _CACHE_TTL = 3600 # 1 hour
23
+
24
+
25
+ def _period_return(df: pd.DataFrame, days: int) -> float:
26
+ if df is None or len(df) < days + 1:
27
+ return 0.0
28
+ recent = df.tail(days + 1)
29
+ start = recent["close"].iloc[0]
30
+ end = recent["close"].iloc[-1]
31
+ return ((end - start) / start * 100) if start > 0 else 0.0
32
+
33
+
34
+ def _determine_market_phase(sectors: list[SectorMomentum]) -> str:
35
+ """Classify market phase based on sector breadth."""
36
+ overweight = sum(1 for s in sectors if s.signal == "OVERWEIGHT")
37
+ underweight = sum(1 for s in sectors if s.signal == "UNDERWEIGHT")
38
+ total = len(sectors) or 1
39
+
40
+ avg_3m = np.mean([s.return_3m for s in sectors]) if sectors else 0
41
+ avg_1m = np.mean([s.return_1m for s in sectors]) if sectors else 0
42
+
43
+ if overweight / total > 0.6 and avg_3m > 5:
44
+ return "EXPANSION"
45
+ elif overweight / total > 0.4 and avg_1m < avg_3m * 0.3:
46
+ return "PEAK"
47
+ elif underweight / total > 0.6 and avg_3m < -5:
48
+ return "CONTRACTION"
49
+ elif underweight / total > 0.4 and avg_1m > avg_3m:
50
+ return "TROUGH"
51
+ elif avg_3m > 2:
52
+ return "EXPANSION"
53
+ elif avg_3m < -2:
54
+ return "CONTRACTION"
55
+ return "PEAK" if avg_1m < 0 else "TROUGH"
56
+
57
+
58
+ async def get_sector_rotation(force: bool = False) -> SectorRotationResponse:
59
+ global _cache
60
+ cached, ts = _cache
61
+ if cached and not force and time.time() - ts < _CACHE_TTL:
62
+ return cached
63
+
64
+ universe = get_stock_universe()
65
+ nifty_df = _get_cached_df(NIFTY_INDEX, "2y")
66
+ nifty_12m = _period_return(nifty_df, 252) if nifty_df is not None else 0
67
+
68
+ # Group stocks by sector
69
+ sector_stocks: dict[str, list[str]] = {}
70
+ for sym in universe:
71
+ sec = get_stock_sector(sym)
72
+ if sec and sec != "Unknown":
73
+ sector_stocks.setdefault(sec, []).append(sym)
74
+
75
+ sectors: list[SectorMomentum] = []
76
+ rotation_history: list[SectorRotationHistory] = []
77
+
78
+ for sector, symbols in sector_stocks.items():
79
+ if len(symbols) < 2:
80
+ continue
81
+
82
+ returns_1m, returns_3m, returns_6m, returns_12m = [], [], [], []
83
+ rsi_vals, vol_vals = [], []
84
+
85
+ for sym in symbols:
86
+ df = _get_cached_df(sym, "2y")
87
+ if df is None or len(df) < 30:
88
+ continue
89
+
90
+ returns_1m.append(_period_return(df, 21))
91
+ returns_3m.append(_period_return(df, 63))
92
+ returns_6m.append(_period_return(df, 126))
93
+ returns_12m.append(_period_return(df, 252))
94
+
95
+ if "rsi_14" in df.columns:
96
+ last_rsi = df["rsi_14"].dropna().iloc[-1] if not df["rsi_14"].dropna().empty else 50
97
+ rsi_vals.append(last_rsi)
98
+ if "daily_return" in df.columns:
99
+ vol = df["daily_return"].dropna().tail(63).std() * np.sqrt(252) * 100
100
+ vol_vals.append(vol)
101
+
102
+ if not returns_3m:
103
+ continue
104
+
105
+ avg_1m = float(np.mean(returns_1m))
106
+ avg_3m = float(np.mean(returns_3m))
107
+ avg_6m = float(np.mean(returns_6m))
108
+ avg_12m = float(np.mean(returns_12m))
109
+
110
+ # Momentum score: weighted average of returns
111
+ momentum = avg_1m * 0.4 + avg_3m * 0.3 + avg_6m * 0.2 + avg_12m * 0.1
112
+ rel_strength = avg_12m - nifty_12m if nifty_12m else avg_12m
113
+
114
+ signal = "OVERWEIGHT" if momentum > 3 else "UNDERWEIGHT" if momentum < -3 else "NEUTRAL"
115
+
116
+ sectors.append(SectorMomentum(
117
+ sector=sector,
118
+ stock_count=len(symbols),
119
+ return_1m=round(avg_1m, 2),
120
+ return_3m=round(avg_3m, 2),
121
+ return_6m=round(avg_6m, 2),
122
+ return_12m=round(avg_12m, 2),
123
+ momentum_score=round(momentum, 2),
124
+ relative_strength=round(rel_strength, 2),
125
+ signal=signal,
126
+ avg_rsi=round(float(np.mean(rsi_vals)), 1) if rsi_vals else 50.0,
127
+ avg_volatility=round(float(np.mean(vol_vals)), 1) if vol_vals else 20.0,
128
+ ))
129
+
130
+ # Build rotation history (monthly sector returns for last 12 months)
131
+ sample_dfs = []
132
+ for sym in symbols[:10]: # sample up to 10 stocks per sector
133
+ df = _get_cached_df(sym, "2y")
134
+ if df is not None and len(df) > 200 and "close" in df.columns:
135
+ s = df.set_index("date")["close"].resample("ME").last().pct_change() * 100
136
+ s.name = sym
137
+ sample_dfs.append(s)
138
+
139
+ if sample_dfs:
140
+ combined = pd.concat(sample_dfs, axis=1).tail(12)
141
+ monthly_avg = combined.mean(axis=1)
142
+ cum_ret = 0.0
143
+ for dt, ret in monthly_avg.items():
144
+ if pd.notna(ret):
145
+ cum_ret += ret
146
+ rotation_history.append(SectorRotationHistory(
147
+ date=dt.strftime("%Y-%m-%d"),
148
+ sector=sector,
149
+ cumulative_return=round(cum_ret, 2),
150
+ ))
151
+
152
+ # Sort by momentum
153
+ sectors.sort(key=lambda s: s.momentum_score, reverse=True)
154
+ leading = [s.sector for s in sectors[:3]]
155
+ lagging = [s.sector for s in sectors[-3:]]
156
+ phase = _determine_market_phase(sectors)
157
+
158
+ result = SectorRotationResponse(
159
+ sectors=sectors,
160
+ rotation_history=rotation_history,
161
+ leading_sectors=leading,
162
+ lagging_sectors=lagging,
163
+ market_phase=phase,
164
+ generated_at=datetime.now(timezone.utc).isoformat(),
165
+ )
166
+ _cache = (result, time.time())
167
+ return result
app/services/timeseries.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Time-series analysis service — ARIMA, ETS, decomposition, stationarity tests.
3
+
4
+ Uses statsmodels for proper econometric modelling. Models are cached per symbol
5
+ so repeat requests are instant after the first computation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import time
12
+ import warnings
13
+ from typing import Optional
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ from statsmodels.tsa.arima.model import ARIMA
18
+ from statsmodels.tsa.holtwinters import ExponentialSmoothing
19
+ from statsmodels.tsa.seasonal import seasonal_decompose
20
+ from statsmodels.tsa.stattools import adfuller, kpss, acf, pacf
21
+
22
+ from ..schemas.analytics import (
23
+ ForecastPoint,
24
+ ModelForecast,
25
+ SeasonalDecomposition,
26
+ StationarityTest,
27
+ AutocorrelationPoint,
28
+ TimeSeriesAnalysisResult,
29
+ )
30
+ from .analytics import (
31
+ _get_cached_df,
32
+ get_stock_name,
33
+ get_stock_sector,
34
+ get_stock_universe,
35
+ )
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Suppress convergence warnings from statsmodels
40
+ warnings.filterwarnings("ignore", category=UserWarning, module="statsmodels")
41
+ warnings.filterwarnings("ignore", category=FutureWarning, module="statsmodels")
42
+
43
+ # ── Cache for computed results ────────────────────────────────────────────────
44
+ _ts_cache: dict[str, tuple[TimeSeriesAnalysisResult, float]] = {}
45
+ _TS_CACHE_TTL = 7200 # 2 hours
46
+
47
+
48
+ # ── Helpers ───────────────────────────────────────────────────────────────────
49
+
50
+ def _make_forecast_points(
51
+ last_date: pd.Timestamp, values: np.ndarray, lower: np.ndarray, upper: np.ndarray
52
+ ) -> list[ForecastPoint]:
53
+ points = []
54
+ for h in range(len(values)):
55
+ d = last_date + pd.Timedelta(days=h + 1)
56
+ points.append(ForecastPoint(
57
+ date=d.strftime("%Y-%m-%d"),
58
+ price=round(float(values[h]), 2),
59
+ lower=round(float(lower[h]), 2),
60
+ upper=round(float(upper[h]), 2),
61
+ ))
62
+ return points
63
+
64
+
65
+ def _determine_differencing_order(series: np.ndarray, max_d: int = 2) -> int:
66
+ """Determine optimal differencing order using ADF test.
67
+
68
+ Repeatedly differences until stationary (p < 0.05) or max_d reached.
69
+ """
70
+ current = series.copy()
71
+ for d in range(max_d + 1):
72
+ try:
73
+ _, p_value, *_ = adfuller(current, maxlag=20, autolag="AIC")
74
+ if p_value < 0.05:
75
+ return d
76
+ except Exception:
77
+ return 1 # safe default
78
+ if d < max_d:
79
+ current = np.diff(current)
80
+ return max_d
81
+
82
+
83
+ # ── Core analysis ─────────────────────────────────────────────────────────────
84
+
85
+ def run_timeseries_analysis(symbol: str, horizon: int = 30) -> Optional[TimeSeriesAnalysisResult]:
86
+ """Full time-series analysis for a single stock."""
87
+
88
+ # Check cache
89
+ if symbol in _ts_cache:
90
+ cached, ts = _ts_cache[symbol]
91
+ if time.time() - ts < _TS_CACHE_TTL:
92
+ return cached
93
+
94
+ df = _get_cached_df(symbol, "2y")
95
+ if df is None or len(df) < 120:
96
+ return None
97
+
98
+ close = df["close"].values.astype(float)
99
+ dates = pd.to_datetime(df["date"].values)
100
+ last_date = dates[-1]
101
+ n = len(close)
102
+
103
+ # ── 1. Seasonal Decomposition ─────────────────────────────────────────
104
+ decomp_data: list[SeasonalDecomposition] = []
105
+ try:
106
+ # Use 5-day period (trading week) for decomposition
107
+ series = pd.Series(close, index=dates)
108
+ result = seasonal_decompose(series, model="additive", period=5, extrapolate_trend="freq")
109
+
110
+ # Sample every 5th point to keep payload manageable
111
+ step = max(1, n // 100)
112
+ for i in range(0, n, step):
113
+ decomp_data.append(SeasonalDecomposition(
114
+ date=dates[i].strftime("%Y-%m-%d"),
115
+ observed=round(float(close[i]), 2),
116
+ trend=round(float(result.trend.iloc[i]), 2) if not np.isnan(result.trend.iloc[i]) else None,
117
+ seasonal=round(float(result.seasonal.iloc[i]), 2) if not np.isnan(result.seasonal.iloc[i]) else None,
118
+ residual=round(float(result.resid.iloc[i]), 2) if not np.isnan(result.resid.iloc[i]) else None,
119
+ ))
120
+ except Exception as exc:
121
+ logger.warning(f"Decomposition failed for {symbol}: {exc}")
122
+
123
+ # ── 2. Stationarity Tests + Optimal Differencing ──────────────────────
124
+ stationarity_tests: list[StationarityTest] = []
125
+
126
+ # Determine optimal differencing order from the data
127
+ optimal_d = _determine_differencing_order(close)
128
+
129
+ # ADF test on raw series
130
+ try:
131
+ adf_stat, adf_p, *_ = adfuller(close, maxlag=20, autolag="AIC")
132
+ stationarity_tests.append(StationarityTest(
133
+ test_name="Augmented Dickey-Fuller",
134
+ statistic=round(float(adf_stat), 4),
135
+ p_value=round(float(adf_p), 4),
136
+ is_stationary=adf_p < 0.05,
137
+ interpretation="Stationary (reject unit root)" if adf_p < 0.05
138
+ else f"Non-stationary — auto-differencing with d={optimal_d} applied",
139
+ ))
140
+ except Exception as exc:
141
+ logger.debug(f"ADF test failed for {symbol}: {exc}")
142
+
143
+ # KPSS test on raw series
144
+ try:
145
+ kpss_stat, kpss_p, *_ = kpss(close, regression="ct", nlags="auto")
146
+ stationarity_tests.append(StationarityTest(
147
+ test_name="KPSS",
148
+ statistic=round(float(kpss_stat), 4),
149
+ p_value=round(float(kpss_p), 4),
150
+ is_stationary=kpss_p > 0.05,
151
+ interpretation="Stationary (fail to reject)" if kpss_p > 0.05
152
+ else f"Non-stationary — auto-differencing with d={optimal_d} applied",
153
+ ))
154
+ except Exception as exc:
155
+ logger.debug(f"KPSS test failed for {symbol}: {exc}")
156
+
157
+ # If differenced, also run ADF on the differenced series to confirm
158
+ if optimal_d > 0:
159
+ try:
160
+ diffed = close.copy()
161
+ for _ in range(optimal_d):
162
+ diffed = np.diff(diffed)
163
+ adf_stat_d, adf_p_d, *_ = adfuller(diffed, maxlag=20, autolag="AIC")
164
+ stationarity_tests.append(StationarityTest(
165
+ test_name=f"ADF (after d={optimal_d} differencing)",
166
+ statistic=round(float(adf_stat_d), 4),
167
+ p_value=round(float(adf_p_d), 4),
168
+ is_stationary=adf_p_d < 0.05,
169
+ interpretation=f"Stationary after {optimal_d}x differencing (p={adf_p_d:.4f})"
170
+ if adf_p_d < 0.05 else f"Still non-stationary after d={optimal_d}",
171
+ ))
172
+ except Exception as exc:
173
+ logger.debug(f"Post-differencing ADF failed for {symbol}: {exc}")
174
+
175
+ # Log-transform check — useful for variance stationarity
176
+ use_log = False
177
+ try:
178
+ if np.all(close > 0):
179
+ log_close = np.log(close)
180
+ log_d = _determine_differencing_order(log_close)
181
+ if log_d < optimal_d:
182
+ use_log = True
183
+ optimal_d = log_d
184
+ logger.info(f"{symbol}: log-transform reduces d from {optimal_d} to {log_d}")
185
+ except Exception:
186
+ pass
187
+
188
+ # ── 3. ACF / PACF ────────────────────────────────────────────────────
189
+ autocorrelation: list[AutocorrelationPoint] = []
190
+ try:
191
+ returns = np.diff(np.log(close))
192
+ nlags = min(30, len(returns) // 3)
193
+ acf_vals = acf(returns, nlags=nlags, fft=True)
194
+ pacf_vals = pacf(returns, nlags=nlags)
195
+ for lag in range(nlags + 1):
196
+ autocorrelation.append(AutocorrelationPoint(
197
+ lag=lag,
198
+ acf=round(float(acf_vals[lag]), 4),
199
+ pacf=round(float(pacf_vals[lag]), 4),
200
+ ))
201
+ except Exception as exc:
202
+ logger.debug(f"ACF/PACF failed for {symbol}: {exc}")
203
+
204
+ # ── 4. Model Forecasts ────────────────────────────────────────────────
205
+ # Split: last 30 days for validation, rest for training
206
+ val_size = min(30, n // 5)
207
+ train = close[:-val_size]
208
+ val = close[-val_size:]
209
+ model_forecasts: list[ModelForecast] = []
210
+
211
+ # --- ARIMA (with data-driven d) ---
212
+ # Prepare data: optionally log-transform for variance stationarity
213
+ arima_data_train = np.log(train) if use_log and np.all(train > 0) else train
214
+ arima_data_full = np.log(close) if use_log and np.all(close > 0) else close
215
+
216
+ try:
217
+ # Build order grid using the optimal d
218
+ d = optimal_d
219
+ order_grid = [
220
+ (1, d, 1), (2, d, 1), (1, d, 2), (2, d, 2), (0, d, 1), (1, d, 0),
221
+ (3, d, 1), (1, d, 3),
222
+ ]
223
+
224
+ best_arima = None
225
+ best_aic = float("inf")
226
+ best_order = (1, d, 1)
227
+
228
+ for order in order_grid:
229
+ try:
230
+ model = ARIMA(arima_data_train, order=order)
231
+ fit = model.fit()
232
+ if fit.aic < best_aic:
233
+ best_aic = fit.aic
234
+ best_arima = fit
235
+ best_order = order
236
+ except Exception:
237
+ continue
238
+
239
+ if best_arima is not None:
240
+ # Validation RMSE (compare on original scale)
241
+ val_pred = best_arima.forecast(steps=val_size)
242
+ if use_log:
243
+ val_pred = np.exp(val_pred)
244
+ rmse = float(np.sqrt(np.mean((val - val_pred) ** 2)))
245
+
246
+ # Refit on full data for final forecast
247
+ full_model = ARIMA(arima_data_full, order=best_order).fit()
248
+ fc = full_model.get_forecast(steps=horizon)
249
+ fc_mean = fc.predicted_mean
250
+ fc_ci = fc.conf_int(alpha=0.05)
251
+
252
+ # Invert log transform if used
253
+ if use_log:
254
+ fc_mean = np.exp(fc_mean)
255
+ fc_ci = np.exp(fc_ci)
256
+
257
+ points = _make_forecast_points(
258
+ last_date, fc_mean, fc_ci[:, 0], fc_ci[:, 1]
259
+ )
260
+ label = f"ARIMA{'(log)' if use_log else ''}"
261
+ model_forecasts.append(ModelForecast(
262
+ model_name=label,
263
+ forecast=points,
264
+ rmse=round(rmse, 2),
265
+ aic=round(best_aic, 2),
266
+ order=str(best_order),
267
+ ))
268
+ except Exception as exc:
269
+ logger.warning(f"ARIMA failed for {symbol}: {exc}")
270
+
271
+ # --- ETS (Holt-Winters Exponential Smoothing) ---
272
+ ets_train = np.log(train) if use_log and np.all(train > 0) else train
273
+ ets_full = np.log(close) if use_log and np.all(close > 0) else close
274
+
275
+ try:
276
+ model = ExponentialSmoothing(
277
+ ets_train, trend="add", seasonal=None, damped_trend=True,
278
+ )
279
+ fit = model.fit(optimized=True)
280
+
281
+ val_pred = fit.forecast(steps=val_size)
282
+ if use_log:
283
+ val_pred = np.exp(val_pred)
284
+ rmse = float(np.sqrt(np.mean((val - val_pred) ** 2)))
285
+
286
+ # Refit on full data
287
+ full_fit = ExponentialSmoothing(
288
+ ets_full, trend="add", seasonal=None, damped_trend=True,
289
+ ).fit(optimized=True)
290
+
291
+ fc_mean = full_fit.forecast(steps=horizon)
292
+
293
+ # Approximate confidence intervals using residual std
294
+ resid_std = float(np.std(full_fit.resid.dropna()))
295
+ h_arr = np.arange(1, horizon + 1)
296
+ band = 1.96 * resid_std * np.sqrt(h_arr)
297
+
298
+ fc_vals = fc_mean.values
299
+ fc_lower = fc_vals - band
300
+ fc_upper = fc_vals + band
301
+
302
+ # Invert log transform
303
+ if use_log:
304
+ fc_vals = np.exp(fc_vals)
305
+ fc_lower = np.exp(fc_lower)
306
+ fc_upper = np.exp(fc_upper)
307
+
308
+ label = f"Exponential Smoothing{'(log)' if use_log else ''}"
309
+ points = _make_forecast_points(last_date, fc_vals, fc_lower, fc_upper)
310
+ model_forecasts.append(ModelForecast(
311
+ model_name=label,
312
+ forecast=points,
313
+ rmse=round(rmse, 2),
314
+ aic=round(float(fit.aic), 2) if hasattr(fit, "aic") else None,
315
+ order="Holt (damped)",
316
+ ))
317
+ except Exception as exc:
318
+ logger.warning(f"ETS failed for {symbol}: {exc}")
319
+
320
+ # --- Linear Trend (simple baseline) ---
321
+ try:
322
+ x = np.arange(len(train))
323
+ coeffs = np.polyfit(x, train, 1)
324
+ trend_pred = np.polyval(coeffs, np.arange(len(train), len(train) + val_size))
325
+ rmse = float(np.sqrt(np.mean((val - trend_pred) ** 2)))
326
+
327
+ x_full = np.arange(n)
328
+ coeffs_full = np.polyfit(x_full, close, 1)
329
+ fc_x = np.arange(n, n + horizon)
330
+ fc_mean = np.polyval(coeffs_full, fc_x)
331
+
332
+ resid = close - np.polyval(coeffs_full, x_full)
333
+ resid_std = float(np.std(resid))
334
+ h_arr = np.arange(1, horizon + 1)
335
+ band = 1.96 * resid_std * np.sqrt(1 + h_arr / n)
336
+
337
+ points = _make_forecast_points(last_date, fc_mean, fc_mean - band, fc_mean + band)
338
+ model_forecasts.append(ModelForecast(
339
+ model_name="Linear Trend",
340
+ forecast=points,
341
+ rmse=round(rmse, 2),
342
+ aic=None,
343
+ order="degree=1",
344
+ ))
345
+ except Exception as exc:
346
+ logger.warning(f"Linear trend failed for {symbol}: {exc}")
347
+
348
+ # ── 5. Pick best model ────────────────────────────────────────────────
349
+ if model_forecasts:
350
+ best = min(model_forecasts, key=lambda m: m.rmse)
351
+ best_model = best.model_name
352
+ best_fc = best.forecast
353
+ predicted_price = best_fc[-1].price
354
+ else:
355
+ best_model = "None"
356
+ predicted_price = float(close[-1])
357
+
358
+ current_price = float(close[-1])
359
+ predicted_return = (predicted_price - current_price) / current_price * 100
360
+
361
+ if predicted_return > 3:
362
+ trend_label = "BULLISH"
363
+ elif predicted_return < -3:
364
+ trend_label = "BEARISH"
365
+ else:
366
+ trend_label = "NEUTRAL"
367
+
368
+ vol_30 = float(np.std(np.diff(np.log(close[-30:]))) * np.sqrt(252) * 100)
369
+ recent_90 = close[-90:] if len(close) >= 90 else close
370
+ support = float(np.min(recent_90))
371
+ resistance = float(np.max(recent_90))
372
+
373
+ result = TimeSeriesAnalysisResult(
374
+ symbol=symbol,
375
+ company_name=get_stock_name(symbol),
376
+ sector=get_stock_sector(symbol),
377
+ current_price=round(current_price, 2),
378
+ data_points=n,
379
+ decomposition=decomp_data,
380
+ stationarity_tests=stationarity_tests,
381
+ autocorrelation=autocorrelation,
382
+ model_forecasts=model_forecasts,
383
+ best_model=best_model,
384
+ predicted_return_pct=round(predicted_return, 2),
385
+ trend=trend_label,
386
+ volatility_30d=round(vol_30, 2),
387
+ support_level=round(support, 2),
388
+ resistance_level=round(resistance, 2),
389
+ )
390
+
391
+ _ts_cache[symbol] = (result, time.time())
392
+ return result
393
+
394
+
395
+ def get_available_symbols() -> list[dict]:
396
+ """Return list of symbols available for analysis."""
397
+ symbols = []
398
+ for sym in get_stock_universe():
399
+ df = _get_cached_df(sym, "1y")
400
+ if df is not None and len(df) >= 120:
401
+ symbols.append({
402
+ "symbol": sym,
403
+ "company_name": get_stock_name(sym),
404
+ "sector": get_stock_sector(sym),
405
+ "data_points": len(df),
406
+ })
407
+ return symbols
app/services/volatility.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Volatility Forecasting — GARCH(1,1) model for 30-day vol prediction.
3
+
4
+ Provides: realized vol history, GARCH forecast, volatility cones,
5
+ vol-regime classification, and low-vol entry signals.
6
+ """
7
+
8
+ import time
9
+ import warnings
10
+ import numpy as np
11
+ import pandas as pd
12
+ from datetime import datetime, timezone
13
+
14
+ from .analytics import (
15
+ get_stock_universe, _get_cached_df, get_stock_name, get_stock_sector,
16
+ )
17
+ from ..schemas.advanced_analytics import (
18
+ VolatilityPoint, VolatilityConePoint, VolatilityForecastResponse, VolSymbol,
19
+ )
20
+
21
+ warnings.filterwarnings("ignore", category=FutureWarning)
22
+
23
+ _cache: dict[str, tuple[VolatilityForecastResponse, float]] = {}
24
+ _CACHE_TTL = 3600
25
+
26
+
27
+ def _annualize(daily_vol: float) -> float:
28
+ return daily_vol * np.sqrt(252) * 100
29
+
30
+
31
+ def _vol_regime(vol_percentile: float) -> str:
32
+ if vol_percentile < 20:
33
+ return "LOW"
34
+ elif vol_percentile < 60:
35
+ return "NORMAL"
36
+ elif vol_percentile < 85:
37
+ return "HIGH"
38
+ return "EXTREME"
39
+
40
+
41
+ def _entry_signal(regime: str) -> str:
42
+ if regime == "LOW":
43
+ return "LOW_VOL_ENTRY"
44
+ elif regime in ("HIGH", "EXTREME"):
45
+ return "HIGH_VOL_CAUTION"
46
+ return "NEUTRAL"
47
+
48
+
49
+ async def get_volatility_forecast(symbol: str) -> VolatilityForecastResponse:
50
+ cache_key = symbol.upper()
51
+ if cache_key in _cache:
52
+ cached, ts = _cache[cache_key]
53
+ if time.time() - ts < _CACHE_TTL:
54
+ return cached
55
+
56
+ from arch import arch_model
57
+
58
+ df = _get_cached_df(symbol, "2y")
59
+ if df is None or len(df) < 200:
60
+ raise ValueError(f"Insufficient data for {symbol}")
61
+
62
+ close = df["close"].values
63
+ returns = pd.Series(close).pct_change().dropna().values * 100 # percentage returns
64
+ dates = df["date"].values[1:] # align with returns
65
+
66
+ if len(returns) < 200:
67
+ raise ValueError(f"Insufficient returns data for {symbol}")
68
+
69
+ # --- GARCH(1,1) ---
70
+ try:
71
+ model = arch_model(returns, vol="Garch", p=1, q=1, mean="Constant", dist="normal")
72
+ with warnings.catch_warnings():
73
+ warnings.simplefilter("ignore")
74
+ res = model.fit(disp="off", show_warning=False)
75
+
76
+ # Forecast 30 days
77
+ fcast = res.forecast(horizon=30, reindex=False)
78
+ forecast_var = fcast.variance.values[-1] # 30-day variance array
79
+ forecast_vol_daily = np.sqrt(forecast_var) # daily vol (% terms)
80
+
81
+ omega = float(res.params.get("omega", 0))
82
+ alpha_1 = float(res.params.get("alpha[1]", 0))
83
+ beta_1 = float(res.params.get("beta[1]", 0))
84
+ persistence = alpha_1 + beta_1
85
+ garch_params = {
86
+ "omega": round(omega, 6),
87
+ "alpha": round(alpha_1, 4),
88
+ "beta": round(beta_1, 4),
89
+ "persistence": round(persistence, 4),
90
+ }
91
+
92
+ # Annualized GARCH forecast (average over 30 days)
93
+ garch_30d_vol = float(np.mean(forecast_vol_daily)) * np.sqrt(252)
94
+ except Exception:
95
+ # Fallback to simple EWMA vol
96
+ ewma_var = pd.Series(returns).ewm(span=30).var().iloc[-1]
97
+ garch_30d_vol = float(np.sqrt(ewma_var) * np.sqrt(252))
98
+ forecast_vol_daily = np.full(30, np.sqrt(ewma_var))
99
+ garch_params = {"omega": 0, "alpha": 0.06, "beta": 0.94, "persistence": 1.0}
100
+
101
+ # --- Realized vol history (30-day rolling, last 6 months) ---
102
+ ret_series = pd.Series(returns, index=pd.to_datetime(dates[:len(returns)]))
103
+ rolling_vol = ret_series.rolling(30).std() * np.sqrt(252)
104
+ hist_6m = rolling_vol.tail(126).dropna()
105
+
106
+ history: list[VolatilityPoint] = []
107
+ for dt, rv in hist_6m.items():
108
+ history.append(VolatilityPoint(
109
+ date=pd.Timestamp(dt).strftime("%Y-%m-%d"),
110
+ realized_vol=round(float(rv), 2),
111
+ ))
112
+
113
+ # Add 30-day forecast
114
+ last_date = pd.Timestamp(dates[-1])
115
+ for i in range(30):
116
+ fdate = last_date + pd.Timedelta(days=i + 1)
117
+ fv = float(forecast_vol_daily[i]) * np.sqrt(252) if i < len(forecast_vol_daily) else garch_30d_vol
118
+ history.append(VolatilityPoint(
119
+ date=fdate.strftime("%Y-%m-%d"),
120
+ forecast_vol=round(fv, 2),
121
+ lower=round(fv * 0.7, 2),
122
+ upper=round(fv * 1.3, 2),
123
+ ))
124
+
125
+ # --- Current realized vol ---
126
+ current_rv = float(rolling_vol.iloc[-1]) if not rolling_vol.empty else garch_30d_vol
127
+
128
+ # --- Vol percentile (vs 1yr) ---
129
+ vol_1y = rolling_vol.tail(252).dropna()
130
+ if len(vol_1y) > 10:
131
+ vol_pct = float((vol_1y < current_rv).sum() / len(vol_1y) * 100)
132
+ else:
133
+ vol_pct = 50.0
134
+
135
+ regime = _vol_regime(vol_pct)
136
+ entry = _entry_signal(regime)
137
+
138
+ # --- Volatility Cone ---
139
+ vol_cone: list[VolatilityConePoint] = []
140
+ for horizon in [5, 10, 21, 63, 126, 252]:
141
+ if len(returns) > horizon + 20:
142
+ h_vols = []
143
+ for start in range(0, len(returns) - horizon, max(1, horizon // 2)):
144
+ chunk = returns[start:start + horizon]
145
+ h_vols.append(float(np.std(chunk) * np.sqrt(252 / horizon)))
146
+ h_vols_arr = np.array(h_vols)
147
+
148
+ # Current vol at this horizon
149
+ cur_h_vol = float(np.std(returns[-horizon:]) * np.sqrt(252 / horizon))
150
+
151
+ vol_cone.append(VolatilityConePoint(
152
+ horizon_days=horizon,
153
+ current_vol=round(cur_h_vol, 2),
154
+ percentile_10=round(float(np.percentile(h_vols_arr, 10)), 2),
155
+ percentile_25=round(float(np.percentile(h_vols_arr, 25)), 2),
156
+ percentile_50=round(float(np.percentile(h_vols_arr, 50)), 2),
157
+ percentile_75=round(float(np.percentile(h_vols_arr, 75)), 2),
158
+ percentile_90=round(float(np.percentile(h_vols_arr, 90)), 2),
159
+ ))
160
+
161
+ result = VolatilityForecastResponse(
162
+ symbol=symbol,
163
+ company_name=get_stock_name(symbol),
164
+ sector=get_stock_sector(symbol),
165
+ current_price=float(close[-1]),
166
+ current_realized_vol=round(current_rv, 2),
167
+ garch_forecast_vol=round(garch_30d_vol, 2),
168
+ vol_regime=regime,
169
+ entry_signal=entry,
170
+ vol_percentile=round(vol_pct, 1),
171
+ history=history,
172
+ vol_cone=vol_cone,
173
+ garch_params=garch_params,
174
+ generated_at=datetime.now(timezone.utc).isoformat(),
175
+ )
176
+ _cache[cache_key] = (result, time.time())
177
+ return result
178
+
179
+
180
+ async def get_vol_symbols() -> list[VolSymbol]:
181
+ universe = get_stock_universe()
182
+ result = []
183
+ for sym in sorted(universe):
184
+ name = get_stock_name(sym)
185
+ sector = get_stock_sector(sym)
186
+ if name:
187
+ result.append(VolSymbol(symbol=sym, company_name=name, sector=sector))
188
+ return result
requirements.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.111.0
2
+ uvicorn[standard]==0.29.0
3
+ python-dotenv==1.0.1
4
+ pydantic==2.7.1
5
+ pydantic-settings==2.2.1
6
+
7
+ # Supabase (using REST API via httpx — no supabase package needed)
8
+
9
+ # AI (OpenRouter via httpx — no extra package needed)
10
+
11
+ # Financial data
12
+ yfinance==0.2.40
13
+ pandas==2.2.2
14
+ numpy==1.26.4
15
+
16
+ # ML / Analytics
17
+ scikit-learn==1.8.0
18
+ scipy==1.17.1
19
+ statsmodels==0.14.6
20
+ arch==8.0.0
21
+
22
+
23
+ # Pipeline scheduling
24
+ schedule==1.2.1
25
+ APScheduler==3.10.4
26
+
27
+ # HTTP
28
+ httpx==0.27.0
29
+ requests==2.31.0
30
+
31
+ # Utils
32
+ python-dateutil==2.9.0
33
+ pytz==2024.1
scripts/backfill_nifty500.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Nifty 500 Full-History Backfill
3
+ ================================
4
+ Downloads complete daily OHLCV history for every Nifty 500 stock from
5
+ Yahoo Finance and persists it to Supabase stock_prices.
6
+
7
+ Run from the project root:
8
+ python -m backend.scripts.backfill_nifty500
9
+
10
+ Features:
11
+ - Fetches live Nifty 500 constituent list from NSE India CSV
12
+ - period="max" → full history from listing date (typically 15-25 yrs)
13
+ - Skips symbols that already have ≥ 200 rows in Supabase (resume-safe)
14
+ - Batch-downloads 50 symbols at a time via yfinance for speed
15
+ - Streams rows to Supabase in 1 000-row chunks
16
+ - Populates stocks metadata table before writing prices (FK safe)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import sys
23
+ import time
24
+ import logging
25
+ from io import StringIO
26
+ from concurrent.futures import ThreadPoolExecutor, as_completed
27
+
28
+ import httpx
29
+ import yfinance as yf
30
+ import pandas as pd
31
+ from dotenv import load_dotenv
32
+
33
+ # ── Bootstrap ──────────────────────────────────────────────────────────────────
34
+ load_dotenv(os.path.join(os.path.dirname(__file__), "..", "..", ".env"))
35
+
36
+ logging.basicConfig(
37
+ level=logging.INFO,
38
+ format="%(asctime)s %(levelname)-7s %(message)s",
39
+ datefmt="%H:%M:%S",
40
+ )
41
+ log = logging.getLogger("backfill")
42
+
43
+ SUPABASE_URL = os.getenv("SUPABASE_URL", "")
44
+ SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
45
+
46
+ if not SUPABASE_URL or not SUPABASE_KEY:
47
+ log.error("SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY not set in .env")
48
+ sys.exit(1)
49
+
50
+
51
+ # ── Supabase helpers ───────────────────────────────────────────────────────────
52
+
53
+ def _sb_headers(prefer: str = "resolution=merge-duplicates") -> dict:
54
+ return {
55
+ "apikey": SUPABASE_KEY,
56
+ "Authorization": f"Bearer {SUPABASE_KEY}",
57
+ "Content-Type": "application/json",
58
+ "Prefer": prefer,
59
+ }
60
+
61
+ def _sb(table: str) -> str:
62
+ return f"{SUPABASE_URL}/rest/v1/{table}"
63
+
64
+
65
+ def sb_upsert(table: str, rows: list[dict], conflict_cols: str = "") -> bool:
66
+ url = _sb(table) + (f"?on_conflict={conflict_cols}" if conflict_cols else "")
67
+ try:
68
+ r = httpx.post(url, headers=_sb_headers(), json=rows, timeout=60)
69
+ r.raise_for_status()
70
+ return True
71
+ except Exception as e:
72
+ log.warning(f" Supabase write error ({table}): {e}")
73
+ return False
74
+
75
+
76
+ def sb_has_sufficient_data(sym: str, min_rows: int = 200) -> bool:
77
+ """Return True if stock_prices already has >= min_rows for this symbol."""
78
+ try:
79
+ r = httpx.get(
80
+ _sb("stock_prices"),
81
+ headers={**_sb_headers(), "Prefer": "count=exact"},
82
+ params={"symbol": f"eq.{sym}", "select": "symbol", "limit": "1"},
83
+ timeout=15,
84
+ )
85
+ content_range = r.headers.get("content-range", "")
86
+ if "/" in content_range:
87
+ total = int(content_range.split("/")[1])
88
+ return total >= min_rows
89
+ except Exception:
90
+ pass
91
+ return False
92
+
93
+
94
+ def sb_get_symbol_counts(symbols: list[str]) -> dict[str, int]:
95
+ """Return {bare_symbol: row_count} checked concurrently for speed."""
96
+ counts: dict[str, int] = {}
97
+ def _check(sym: str):
98
+ try:
99
+ r = httpx.get(
100
+ _sb("stock_prices"),
101
+ headers={**_sb_headers(), "Prefer": "count=exact"},
102
+ params={"symbol": f"eq.{sym}", "select": "symbol", "limit": "1"},
103
+ timeout=15,
104
+ )
105
+ cr = r.headers.get("content-range", "")
106
+ if "/" in cr:
107
+ counts[sym] = int(cr.split("/")[1])
108
+ except Exception:
109
+ pass
110
+
111
+ with ThreadPoolExecutor(max_workers=20) as ex:
112
+ list(ex.map(_check, symbols))
113
+ return counts
114
+
115
+
116
+ # ── NSE 500 constituent list ───────────────────────────────────────────────────
117
+
118
+ NSE_CSV_URL = "https://archives.nseindia.com/content/indices/ind_nifty500list.csv"
119
+
120
+ # Fallback: top ~100 liquid NSE stocks if NSE CSV is unreachable
121
+ FALLBACK_SYMBOLS = [
122
+ "RELIANCE","TCS","HDFCBANK","INFY","ICICIBANK","HINDUNILVR","SBIN",
123
+ "BHARTIARTL","KOTAKBANK","AXISBANK","BAJFINANCE","LT","WIPRO","HCLTECH",
124
+ "ASIANPAINT","MARUTI","SUNPHARMA","ULTRACEMCO","TITAN","POWERGRID",
125
+ "NTPC","ONGC","JSWSTEEL","ADANIENT","TATAMOTORS","HDFCLIFE","BAJAJFINSV",
126
+ "TECHM","MM","NESTLEIND","CIPLA","DRREDDY","DIVISLAB","BRITANNIA","HEROMOTOCO",
127
+ "EICHERMOT","INDUSINDBK","APOLLOHOSP","TATACONSUM","SBILIFE","PIDILITIND",
128
+ "HAVELLS","BERGEPAINT","MUTHOOTFIN","COLPAL","DABUR","MARICO","GODREJCP",
129
+ "LUPIN","TORNTPHARM","AUROPHARMA","BIOCON","ALKEM","ABBOTINDIA","PFIZER",
130
+ "GLAXO","TATACHEM","AMBUJACEM","ACCGRI","SHREECEM","GRASIM","HINDZINC",
131
+ "VEDL","HINDALCO","NATIONALUM","SAIL","JSWENERGY","TATAPOWER","ADANIGREEN",
132
+ "ADANIPORTS","ADANITRANS","ITC","COALINDIA","BPCL","IOC","HINDPETRO","GAIL",
133
+ "PETRONET","MGL","IGL","CONCOR","IRCTC","PFC","RECLTD","IRFC","NHPC",
134
+ "SJVN","TORNTPOWER","CESC","TRENT","DMART","NYKAA","ZOMATO","PAYTM",
135
+ "POLICYBZR","NAUKRI","JUSTDIAL","INDIAMART","HAPPSTMNDS","COFORGE",
136
+ "MPHASIS","PERSISTENT","LTIM","KPITTECH","TATAELXSI","SONATSOFTW",
137
+ ]
138
+
139
+
140
+ def fetch_nifty500_list() -> list[dict]:
141
+ """
142
+ Returns list of {symbol_ns, company_name, sector} dicts.
143
+ symbol_ns = bare NSE ticker + ".NS" e.g. "RELIANCE.NS"
144
+ """
145
+ log.info("Fetching Nifty 500 constituent list from NSE India…")
146
+ try:
147
+ r = httpx.get(
148
+ NSE_CSV_URL,
149
+ headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"},
150
+ timeout=20,
151
+ follow_redirects=True,
152
+ )
153
+ r.raise_for_status()
154
+ df = pd.read_csv(StringIO(r.text))
155
+ # NSE CSV columns: Company Name, Industry, Symbol, Series, ISIN Code
156
+ df.columns = [c.strip() for c in df.columns]
157
+ sym_col = next(c for c in df.columns if "symbol" in c.lower())
158
+ name_col = next(c for c in df.columns if "company" in c.lower())
159
+ ind_col = next((c for c in df.columns if "industry" in c.lower()), None)
160
+
161
+ results = []
162
+ for _, row in df.iterrows():
163
+ sym = str(row[sym_col]).strip()
164
+ if not sym or sym == "nan":
165
+ continue
166
+ results.append({
167
+ "symbol_ns": sym + ".NS",
168
+ "bare": sym,
169
+ "company_name": str(row[name_col]).strip(),
170
+ "sector": str(row[ind_col]).strip() if ind_col else "Unknown",
171
+ })
172
+ log.info(f" Got {len(results)} symbols from NSE CSV")
173
+ return results
174
+
175
+ except Exception as e:
176
+ log.warning(f"NSE CSV fetch failed ({e}), using fallback list")
177
+ return [
178
+ {"symbol_ns": s + ".NS", "bare": s, "company_name": s, "sector": "Unknown"}
179
+ for s in FALLBACK_SYMBOLS
180
+ ]
181
+
182
+
183
+ # ── yfinance download ──────────────────────────────────────────────────────────
184
+
185
+ def download_batch(symbols_ns: list[str]) -> dict[str, pd.DataFrame]:
186
+ """
187
+ Download full daily history for a batch of symbols.
188
+ Returns {symbol_ns: DataFrame(date, open, high, low, close, volume)}.
189
+ """
190
+ if not symbols_ns:
191
+ return {}
192
+
193
+ try:
194
+ raw = yf.download(
195
+ symbols_ns,
196
+ period="max",
197
+ interval="1d",
198
+ auto_adjust=True,
199
+ progress=False,
200
+ threads=True,
201
+ )
202
+ except Exception as e:
203
+ log.warning(f" yfinance batch error: {e}")
204
+ return {}
205
+
206
+ if raw is None or raw.empty:
207
+ return {}
208
+
209
+ result: dict[str, pd.DataFrame] = {}
210
+
211
+ # Single symbol → flat columns
212
+ if len(symbols_ns) == 1:
213
+ df = raw.reset_index()
214
+ df.rename(columns={"Date": "date", "Open": "open", "High": "high",
215
+ "Low": "low", "Close": "close", "Volume": "volume"}, inplace=True)
216
+ df["date"] = pd.to_datetime(df["date"]).dt.tz_localize(None)
217
+ df = df[["date", "open", "high", "low", "close", "volume"]].dropna(subset=["close"])
218
+ df = df[df["close"] > 0].reset_index(drop=True)
219
+ if not df.empty:
220
+ result[symbols_ns[0]] = df
221
+ return result
222
+
223
+ # Multiple symbols → MultiIndex columns (Price, Ticker)
224
+ for sym in symbols_ns:
225
+ try:
226
+ sym_data = raw.xs(sym, axis=1, level=1) if sym in raw.columns.get_level_values(1) else None
227
+ if sym_data is None or sym_data.empty:
228
+ continue
229
+ df = sym_data.reset_index()
230
+ df.rename(columns={"Date": "date", "Open": "open", "High": "high",
231
+ "Low": "low", "Close": "close", "Volume": "volume"}, inplace=True)
232
+ df["date"] = pd.to_datetime(df["date"]).dt.tz_localize(None)
233
+ df = df[["date", "open", "high", "low", "close", "volume"]].dropna(subset=["close"])
234
+ df = df[df["close"] > 0].reset_index(drop=True)
235
+ if not df.empty:
236
+ result[sym] = df
237
+ except Exception:
238
+ continue
239
+
240
+ return result
241
+
242
+
243
+ # ── Supabase row builder ───────────────────────────────────────────────────────
244
+
245
+ def _f(v) -> float | None:
246
+ try:
247
+ x = float(v)
248
+ return None if x != x else round(x, 6) # NaN → None
249
+ except (TypeError, ValueError):
250
+ return None
251
+
252
+
253
+ def df_to_rows(bare_sym: str, df: pd.DataFrame) -> list[dict]:
254
+ rows = []
255
+ for _, r in df.iterrows():
256
+ rows.append({
257
+ "symbol": bare_sym,
258
+ "date": str(r["date"].date()),
259
+ "open": _f(r.get("open")),
260
+ "high": _f(r.get("high")),
261
+ "low": _f(r.get("low")),
262
+ "close": _f(r.get("close")),
263
+ "volume": int(r["volume"]) if r.get("volume") and r["volume"] == r["volume"] else None,
264
+ })
265
+ return rows
266
+
267
+
268
+ def write_to_supabase(bare_sym: str, df: pd.DataFrame) -> int:
269
+ """Write all rows for one symbol to Supabase. Returns rows written."""
270
+ rows = df_to_rows(bare_sym, df)
271
+ written = 0
272
+ for i in range(0, len(rows), 1000):
273
+ chunk = rows[i : i + 1000]
274
+ if sb_upsert("stock_prices", chunk, conflict_cols="symbol,date"):
275
+ written += len(chunk)
276
+ return written
277
+
278
+
279
+ # ── Main backfill logic ────────────────────────────────────────────────────────
280
+
281
+ BATCH_SIZE = 50 # symbols per yfinance download call
282
+ SKIP_IF_ROWS = 200 # skip symbol if Supabase already has this many rows
283
+
284
+
285
+ def run_backfill():
286
+ t_start = time.time()
287
+
288
+ # 1. Get Nifty 500 list
289
+ constituents = fetch_nifty500_list()
290
+ total = len(constituents)
291
+ log.info(f"Total symbols to process: {total}")
292
+
293
+ # 2. Check existing Supabase data (resume support)
294
+ log.info("Checking existing Supabase data…")
295
+ all_bare = [c["bare"] for c in constituents]
296
+ existing = sb_get_symbol_counts(all_bare)
297
+ to_process = [c for c in constituents if existing.get(c["bare"], 0) < SKIP_IF_ROWS]
298
+ skipped = total - len(to_process)
299
+ log.info(f" Already populated: {skipped} | Need to fetch: {len(to_process)}")
300
+
301
+ if not to_process:
302
+ log.info("All symbols already have sufficient data. Nothing to do.")
303
+ return
304
+
305
+ # 3. Populate stocks metadata (FK requirement)
306
+ log.info("Upserting stocks metadata…")
307
+ stock_meta = [
308
+ {
309
+ "symbol": c["bare"],
310
+ "company_name": c["company_name"] or c["bare"],
311
+ "exchange": "NSE",
312
+ "sector": c["sector"] or "Unknown",
313
+ }
314
+ for c in constituents
315
+ ]
316
+ # Batch upsert in groups of 200
317
+ for i in range(0, len(stock_meta), 200):
318
+ sb_upsert("stocks", stock_meta[i : i + 200])
319
+ log.info(f" Upserted {len(stock_meta)} stock metadata rows")
320
+
321
+ # 4. Download + write in batches
322
+ symbols_ns = [c["symbol_ns"] for c in to_process]
323
+ bare_map = {c["symbol_ns"]: c["bare"] for c in to_process}
324
+
325
+ total_rows = 0
326
+ done = 0
327
+ errors = 0
328
+
329
+ for batch_start in range(0, len(symbols_ns), BATCH_SIZE):
330
+ batch = symbols_ns[batch_start : batch_start + BATCH_SIZE]
331
+ log.info(
332
+ f"Batch {batch_start // BATCH_SIZE + 1}/{(len(symbols_ns) + BATCH_SIZE - 1) // BATCH_SIZE}"
333
+ f" ({batch_start + 1}–{min(batch_start + BATCH_SIZE, len(symbols_ns))} of {len(symbols_ns)})"
334
+ f" symbols: {', '.join(s.replace('.NS','') for s in batch[:5])}{'…' if len(batch) > 5 else ''}"
335
+ )
336
+
337
+ dfs = download_batch(batch)
338
+
339
+ for sym_ns in batch:
340
+ bare = bare_map[sym_ns]
341
+ df = dfs.get(sym_ns)
342
+ if df is None or df.empty:
343
+ log.warning(f" No data for {sym_ns}")
344
+ errors += 1
345
+ done += 1
346
+ continue
347
+
348
+ n = write_to_supabase(bare, df)
349
+ total_rows += n
350
+ done += 1
351
+ log.info(f" [{done}/{len(symbols_ns)}] {bare:<18} {len(df)} rows → Supabase {n} upserted")
352
+
353
+ # Brief pause between batches to be polite to Yahoo Finance
354
+ time.sleep(1)
355
+
356
+ elapsed = time.time() - t_start
357
+ log.info(
358
+ f"\n{'='*60}\n"
359
+ f" Backfill complete in {elapsed:.0f}s\n"
360
+ f" Symbols processed : {done}\n"
361
+ f" Rows written : {total_rows:,}\n"
362
+ f" Errors / no data : {errors}\n"
363
+ f"{'='*60}"
364
+ )
365
+
366
+
367
+ if __name__ == "__main__":
368
+ run_backfill()