Spaces:
Running
Running
# main.py | |
from fastapi import FastAPI, HTTPException, Depends | |
from fastapi.middleware.cors import CORSMiddleware # If Streamlit runs on a different port | |
from typing import Dict, List | |
from services.data_fetcher import IndianMarketDataFetcher | |
from services.analyzer import IndianFinancialAnalyzer | |
from services.swarm_service import create_indian_market_swarm | |
from models.market_data import StockDataResponse, IndexData, SectorPerformance, EconomicIndicators | |
from models.analysis import StockAnalysisResponse, SwarmAnalysisResponse, InvestmentRecommendationResponse | |
from config import NIFTY50_COMPANIES | |
app = FastAPI(title="Indian Market Analysis API", version="1.0.0") | |
# Configure CORS if needed (e.g., if Streamlit runs on localhost:8501) | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], # Restrict this in production! | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
# Dependency Injection for services | |
def get_data_fetcher(): | |
return IndianMarketDataFetcher() | |
def get_analyzer(): | |
return IndianFinancialAnalyzer() | |
# --- API Endpoints --- | |
async def root(): | |
return {"message": "Indian Market Analysis API"} | |
# --- Market Data Endpoints --- | |
async def get_market_indices(fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher)): | |
"""Get live market indices data.""" | |
return fetcher.get_market_indices() | |
async def get_sector_performance(fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher)): | |
"""Get sector performance data.""" | |
return fetcher.get_sector_performance() | |
async def get_economic_indicators(analyzer: IndianFinancialAnalyzer = Depends(get_analyzer)): | |
"""Get key economic indicators.""" | |
return EconomicIndicators( | |
repo_rate=analyzer.rbi_repo_rate, | |
inflation_rate=analyzer.indian_inflation_rate | |
) | |
# --- Stock Data Endpoints --- | |
async def get_nifty50_list(fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher)): | |
"""Get the list of Nifty 50 companies.""" | |
return fetcher.get_nifty50_companies() | |
async def get_stock_data(symbol: str, period: str = "1y", fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher)): | |
"""Get detailed stock data for a given symbol.""" | |
stock_data = fetcher.get_stock_data(symbol, period) | |
if not stock_data: | |
raise HTTPException(status_code=404, detail=f"Data for stock symbol {symbol} could not be fetched.") | |
return stock_data | |
# --- Analysis Endpoints --- | |
async def analyze_stock(symbol: str, period: str = "1y", | |
fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher), | |
analyzer: IndianFinancialAnalyzer = Depends(get_analyzer)): | |
"""Perform basic financial analysis on a stock.""" | |
stock_data = fetcher.get_stock_data(symbol, period) | |
if not stock_data: | |
raise HTTPException(status_code=404, detail=f"Data for stock symbol {symbol} could not be fetched.") | |
company_name = NIFTY50_COMPANIES.get(symbol, symbol) | |
return analyzer.analyze_indian_stock(stock_data, company_name) | |
async def run_swarm_analysis(symbol: str, period: str = "1y", | |
fetcher: IndianMarketDataFetcher = Depends(get_data_fetcher), | |
analyzer: IndianFinancialAnalyzer = Depends(get_analyzer)): | |
"""Run AI swarm analysis on a stock.""" | |
stock_data = fetcher.get_stock_data(symbol, period) | |
if not stock_data: | |
return SwarmAnalysisResponse(status="error", error=f"Data for stock symbol {symbol} could not be fetched.") | |
company_name = NIFTY50_COMPANIES.get(symbol, symbol) | |
# Perform basic analysis first | |
basic_analysis_response = analyzer.analyze_indian_stock(stock_data, company_name) | |
basic_analysis_text = basic_analysis_response.basic_analysis | |
# Prepare data for swarm analysis | |
market_data_summary = f""" | |
Stock: {company_name} ({symbol}) | |
Current Price: ₹{stock_data.history.get('Close', [0])[-1] if stock_data.history.get('Close') else 'N/A'} | |
Market Data Analysis: {basic_analysis_text} | |
""" | |
# Run swarm analysis | |
return create_indian_market_swarm(market_data_summary, company_name) | |
async def get_investment_recommendation(analyzer: IndianFinancialAnalyzer = Depends(get_analyzer)): | |
"""Get general investment recommendations.""" | |
return analyzer.generate_investment_recommendation() | |
# --- Utility Endpoints --- | |
async def health_check(): | |
"""Health check endpoint.""" | |
return {"status": "ok"} | |