Spaces:
Sleeping
Sleeping
Upload 52 files
Browse filesFiles changed (9)
- app.py+10
- models/nifty_opening_mfe_regressor/outputs/latest_prediction.csv+1-1
- models/nifty_opening_mfe_regressor/outputs/mfe_live_history.csvAdded+2
- models/tomorrow_latest_prediction.csv+1-1
- models/tomorrow_prediction_history.parquet+2-2
- models/yahoo_history_cache.sqlite3+2-2
- nifty_backend/__pycache__/runtime.cpython-311.pyc+2-2
- nifty_backend/runtime.py+89
- scraper.pyAdded+97
37 unmodified lines383940414243623 unmodified lines66766866937 unmodified linesKotakNeoSessionRequired,kotak_neo_manager,)app = FastAPI(title="NIFTY 50 Forecaster Backend")623 unmodified linessession_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),) -> dict:return refresh_market_close_data(session_date=session_date)37 unmodified lines38394041424344623 unmodified lines66866967067167267367467567667767867937 unmodified linesKotakNeoSessionRequired,kotak_neo_manager,)from scraper import get_stock_infoapp = FastAPI(title="NIFTY 50 Forecaster Backend")623 unmodified linessession_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),) -> dict:return refresh_market_close_data(session_date=session_date)@app.get("/api/info/{ticker}")def stock_info(ticker: str) -> dict:data = get_stock_info(ticker)if "error" in data:raise HTTPException(status_code=404, detail=data["error"])return data
12input_date,first5_start,first5_end,first5_close,predicted_up_points,predicted_down_points2026-06-09,2026-06-09 09:15:00,2026-06-09 09:19:00,23234.849609375,63.15162391627527,71.578848691434112input_date,first5_start,first5_end,first5_close,predicted_up_points,predicted_down_points2026-06-11,2026-06-11 09:15:00,2026-06-11 09:19:00,23112.650390625,97.5434972440442,76.48054546871592
12input_date,first5_start,first5_end,first5_close,predicted_up_points,predicted_down_points
2026-06-11,2026-06-11 09:15:00,2026-06-11 09:19:00,23112.650390625,97.5434972440442,76.4805454687159212input_date,target_date,prediction,prob_up,confidence,threshold,model_name,source_model,validation_accuracy,test_accuracy,source2026-06-11,2026-06-12,DOWN,0.46778826961945674,0.5322117303805433,0.534,nifty_tomorrow_direction_model,locked_multiwindow_nifty50_ensemble_v2,0.5886524822695035,0.7070707070707071,live12input_date,target_date,prediction,prob_up,confidence,threshold,model_name,source_model,validation_accuracy,test_accuracy,source2026-06-12,2026-06-15,UP,0.5568798000516237,0.5568798000516237,0.534,nifty_tomorrow_direction_model,locked_multiwindow_nifty50_ensemble_v2,0.5886524822695035,0.7070707070707071,live
123version https://git-lfs.github.com/spec/v1oid sha256:89f100aced6b7ff9d8d0c5cd0ce10a00e5a402bbf935949fac103b8a33d0dbcasize 8273123version https://git-lfs.github.com/spec/v1oid sha256:ba49d81e54af07af6cd1b7defee306558ab4377dc09888b1d8452446aae13f4asize 8300
123version https://git-lfs.github.com/spec/v1oid sha256:75c3f55a2adee670c10dbadd1c998d3ce773ed067c8e196ed2c7539ca6f8eb87size 397312123version https://git-lfs.github.com/spec/v1oid sha256:8198956ffb6a3aca16eabd5f6fc4aa188ba816d324a7f9987caf631d1b0eea14size 421888
123version https://git-lfs.github.com/spec/v1oid sha256:eac2a9d465d264f6ebb982a4f2b7fbd61ef4db81c5a3549543b07cb103b8d680size 138158123version https://git-lfs.github.com/spec/v1oid sha256:83ba07597a5f92396b6297f2fe401f732a2a617e82c6fd3311f2d3e5537475e5size 143804
59 unmodified lines606162636465879 unmodified lines945946947948949950316 unmodified lines126712681269127012711272169 unmodified lines14421443144414451446144773 unmodified lines15211522152315241525152624 unmodified lines15511552155315541555155659 unmodified linesMFE_SUMMARY_PATH = MFE_OUTPUT_DIR / "summary.json"MFE_LATEST_PATH = MFE_OUTPUT_DIR / "latest_prediction.csv"MFE_TEST_PREDICTIONS_PATH = MFE_OUTPUT_DIR / "test_predictions.csv"TPLUS1_MODEL_PATH = MODEL_DIR / "nifty_1420_tplus1_logistic_model.joblib"TPLUS1_LATEST_PATH = MODEL_DIR / "tplus1_latest_prediction.csv"TPLUS1_SUMMARY_PATH = MODEL_DIR / "tplus1_summary.json"879 unmodified lines}def _minute_frame_for_tplus1() -> pd.DataFrame:minute = pd.read_parquet(NIFTY_1M_PATH)minute = minute.copy()316 unmodified lines_file_cache_key(NIFTY_1M_PATH),_file_cache_key(LIVE_ACCURACY_PATH),_file_cache_key(TOMORROW_PREDICTION_HISTORY_PATH),)with _dashboard_payload_lock:return copy.deepcopy(_dashboard_payload_cached(key))169 unmodified linestomorrow_test = load_tomorrow_test_predictions()tomorrow_history = _load_prediction_history(TOMORROW_PREDICTION_HISTORY_PATH)tplus1_test = load_tplus1_test_predictions()daily = pd.read_parquet(NIFTY_1D_PATH)daily["date"] = pd.to_datetime(daily["date"], errors="coerce")daily = daily.sort_values("date").tail(180)73 unmodified lines"latest": tplus1_latest,"summary": tplus1_summary,},},"metrics": metrics,"models": model_metrics,24 unmodified linesmerged = merged.drop_duplicates(subset=["date"], keep="last").sort_values("date").reset_index(drop=True)merged.to_parquet(OPENING_DATASET_PATH, index=False, compression="zstd")prediction = predict_row(row)return prediction59 unmodified lines6061626364656667879 unmodified lines947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026316 unmodified lines134313441345134613471348134913501351169 unmodified lines1521152215231524152515261527152873 unmodified lines160216031604160516061607160816091610161124 unmodified lines163616371638163916401641164216431644164559 unmodified linesMFE_SUMMARY_PATH = MFE_OUTPUT_DIR / "summary.json"MFE_LATEST_PATH = MFE_OUTPUT_DIR / "latest_prediction.csv"MFE_TEST_PREDICTIONS_PATH = MFE_OUTPUT_DIR / "test_predictions.csv"MFE_MODEL_PATH = MFE_OUTPUT_DIR / "nifty_opening_mfe_regressor.joblib"MFE_LIVE_HISTORY_PATH = MFE_OUTPUT_DIR / "mfe_live_history.csv"TPLUS1_MODEL_PATH = MODEL_DIR / "nifty_1420_tplus1_logistic_model.joblib"TPLUS1_LATEST_PATH = MODEL_DIR / "tplus1_latest_prediction.csv"TPLUS1_SUMMARY_PATH = MODEL_DIR / "tplus1_summary.json"879 unmodified lines}def load_mfe_summary() -> dict[str, Any]:if MFE_SUMMARY_PATH.exists():return json.loads(MFE_SUMMARY_PATH.read_text(encoding="utf-8"))return {}def latest_mfe_prediction() -> dict[str, Any]:if MFE_LATEST_PATH.exists():row = pd.read_csv(MFE_LATEST_PATH).iloc[-1].to_dict()return {k: (None if pd.isna(v) else v) for k, v in row.items()}summary = load_mfe_summary()return {"input_date": summary.get("latest_input_date"),"first5_start": summary.get("latest_first5_start"),"first5_end": summary.get("latest_first5_end"),"predicted_up_points": summary.get("latest_predicted_up_points"),"predicted_down_points": summary.get("latest_predicted_down_points"),}def refresh_mfe_prediction(session_date: date | None = None) -> dict[str, Any]:if not MFE_MODEL_PATH.exists():return {}payload = joblib.load(MFE_MODEL_PATH)up_model = payload["up_model"]down_model = payload["down_model"]up_features = payload["up_features"]down_features = payload["down_features"]up_calib = payload["up_calibration"]down_calib = payload["down_calibration"]dataset = pd.read_parquet(OPENING_DATASET_PATH)dataset["_session_date"] = pd.to_datetime(dataset["date"], errors="coerce").dt.normalize()if session_date is not None:latest_df = dataset[dataset["_session_date"].dt.date == session_date].tail(1)else:latest_df = dataset.tail(1)if latest_df.empty:return {}raw_up = float(np.clip(up_model.predict(latest_df[up_features])[0], 0.0, None))pred_up = float(np.clip((raw_up * up_calib["scale"]) + up_calib["offset"], 0.0, None))raw_down = float(np.clip(down_model.predict(latest_df[down_features])[0], 0.0, None))pred_down = float(np.clip((raw_down * down_calib["scale"]) + down_calib["offset"], 0.0, None))out = {"input_date": latest_df["_session_date"].dt.date.iloc[0].isoformat(),"first5_start": str(latest_df["first5_start"].iloc[0]),"first5_end": str(latest_df["first5_end"].iloc[0]),"first5_close": float(latest_df["first5_close"].iloc[0]),"predicted_up_points": pred_up,"predicted_down_points": pred_down,}pd.DataFrame([out]).to_csv(MFE_LATEST_PATH, index=False)# Append to live historylive_df = pd.DataFrame([out])if MFE_LIVE_HISTORY_PATH.exists():try:existing = pd.read_csv(MFE_LIVE_HISTORY_PATH)# Avoid duplicates if refreshed multiple times in the same sessionexisting = existing[existing["input_date"] != out["input_date"]]pd.concat([existing, live_df], ignore_index=True).to_csv(MFE_LIVE_HISTORY_PATH, index=False)except Exception:live_df.to_csv(MFE_LIVE_HISTORY_PATH, index=False)else:live_df.to_csv(MFE_LIVE_HISTORY_PATH, index=False)clear_dashboard_payload_cache()return outdef _minute_frame_for_tplus1() -> pd.DataFrame:minute = pd.read_parquet(NIFTY_1M_PATH)minute = minute.copy()316 unmodified lines_file_cache_key(NIFTY_1M_PATH),_file_cache_key(LIVE_ACCURACY_PATH),_file_cache_key(TOMORROW_PREDICTION_HISTORY_PATH),_file_cache_key(MFE_SUMMARY_PATH),_file_cache_key(MFE_LATEST_PATH),_file_cache_key(MFE_MODEL_PATH),)with _dashboard_payload_lock:return copy.deepcopy(_dashboard_payload_cached(key))169 unmodified linestomorrow_test = load_tomorrow_test_predictions()tomorrow_history = _load_prediction_history(TOMORROW_PREDICTION_HISTORY_PATH)tplus1_test = load_tplus1_test_predictions()mfe_summary = load_mfe_summary()mfe_latest = latest_mfe_prediction()daily = pd.read_parquet(NIFTY_1D_PATH)daily["date"] = pd.to_datetime(daily["date"], errors="coerce")daily = daily.sort_values("date").tail(180)73 unmodified lines"latest": tplus1_latest,"summary": tplus1_summary,},"mfe": {"latest": mfe_latest,"summary": mfe_summary,},},"metrics": metrics,"models": model_metrics,24 unmodified linesmerged = merged.drop_duplicates(subset=["date"], keep="last").sort_values("date").reset_index(drop=True)merged.to_parquet(OPENING_DATASET_PATH, index=False, compression="zstd")prediction = predict_row(row)try:refresh_mfe_prediction(session_date=session_date)except Exception as exc:print(f"MFE refresh failed: {exc}", flush=True)return prediction
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import requestsfrom bs4 import BeautifulSoup
def get_stock_info(ticker): url = f"https://www.screener.in/company/{ticker.upper()}/consolidated/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) if response.status_code == 404: url = f"https://www.screener.in/company/{ticker.upper()}/" response = requests.get(url, headers=headers) if response.status_code != 200: return {"error": f"Failed to fetch data for {ticker.upper()}. Status {response.status_code}"} soup = BeautifulSoup(response.text, 'html.parser') data = { "ticker": ticker.upper(), "key_metrics": {}, "pros": [], "cons": [], "growth": [], "history": {} } # 1. Key Metrics top_ratios = soup.find('ul', id='top-ratios') if top_ratios: for li in top_ratios.find_all('li'): n_span = li.find('span', class_='name') v_span = li.find('span', class_='value') if n_span and v_span: name = n_span.text.strip().replace('₹', 'Rs.') val = ' '.join(v_span.text.split()).replace('₹', 'Rs.') data["key_metrics"][name] = val # 2. Pros/Cons analysis = soup.find('section', id='analysis') if analysis: pros = analysis.find('div', class_='pros') if pros: data["pros"] = [li.text.strip() for li in pros.find_all('li')] cons = analysis.find('div', class_='cons') if cons: data["cons"] = [li.text.strip() for li in cons.find_all('li')] # 3. Growth Metrics ranges = soup.find_all('table', class_='ranges-table') for table in ranges: th = table.find('th') if not th: continue metric = th.text.strip() for tr in table.find_all('tr')[1:]: tds = tr.find_all('td') if len(tds) == 2: data["growth"].append({ "Metric": metric, "Period": tds[0].text.strip(), "Value": tds[1].text.strip() }) # 4. Tables sections = { 'quarters': 'Quarterly Results', 'profit-loss': 'Profit & Loss', 'balance-sheet': 'Balance Sheet', 'cash-flow': 'Cash Flows', 'ratios': 'Financial Ratios', 'shareholding': 'Shareholding Pattern' } for sec_id, sec_name in sections.items(): sec = soup.find('section', id=sec_id) if not sec: continue tbl = sec.find('table') if not tbl: continue thead = tbl.find('thead') headers = [th.text.strip().replace('₹', 'Rs.') for th in thead.find_all('th')] if thead else [] rows = [] for tr in tbl.find('tbody').find_all('tr'): cols = [td.text.strip().replace('₹', 'Rs.') for td in tr.find_all('td')] rname = tr.find('td', class_='text') if rname: cols[0] = rname.text.replace('+', '').strip() if cols: rows.append(cols) if headers and len(headers) == len(rows[0]) - 1: headers.insert(0, 'Metric') data["history"][sec_id] = { "title": sec_name, "headers": headers, "rows": rows } return dataapp.py+10
models/nifty_opening_mfe_regressor/outputs/latest_prediction.csv+1-1
models/nifty_opening_mfe_regressor/outputs/mfe_live_history.csvAdded+2
models/tomorrow_latest_prediction.csv+1-1
models/tomorrow_prediction_history.parquet+2-2
models/yahoo_history_cache.sqlite3+2-2
nifty_backend/__pycache__/runtime.cpython-311.pyc+2-2
nifty_backend/runtime.py+89
scraper.pyAdded+97