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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -160
app.py CHANGED
@@ -1,21 +1,25 @@
 
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
- from typing import Optional
5
-
6
- import stock
7
- import indices_html
8
- import index_live_html
9
- import preopen_html
10
- import eq_html
11
- import bhavcopy_html
12
- import nsepython
13
- import yahooinfo
14
- import build_nse_fno
15
-
 
 
 
16
  app = FastAPI(title="Stock Backend")
17
 
18
- # ---------- CORS ----------
19
  app.add_middleware(
20
  CORSMiddleware,
21
  allow_origins=["*"],
@@ -25,157 +29,88 @@ app.add_middleware(
25
 
26
  # ---------- Request Model ----------
27
  class FetchRequest(BaseModel):
28
- req_type: str # From STOCK_REQ or INDEX_REQ
29
- name: str
30
- date_start: str # dd-mm-yyyy
31
- date_end: str # dd-mm-yyyy
32
-
33
- # ---------- STOCK Handlers ----------
34
- def stock_info(req: FetchRequest):
35
- return common.wrap(yahooinfo.fetch_info(req.name))
36
-
37
- def stock_intraday(req: FetchRequest):
38
- return common.wrap(stock.fetch_intraday(req.name, req.date_start, req.date_end))
39
-
40
- def stock_daily(req: FetchRequest):
41
- return common.wrap(stock.fetch_daily(req.name, req.date_start, req.date_end))
42
-
43
- def stock_nse_eq(req: FetchRequest):
44
- return eq_html.build_eq_html(req.name)
45
-
46
- def stock_qresult(req: FetchRequest):
47
- return common.wrap(stock.fetch_qresult(req.name))
48
-
49
- def stock_result(req: FetchRequest):
50
- return common.wrap(stock.fetch_result(req.name))
51
-
52
- def stock_balance(req: FetchRequest):
53
- return common.wrap(stock.fetch_balance(req.name))
54
-
55
- def stock_cashflow(req: FetchRequest):
56
- return common.wrap(stock.fetch_cashflow(req.name))
57
-
58
- def stock_dividend(req: FetchRequest):
59
- return common.wrap(stock.fetch_dividend(req.name))
60
-
61
- def stock_split(req: FetchRequest):
62
- return common.wrap(stock.fetch_split(req.name))
63
-
64
- def stock_other(req: FetchRequest):
65
- return common.wrap(stock.fetch_other(req.name))
66
-
67
- def stock_hist(req: FetchRequest):
68
- return nsepython.nse_stock_hist(req.date_start, req.date_end, req.name).to_html()
69
-
70
-
71
- # ---------- INDEX Handlers ----------
72
- def index_indices(req: FetchRequest):
73
- return indices_html.build_indices_html()
74
-
75
- def index_nse_open(req: FetchRequest):
76
- return index_live_html.build_index_live_html()
77
-
78
- def index_nse_preopen(req: FetchRequest):
79
- return preopen_html.build_preopen_html()
80
-
81
- def index_nse_fno(req: FetchRequest):
82
- return build_nse_fno.nse_fno_html(req.date_end, req.name)
83
-
84
- def index_nse_fiidii(req: FetchRequest):
85
- return nsepython.nse_fiidii().to_html()
86
-
87
- def index_nse_events(req: FetchRequest):
88
- return nsepython.nse_events().to_html()
89
-
90
- def index_nse_future(req: FetchRequest):
91
- return common.wrap(nsepython.nse_future(req.name))
92
-
93
- def index_nse_bhav(req: FetchRequest):
94
- return bhavcopy_html.build_bhavcopy_html(req.date_end)
95
-
96
- def index_nse_highlow(req: FetchRequest):
97
- return nsepython.nse_highlow(req.date_end).to_html()
98
-
99
- def index_stock_highlow(req: FetchRequest):
100
- return nsepython.stock_highlow(req.date_end).to_html()
101
-
102
- def index_history(req: FetchRequest):
103
- return nsepython.index_history("NIFTY", req.date_start, req.date_end).to_html()
104
-
105
- def index_nse_largedeals(req: FetchRequest):
106
- return nsepython.nse_largedeals().to_html()
107
-
108
- def index_nse_most_active(req: FetchRequest):
109
- return nsepython.nse_most_active().to_html()
110
-
111
- def index_largedeals_historical(req: FetchRequest):
112
- return nsepython.nse_largedeals_historical(req.date_start, req.date_end).to_html()
113
-
114
- def index_nse_bulkdeals(req: FetchRequest):
115
- return nsepython.nse_bulkdeals().to_html()
116
-
117
- def index_nse_blockdeals(req: FetchRequest):
118
- return nsepython.nse_blockdeals().to_html()
119
-
120
- def index_pe_pb_div(req: FetchRequest):
121
- return nsepython.index_pe_pb_div("NIFTY", req.date_start, req.date_end).to_html()
122
-
123
- def index_total_returns(req: FetchRequest):
124
- return nsepython.index_total_returns("NIFTY", req.date_start, req.date_end).to_html()
125
-
126
-
127
- # ---------- ROUTER MAPPING ----------
128
- ROUTER = {
129
- # STOCK
130
- "info": stock_info,
131
- "intraday": stock_intraday,
132
- "daily": stock_daily,
133
- "nse_eq": stock_nse_eq,
134
- "qresult": stock_qresult,
135
- "result": stock_result,
136
- "balance": stock_balance,
137
- "cashflow": stock_cashflow,
138
- "dividend": stock_dividend,
139
- "split": stock_split,
140
- "other": stock_other,
141
- "stock_hist": stock_hist,
142
-
143
- # INDEX
144
- "indices": index_indices,
145
- "nse_open": index_nse_open,
146
- "nse_preopen": index_nse_preopen,
147
- "nse_fno": index_nse_fno,
148
- "nse_fiidii": index_nse_fiidii,
149
- "nse_events": index_nse_events,
150
- "nse_future": index_nse_future,
151
- "nse_bhav": index_nse_bhav,
152
- "nse_highlow": index_nse_highlow,
153
- "stock_highlow": index_stock_highlow,
154
- "index_history": index_history,
155
- "nse_largedeals": index_nse_largedeals,
156
- "nse_most_active": index_nse_most_active,
157
- "largedeals_historical": index_largedeals_historical,
158
- "nse_bulkdeals": index_nse_bulkdeals,
159
- "nse_blockdeals": index_nse_blockdeals,
160
- "index_pe_pb_div": index_pe_pb_div,
161
- "index_total_returns": index_total_returns
162
- }
163
-
164
- # ---------- MAIN ENDPOINT ----------
165
  @app.post("/api/fetch")
166
  def fetch_data(req: FetchRequest):
167
  handler = ROUTER.get(req.req_type)
168
  if not handler:
169
- raise HTTPException(status_code=400, detail=f"Unsupported req_type: {req.req_type}")
 
170
  try:
171
- html_content = handler(req)
172
- return {
173
- "success": True,
174
- "req_type": req.req_type,
175
- "name": req.name,
176
- "date_start": req.date_start,
177
- "date_end": req.date_end,
178
- "html": html_content
179
- }
180
  except Exception as e:
181
  raise HTTPException(status_code=500, detail=str(e))
 
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=["*"],
 
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"
47
+ ]
48
+
49
+ INDEX_REQ = [
50
+ "indices", "nse_open", "nse_preopen", "nse_fno", "nse_fiidii",
51
+ "nse_events", "nse_future", "nse_bhav", "nse_highlow","stock_highlow",
52
+ "index_history", "nse_largedeals", "nse_most_active",
53
+ "largedeals_historical", "nse_bulkdeals", "nse_blockdeals",
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))