eshan6704 commited on
Commit
a931ad4
·
verified ·
1 Parent(s): 7847b89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -84
app.py CHANGED
@@ -1,25 +1,22 @@
1
- import os
2
- import importlib
3
  from fastapi import FastAPI, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from pydantic import BaseModel
6
- from typing import Optional, Dict, Callable
7
 
8
- # ---------- Dynamically import all .py files ----------
9
- current_dir = os.path.dirname(os.path.abspath(__file__))
10
- modules = {}
11
- for file in os.listdir(current_dir):
12
- if file.endswith(".py") and file != "app.py":
13
- name = file[:-3]
14
- try:
15
- modules[name] = importlib.import_module(name)
16
- print(f"Imported module: {name}")
17
- except Exception as e:
18
- print(f"Failed importing {name}: {e}")
19
 
20
- # ---------- FastAPI ----------
21
- app = FastAPI(title="Stock Backend")
22
 
 
23
  app.add_middleware(
24
  CORSMiddleware,
25
  allow_origins=["*"],
@@ -27,20 +24,7 @@ app.add_middleware(
27
  allow_headers=["*"],
28
  )
29
 
30
- # ---------- Request Model ----------
31
- class FetchRequest(BaseModel):
32
- req_type: str # like 'info', 'intraday', 'nse_open', etc.
33
- mode: str # 'stock' or 'index'
34
- name: str # symbol or index name
35
- date_start: str # dd-mm-yyyy
36
- date_end: str # dd-mm-yyyy
37
-
38
- # ---------- Health Check ----------
39
- @app.get("/")
40
- def health():
41
- return {"status": "ok", "service": "backend alive"}
42
-
43
- # ---------- STOCK & INDEX Request Mapping ----------
44
  STOCK_REQ = [
45
  "info", "intraday", "daily", "nse_eq", "qresult", "result",
46
  "balance", "cashflow", "dividend", "split", "other", "stock_hist"
@@ -54,63 +38,72 @@ INDEX_REQ = [
54
  "index_pe_pb_div", "index_total_returns"
55
  ]
56
 
57
- # ---------- Handler Router ----------
58
- ROUTER: Dict[str, Callable[[FetchRequest], str]] = {}
 
 
 
 
 
59
 
60
- # STOCK ROUTES
61
- if 'stock' in modules:
62
- ROUTER.update({
63
- "info": lambda r: modules['yahooinfo'].fetch_info(r.name),
64
- "intraday": lambda r: modules['stock'].fetch_intraday(r.name, r.date_start, r.date_end),
65
- "daily": lambda r: modules['stock'].fetch_daily(r.name, r.date_start, r.date_end),
66
- "nse_eq": lambda r: modules['eq_html'].build_eq_html(r.name),
67
- "qresult": lambda r: modules['stock'].fetch_qresult(r.name),
68
- "result": lambda r: modules['stock'].fetch_result(r.name),
69
- "balance": lambda r: modules['stock'].fetch_balance(r.name),
70
- "cashflow": lambda r: modules['stock'].fetch_cashflow(r.name),
71
- "dividend": lambda r: modules['stock'].fetch_dividend(r.name),
72
- "split": lambda r: modules['stock'].fetch_split(r.name),
73
- "other": lambda r: modules['stock'].fetch_other(r.name),
74
- })
75
 
76
- if 'nsepython' in modules:
77
- ROUTER["stock_hist"] = lambda r: modules['nsepython'].nse_stock_hist(r.date_start, r.date_end, r.name).to_html()
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- # INDEX ROUTES
80
- if 'indices_html' in modules:
81
- ROUTER["indices"] = lambda r: modules['indices_html'].build_indices_html()
82
- if 'index_live_html' in modules:
83
- ROUTER["nse_open"] = lambda r: modules['index_live_html'].build_index_live_html()
84
- if 'preopen_html' in modules:
85
- ROUTER["nse_preopen"] = lambda r: modules['preopen_html'].build_preopen_html()
86
- if 'build_nse_fno' in modules:
87
- ROUTER["nse_fno"] = lambda r: modules['build_nse_fno'].nse_fno_html(r.date_end, r.name)
88
- if 'nsepython' in modules:
89
- ROUTER.update({
90
- "nse_events": lambda r: modules['nsepython'].nse_events().to_html(),
91
- "nse_fiidii": lambda r: modules['nsepython'].nse_fiidii().to_html(),
92
- "nse_future": lambda r: modules['nsepython'].nse_future(r.name),
93
- "nse_highlow": lambda r: modules['nsepython'].nse_highlow(r.date_end).to_html(),
94
- "stock_highlow": lambda r: modules['nsepython'].stock_highlow(r.date_end).to_html(),
95
- "index_history": lambda r: modules['nsepython'].index_history(r.name, r.date_start, r.date_end).to_html(),
96
- "largedeals_historical": lambda r: modules['nsepython'].nse_largedeals_historical(r.date_start, r.date_end).to_html(),
97
- "index_pe_pb_div": lambda r: modules['nsepython'].index_pe_pb_div(r.name, r.date_start, r.date_end).to_html(),
98
- "index_total_returns": lambda r: modules['nsepython'].index_total_returns(r.name, r.date_start, r.date_end).to_html(),
99
- })
100
- if 'bhavcopy_html' in modules:
101
- ROUTER["nse_bhav"] = lambda r: modules['bhavcopy_html'].build_bhavcopy_html(r.date_end)
102
 
103
- # ---------- Fetch Endpoint ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  @app.post("/api/fetch")
105
  def fetch_data(req: FetchRequest):
106
- handler = ROUTER.get(req.req_type)
107
- if not handler:
108
- raise HTTPException(status_code=400, detail=f"No handler for req_type: {req.req_type}")
109
-
110
- try:
111
- result = handler(req)
112
- if 'common' in modules and hasattr(modules['common'], 'wrap'):
113
- return modules['common'].wrap(result)
114
- return result
115
- except Exception as e:
116
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
 
4
 
5
+ # Import all modules from same folder
6
+ from stock import *
7
+ from indices_html import *
8
+ from index_live_html import *
9
+ from preopen_html import *
10
+ from eq_html import *
11
+ from bhavcopy_html import *
12
+ from nsepython import *
13
+ from yahooinfo import *
14
+ from build_nse_fno import *
15
+ from common import wrap
16
 
17
+ app = FastAPI(title="Stock / Index Backend")
 
18
 
19
+ # ---------- CORS ----------
20
  app.add_middleware(
21
  CORSMiddleware,
22
  allow_origins=["*"],
 
24
  allow_headers=["*"],
25
  )
26
 
27
+ # ---------- Valid req_type options ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  STOCK_REQ = [
29
  "info", "intraday", "daily", "nse_eq", "qresult", "result",
30
  "balance", "cashflow", "dividend", "split", "other", "stock_hist"
 
38
  "index_pe_pb_div", "index_total_returns"
39
  ]
40
 
41
+ # ---------- Request Model ----------
42
+ class FetchRequest(BaseModel):
43
+ mode: str # stock / index
44
+ req_type: str
45
+ name: str
46
+ date_start: str # dd-mm-yyyy
47
+ date_end: str # dd-mm-yyyy
48
 
49
+ # ---------- Health ----------
50
+ @app.get("/")
51
+ def health():
52
+ return {"status": "ok", "service": "backend alive"}
53
+
54
+ # ---------- STOCK Handlers ----------
55
+ def handle_stock(req: FetchRequest):
56
+ if req.req_type not in STOCK_REQ:
57
+ raise HTTPException(status_code=400, detail=f"Invalid stock req_type: {req.req_type}")
 
 
 
 
 
 
58
 
59
+ t = req.req_type.lower()
60
+ if t == "info": return wrap(yahooinfo.fetch_info(req.name))
61
+ if t == "intraday": return wrap(stock.fetch_intraday(req.name, req.date_start, req.date_end))
62
+ if t == "daily": return wrap(stock.fetch_daily(req.name, req.date_start, req.date_end))
63
+ if t == "nse_eq": return eq_html.build_eq_html(req.name)
64
+ if t == "qresult": return wrap(stock.fetch_qresult(req.name))
65
+ if t == "result": return wrap(stock.fetch_result(req.name))
66
+ if t == "balance": return wrap(stock.fetch_balance(req.name))
67
+ if t == "cashflow": return wrap(stock.fetch_cashflow(req.name))
68
+ if t == "dividend": return wrap(stock.fetch_dividend(req.name))
69
+ if t == "split": return wrap(stock.fetch_split(req.name))
70
+ if t == "other": return wrap(stock.fetch_other(req.name))
71
+ if t == "stock_hist": return nsepython.nse_stock_hist(req.date_start, req.date_end, req.name).to_html()
72
+ return wrap(f"<h3>No handler for stock req_type: {t}</h3>")
73
 
74
+ # ---------- INDEX Handlers ----------
75
+ def handle_index(req: FetchRequest):
76
+ if req.req_type not in INDEX_REQ:
77
+ raise HTTPException(status_code=400, detail=f"Invalid index req_type: {req.req_type}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ t = req.req_type.lower()
80
+ if t == "indices": return indices_html.build_indices_html()
81
+ if t == "nse_open": return index_live_html.build_index_live_html()
82
+ if t == "nse_preopen": return preopen_html.build_preopen_html()
83
+ if t == "nse_fno": return build_nse_fno.nse_fno_html(req.date_end, req.name)
84
+ if t == "nse_fiidii": return nsepython.nse_fiidii().to_html()
85
+ if t == "nse_events": return nsepython.nse_events().to_html()
86
+ if t == "nse_future": return wrap(nsepython.nse_future(req.name))
87
+ if t == "nse_highlow": return nsepython.nse_highlow(req.date_end).to_html()
88
+ if t == "stock_highlow": return nsepython.stock_highlow(req.date_end).to_html()
89
+ if t == "nse_bhav": return bhavcopy_html.build_bhavcopy_html(req.date_end)
90
+ if t == "nse_largedeals": return nsepython.nse_largedeals().to_html()
91
+ if t == "nse_bulkdeals": return nsepython.nse_bulkdeals().to_html()
92
+ if t == "nse_blockdeals": return nsepython.nse_blockdeals().to_html()
93
+ if t == "nse_most_active": return nsepython.nse_most_active().to_html()
94
+ if t == "index_history": return nsepython.index_history("NIFTY", req.date_start, req.date_end).to_html()
95
+ if t == "largedeals_historical": return nsepython.nse_largedeals_historical(req.date_start, req.date_end).to_html()
96
+ if t == "index_pe_pb_div": return nsepython.index_pe_pb_div("NIFTY", req.date_start, req.date_end).to_html()
97
+ if t == "index_total_returns": return nsepython.index_total_returns("NIFTY", req.date_start, req.date_end).to_html()
98
+ return wrap(f"<h3>No handler for index req_type: {t}</h3>")
99
+
100
+ # ---------- Main POST Endpoint ----------
101
  @app.post("/api/fetch")
102
  def fetch_data(req: FetchRequest):
103
+ mode = req.mode.lower()
104
+ if mode == "stock":
105
+ return handle_stock(req)
106
+ elif mode == "index":
107
+ return handle_index(req)
108
+ else:
109
+ raise HTTPException(status_code=400, detail=f"Invalid mode: {req.mode}")