Spaces:
Sleeping
Sleeping
Upload 12 files
Browse filesFiles changed (12)
- app.py+32
- feature_pipeline.pyAdded+313
- forecaster_cli.pyAdded+282
- imputer_large.pklAdded+3
- imputer_mid.pklAdded+3
- imputer_small.pklAdded+3
- rf_model_large.pklAdded+3
- rf_model_mid.pklAdded+3
- rf_model_small.pklAdded+3
- scaler_large.pklAdded+3
- scaler_mid.pklAdded+3
- scaler_small.pklAdded+3
7 unmodified lines891011121398 unmodified lines1121131141151161177 unmodified linesfrom forecaster_engine import generate_predictionsfrom signal_generator import generate_signalsfrom t5_engine import run_t5_pipelineIST = ZoneInfo("Asia/Kolkata")MARKET_CLOSE_BUFFER = time(15, 45) # Update runs after 3:45 PM98 unmodified linesreturn {"status": "triggered", "message": "T5 update pipeline started in the background."}# ── NEW: Signal Generator Endpoints ──────────────────────────────────────────@app.get("/signals")7 unmodified lines89101112131498 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481497 unmodified linesfrom forecaster_engine import generate_predictionsfrom signal_generator import generate_signalsfrom t5_engine import run_t5_pipelinefrom forecaster_cli import run_daemonIST = ZoneInfo("Asia/Kolkata")MARKET_CLOSE_BUFFER = time(15, 45) # Update runs after 3:45 PM98 unmodified linesreturn {"status": "triggered", "message": "T5 update pipeline started in the background."}# ── NEW: NIFTY 50 Multi-Tier Forecaster Endpoints ─────────────────────────────@app.get("/nifty50")def get_nifty50_predictions():"""Get the latest high-conviction BUY predictions for NIFTY 50."""nifty_file = os.path.join(os.path.dirname(__file__), "nifty50_predictions.json")if not os.path.exists(nifty_file):raise HTTPException(status_code=404, detail="NIFTY 50 predictions not yet generated")with open(nifty_file, "r") as f:data = json.load(f)# Filter for high conviction trades (BUY)high_conviction = [p for p in data.get("predictions", []) if p.get("Decision") == "BUY"]return {"last_updated": data.get("last_updated"),"total_analyzed": len(data.get("predictions", [])),"high_conviction_buys": len(high_conviction),"predictions": high_conviction}@app.post("/cron/nifty50_update")def nifty50_update_trigger(background_tasks: BackgroundTasks):"""Trigger the multi-tier Random Forest NIFTY 50 forecasting daemon.Should be called every two weeks."""background_tasks.add_task(run_daemon)return {"status": "triggered", "message": "NIFTY 50 forecasting daemon started in the background."}# ── NEW: Signal Generator Endpoints ──────────────────────────────────────────@app.get("/signals")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
import reimport threadingfrom datetime import datetime
import numpy as npimport pandas as pdimport requestsfrom bs4 import BeautifulSoupfrom requests.adapters import HTTPAdapterfrom urllib3.util.retry import Retry
class _ThreadLocalSessionFactory: def __init__(self, headers=None, timeout=(3.5, 10.0), pool_maxsize=32): self._local = threading.local() self.headers = headers or {"User-Agent": "Mozilla/5.0"} self.timeout = timeout self.pool_maxsize = pool_maxsize
def get(self) -> requests.Session: if not hasattr(self._local, "session"): session = requests.Session() session.headers.update(self.headers) retry = Retry( total=2, connect=2, read=2, backoff_factor=0.15, status_forcelist=(429, 500, 502, 503, 504), allowed_methods=frozenset(["GET"]), raise_on_status=False, ) adapter = HTTPAdapter( max_retries=retry, pool_connections=self.pool_maxsize, pool_maxsize=self.pool_maxsize, ) session.mount("https://", adapter) session.mount("http://", adapter) self._local.session = session return self._local.session
class ScreenerScraper: def __init__(self): self._session_factory = _ThreadLocalSessionFactory() self.timeout = self._session_factory.timeout
def _session(self) -> requests.Session: return self._session_factory.get()
@staticmethod def _make_soup(html: str): try: return BeautifulSoup(html, "lxml") except Exception: return BeautifulSoup(html, "html.parser")
def _fetch_html(self, ticker: str, consolidated: bool = True) -> str: t = ticker.upper().strip() urls = [ f"https://www.screener.in/company/{t}/consolidated/", f"https://www.screener.in/company/{t}/", ] if consolidated else [ f"https://www.screener.in/company/{t}/", f"https://www.screener.in/company/{t}/consolidated/", ]
last_status = None last_text = "" session = self._session()
for url in urls: try: response = session.get(url, timeout=self.timeout) last_status = response.status_code last_text = response.text if response.status_code == 200: return response.text except requests.RequestException: continue
raise RuntimeError(f"Failed to fetch data for {t}. Last status: {last_status}")
@staticmethod def _clean_text(value: str) -> str: return " ".join(value.split()).replace("₹", "Rs.")
def get_stock_info(self, ticker): html = self._fetch_html(ticker, consolidated=True) soup = self._make_soup(html)
data = { "ticker": ticker.upper(), "key_metrics": {}, "history": {}, "documents": {}, }
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.get_text(strip=True).replace("₹", "Rs.") val = self._clean_text(v_span.get_text(" ", strip=True)) data["key_metrics"][name] = val
sections = { "quarters": "Quarterly Results", "profit-loss": "Profit & Loss", "balance-sheet": "Balance Sheet", "cash-flow": "Cash Flows", "ratios": "Financial Ratios", }
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_list = [th.get_text(" ", strip=True) for th in thead.find_all("th")] if thead else [] tbody = tbl.find("tbody") if not tbody: continue
rows = [] for tr in tbody.find_all("tr"): tds = tr.find_all("td") if not tds: continue cols = [td.get_text(" ", strip=True) for td in tds] rname = tr.find("td", class_="text") if rname and cols: cols[0] = rname.get_text(" ", strip=True).replace("+", "").strip() rows.append(cols)
if not rows: continue
if headers_list: if len(headers_list) == len(rows[0]) - 1: headers_list = ["Metric"] + headers_list elif len(headers_list) == len(rows[0]): headers_list[0] = "Metric" else: headers_list = ["Metric"] + headers_list[1:]
data["history"][sec_id] = { "title": sec_name, "headers": headers_list, "rows": rows, }
docs = soup.find_all("div", class_="documents") for doc in docs: h3 = doc.find("h3") if not h3: continue sec_name = h3.get_text(" ", strip=True) data["documents"][sec_name] = [] ul = doc.find("ul", class_="list-links") if not ul: continue for li in ul.find_all("li"): text_div = li.find("div") a = li.find("a") date_str = " ".join(text_div.get_text(" ", strip=True).replace("\n", " ").split()) if text_div else "" link_str = a.get_text(" ", strip=True) if a else "" if link_str and date_str.endswith(link_str): date_str = date_str[:-len(link_str)].strip() data["documents"][sec_name].append({"date": date_str, "title": link_str})
return data
class FeatureEngineer: @staticmethod def clean_numeric(val): if pd.isna(val): return np.nan if isinstance(val, (int, float, np.number)): return float(val) if not isinstance(val, str): return val val = val.replace(",", "").replace("%", "").replace("₹", "").replace("Rs.", "").strip() if val in ["-", ""]: return np.nan try: return float(val) except ValueError: return val
@staticmethod def parse_date(date_str): try: return pd.to_datetime(date_str, format="%b %Y") except Exception: return pd.to_datetime(date_str, errors="coerce")
@staticmethod def _section_to_frame(sec_id, sec_data): headers = sec_data.get("headers") or [] rows = sec_data.get("rows") or [] if len(headers) < 2 or not rows: return None
df = pd.DataFrame(rows, columns=headers[: len(rows[0])]) if "Metric" not in df.columns: df.columns = ["Metric"] + list(df.columns[1:])
df = df.set_index("Metric").transpose().reset_index().rename(columns={"index": "Date_Str"}) metric_cols = [c for c in df.columns if c != "Date_Str"]
if metric_cols: cleaned = df[metric_cols].replace( {",": "", "%": "", "₹": "", "Rs.": ""}, regex=True, ) df[metric_cols] = cleaned.apply(pd.to_numeric, errors="coerce")
df["Date"] = df["Date_Str"].map(FeatureEngineer.parse_date) df = df.dropna(subset=["Date"]).sort_values("Date").set_index("Date") df = df.drop(columns=["Date_Str"])
prefix = sec_id.split("-")[0].upper() + "_" df.columns = [f"{prefix}{col}" for col in df.columns] return df
def build_features(self, data): ticker = data["ticker"]
df_dict = {} for sec_id, sec_data in data["history"].items(): df = self._section_to_frame(sec_id, sec_data) if df is not None and not df.empty: df_dict[sec_id] = df
if "quarters" not in df_dict or df_dict["quarters"].empty: print("No quarterly data found.") return None
main_df = df_dict["quarters"].copy()
for sec_id in ["profit-loss", "balance-sheet", "cash-flow", "ratios"]: if sec_id in df_dict and not df_dict[sec_id].empty: annual_df = df_dict[sec_id].sort_index() main_df = pd.merge_asof( main_df.sort_index(), annual_df, left_index=True, right_index=True, direction="backward", )
announcements = data.get("documents", {}).get("Announcements", []) if announcements: event_dates = [] for ann in announcements: ds = ann.get("date", "") if "20" in ds: parsed = pd.to_datetime(ds, errors="coerce") if pd.notnull(parsed): event_dates.append(parsed) if event_dates: events_series = pd.Series(1, index=pd.DatetimeIndex(event_dates)) quarterly_counts = events_series.resample("Q").sum() main_df["ANN_COUNT"] = 0 for q_date, count in quarterly_counts.items(): valid_idx = main_df.index[main_df.index <= q_date] if len(valid_idx) > 0: main_df.loc[valid_idx[-1], "ANN_COUNT"] += int(count)
for k, v in data.get("key_metrics", {}).items(): main_df[f"STATIC_{k.replace(' ', '_')}"] = self.clean_numeric(v)
main_df["Ticker"] = ticker
if "QUARTERS_Sales" in main_df.columns: main_df["QUARTERS_Sales_YoY_Growth"] = main_df["QUARTERS_Sales"].pct_change(periods=4) * 100
return main_df
def run_pipeline(ticker): print(f"[{ticker}] Scraping data...") data = ScreenerScraper().get_stock_info(ticker)
print(f"[{ticker}] Engineering features...") df = FeatureEngineer().build_features(data)
if df is not None: filename = f"{ticker}_features.parquet" print(f"[{ticker}] Exporting to {filename}...") df.to_parquet(filename, engine="pyarrow", index=True) print("Success!") return filename
print("Failed to build features.") return None
if __name__ == "__main__": import sys
ticker = sys.argv[1] if len(sys.argv) > 1 else "TCS" run_pipeline(ticker)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282import argparseimport pandas as pdimport numpy as npimport concurrent.futuresimport timeimport joblibimport datetimeimport osimport warnings
warnings.filterwarnings('ignore')
from feature_pipeline import ScreenerScraper
TIERS = { "Large": "https://archives.nseindia.com/content/indices/ind_nifty100list.csv", "Mid": "https://archives.nseindia.com/content/indices/ind_niftymidcap150list.csv", "Small": "https://archives.nseindia.com/content/indices/ind_niftysmallcap250list.csv", "Nifty50": "https://archives.nseindia.com/content/indices/ind_nifty50list.csv"}
def get_current_historic_val(table_data, row_name): if not table_data: return np.nan for row in table_data.get('rows', []): if row and row[0].lower() == row_name.lower(): for val_raw in reversed(row[1:]): val = str(val_raw).replace(',', '').replace('%', '').strip() if val not in ['-', '']: try: return float(val) except: continue return np.nan
def fetch_live_features(ticker): try: scraper = ScreenerScraper() data = None for _ in range(3): try: data = scraper.get_stock_info(ticker) if "error" in data and "429" in data["error"]: time.sleep(1.5) continue break except Exception: time.sleep(1) if not data or "error" in data: return None pl = data['history'].get('profit-loss', {}) bs = data['history'].get('balance-sheet', {}) ratios = data['history'].get('ratios', {}) sales_row = None for row in pl.get('rows', []): if row and row[0].lower() == 'sales': sales_row = row break sales = np.nan prev_sales = np.nan if sales_row and len(sales_row) >= 3: try: sales = float(str(sales_row[-1]).replace(',', '').strip()) prev_sales = float(str(sales_row[-2]).replace(',', '').strip()) except: pass opm = get_current_historic_val(pl, 'OPM %') net_profit = get_current_historic_val(pl, 'Net Profit') equity = get_current_historic_val(bs, 'Equity Capital') reserves = get_current_historic_val(bs, 'Reserves') borrowings = get_current_historic_val(bs, 'Borrowings') roce = get_current_historic_val(ratios, 'ROCE %') sales_growth = ((sales - prev_sales) / prev_sales * 100) if pd.notnull(prev_sales) and prev_sales > 0 else np.nan total_eq = equity + reserves if pd.notnull(equity) and pd.notnull(reserves) else np.nan roe = (net_profit / total_eq * 100) if pd.notnull(total_eq) and total_eq > 0 else np.nan debt_to_equity = (borrowings / total_eq) if pd.notnull(total_eq) and total_eq > 0 else np.nan pe = np.nan for metric in data.get('metrics', []): if metric['name'] == 'Stock P/E': pe = metric['value'] break return { 'Ticker': ticker, 'Sales_Growth': sales_growth, 'OPM': opm, 'ROCE': roce, 'ROE': roe, 'Debt_to_Equity': debt_to_equity, 'PE_Ratio': pe } except Exception: return None
def get_market_cap_tier(ticker): print(f"[{ticker}] Resolving market cap classification from NSE servers...") try: large = pd.read_csv(TIERS["Large"])['Symbol'].tolist() if ticker in large: return "Large" mid = pd.read_csv(TIERS["Mid"])['Symbol'].tolist() if ticker in mid: return "Mid" small = pd.read_csv(TIERS["Small"])['Symbol'].tolist() if ticker in small: return "Small" except Exception as e: print(f"Warning: Could not fetch NSE lists ({e}). Defaulting to Small Cap.") return "Small" # Default to small cap model for everything else
def generate_reasoning(features, tier, prob): reasons = [] if tier == "Large": if pd.notnull(features.get('Sales_Growth')): if features['Sales_Growth'] < 5: reasons.append(f"Weak Sales Growth ({features['Sales_Growth']:.1f}%) drags down Large Cap momentum.") elif features['Sales_Growth'] > 15: reasons.append(f"Strong Sales Growth ({features['Sales_Growth']:.1f}%) is an excellent indicator for Large Caps.") if pd.notnull(features.get('ROE')) and features['ROE'] > 20: reasons.append(f"High ROE ({features['ROE']:.1f}%) shows efficient capital use.") elif tier == "Small": if pd.notnull(features.get('Debt_to_Equity')): if features['Debt_to_Equity'] > 1.5: reasons.append(f"Dangerously high Debt/Equity ({features['Debt_to_Equity']:.2f}) signals severe structural risk.") elif features['Debt_to_Equity'] < 0.5: reasons.append(f"Low Debt/Equity ({features['Debt_to_Equity']:.2f}) provides strong survival padding.") if pd.notnull(features.get('OPM')) and features['OPM'] < 10: reasons.append(f"Low margins ({features['OPM']:.1f}%) leave little room for error.") elif tier == "Mid": reasons.append("Mid caps exhibit inverted return logic. Metrics are volatile and evaluated in aggregate.") if not reasons: reasons.append("Fundamentals are mixed or average, showing no extreme strengths or weaknesses.") return " ".join(reasons)
def run_inference(ticker): tier = get_market_cap_tier(ticker) print(f"[{ticker}] Classified as: {tier} Cap") print(f"[{ticker}] Extracting live fundamental data...") features = fetch_live_features(ticker) if not features: print(f"[{ticker}] Error: Could not extract live data.") return df = pd.DataFrame([features]) model_features = ['Sales_Growth', 'OPM', 'ROCE', 'ROE', 'Debt_to_Equity', 'PE_Ratio'] X = df[model_features].copy() try: model = joblib.load(f'rf_model_{tier.lower()}.pkl') imputer = joblib.load(f'imputer_{tier.lower()}.pkl') scaler = joblib.load(f'scaler_{tier.lower()}.pkl') except Exception as e: print(f"Error loading models: {e}") return X_imputed = imputer.transform(X) X_scaled = scaler.transform(X_imputed) prob = model.predict_proba(X_scaled)[0][1] if prob > 0.65: decision = "BUY" else: decision = "PASS" reasoning = generate_reasoning(features, tier, prob) print("\n" + "="*50) print(f" FORECAST FOR {ticker} ({tier} Cap Model)") print("="*50) print(f" Decision: {decision} (Confidence: {prob*100:.1f}%)") print(f" Reasoning: {reasoning}") print("-" * 50) print(f" Sales Growth: {features['Sales_Growth']:.2f}%") print(f" ROE: {features['ROE']:.2f}%") print(f" ROCE: {features['ROCE']:.2f}%") print(f" Debt/Equity: {features['Debt_to_Equity']:.2f}") print(f" OPM: {features['OPM']:.2f}%") print("="*50 + "\n") return {"Ticker": ticker, "Tier": tier, "Decision": decision, **features}
def run_daemon(): print("Starting NIFTY 50 Forecasting Daemon...") try: df_nifty = pd.read_csv(TIERS["Nifty50"]) tickers = df_nifty['Symbol'].tolist() except Exception as e: print(f"Could not load NIFTY 50 tickers: {e}") return print(f"[{datetime.datetime.now()}] Waking up to process NIFTY 50...") # We don't fetch market cap tiers because NIFTY 50 is all Large Cap # Verify rate limit status first with a test call print("Testing connection...") test_feat = fetch_live_features("RELIANCE") if not test_feat: print(f"[{datetime.datetime.now()}] Error: IP Rate Limit Block detected on startup. Will not proceed.") return results = [] total = len(tickers) processed = 0 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = {executor.submit(fetch_live_features, ticker): ticker for ticker in tickers} for future in concurrent.futures.as_completed(futures): res = future.result() processed += 1 if res: results.append(res) pct = int((processed / total) * 100) bar = '#' * (pct // 5) + '-' * (20 - (pct // 5)) print(f"\r[NIFTY 50] {bar} {pct}% ({processed}/{total})", end='', flush=True) print("\n", flush=True) if results: df = pd.DataFrame(results) features = ['Sales_Growth', 'OPM', 'ROCE', 'ROE', 'Debt_to_Equity', 'PE_Ratio'] try: # NIFTY 50 is strictly Large Cap model = joblib.load('rf_model_large.pkl') imputer = joblib.load('imputer_large.pkl') scaler = joblib.load('scaler_large.pkl') X = df[features].copy() X_imputed = imputer.transform(X) X_scaled = scaler.transform(X_imputed) probs = model.predict_proba(X_scaled)[:, 1] df['Confidence'] = probs df['Decision'] = df['Confidence'].apply(lambda x: "BUY" if x > 0.65 else "PASS") # Generate reasoning for each reasonings = [] for _, row in df.iterrows(): feat_dict = { 'Sales_Growth': row['Sales_Growth'], 'ROE': row['ROE'], 'ROCE': row['ROCE'], 'Debt_to_Equity': row['Debt_to_Equity'], 'OPM': row['OPM'] } r = generate_reasoning(feat_dict, "Large", row['Confidence']) reasonings.append(r) df['Reasoning'] = reasonings # Format report and save to JSON report = df[['Ticker', 'Decision', 'Confidence', 'Reasoning', 'Sales_Growth', 'ROE', 'Debt_to_Equity', 'OPM']] report_dict = report.to_dict(orient='records') import json with open("nifty50_predictions.json", "w") as f: json.dump({"last_updated": datetime.datetime.now().isoformat(), "predictions": report_dict}, f, indent=4) print(f"[{datetime.datetime.now()}] Successfully generated nifty50_predictions.json with {len(df)} stocks.", flush=True) except Exception as e: print(f"Error during NIFTY 50 prediction: {e}", flush=True) else: print(f"[{datetime.datetime.now()}] Error: Failed to extract live data for all 50 stocks (Likely IP Rate Limit Block). Skipping report generation.", flush=True) print("Daemon run completed.", flush=True)
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Multi-Cap Stock Forecasting Engine") parser.add_argument("--ticker", type=str, help="Run an on-demand forecast for a specific ticker") parser.add_argument("--daemon", action="store_true", help="Run the background 14-day loop for NIFTY 50") args = parser.parse_args() if args.daemon: run_daemon() elif args.ticker: run_inference(args.ticker.upper()) else: print("Please provide a --ticker or run with --daemon. Use -h for help.")123version https://git-lfs.github.com/spec/v1oid sha256:2894a48dbcb70bc99e657795b4973954e4599b5c83e97be9623d8c15a029990asize 855123version https://git-lfs.github.com/spec/v1oid sha256:455258365334b9db6b2af0c00433d97bc2c8eb5e29702d9ed95d9737874d4251size 855123version https://git-lfs.github.com/spec/v1oid sha256:d65a78b810f54e372e91724d3bd8d481f2806b5c2f4ed76c3c7377115be5bd49size 855123version https://git-lfs.github.com/spec/v1oid sha256:c0231dc1ab983560de50edcbff6599edc673f9c2f528e8cd2c479d6421e963a7size 150537123version https://git-lfs.github.com/spec/v1oid sha256:07e84e6700854d7545cb81d1c434f7c70173d92a4b84a1e2ced40bfee5a84464size 135177123version https://git-lfs.github.com/spec/v1oid sha256:481d91e098ec92aecaf115f137ef18da64e715a6ceaf2c44b38890967ce15c64size 155337123version https://git-lfs.github.com/spec/v1oid sha256:bcc1ca9f607af2f9fed7c3da780c9006eabc622cc8e3f3afb3176c04de4f286asize 727123version https://git-lfs.github.com/spec/v1oid sha256:ec9343fa00941cae7852d91a0775ac01ac6ad94b692cdbaee12a2116e774f182size 727123version https://git-lfs.github.com/spec/v1oid sha256:2b648ba253b033f0b37d397e27d9e7152b0019c77cf7d5d95f148d93e8eaa0d6size 727app.py+32
feature_pipeline.pyAdded+313
forecaster_cli.pyAdded+282
imputer_large.pklAdded+3
imputer_mid.pklAdded+3
imputer_small.pklAdded+3
rf_model_large.pklAdded+3
rf_model_mid.pklAdded+3
rf_model_small.pklAdded+3
scaler_large.pklAdded+3
scaler_mid.pklAdded+3
scaler_small.pklAdded+3