Spaces:
Sleeping
Sleeping
Download app.py from ghstedpixel/BRIE: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/ghstedpixel/BRIE/resolve/main/app.py
- Command line
-
hf download hf://spaces/ghstedpixel/BRIE/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ghstedpixel/BRIE/resolve/main/app.py
15.5 kB
| import os | |
| import pickle | |
| import subprocess | |
| import sqlite3 | |
| from datetime import datetime | |
| import duckdb | |
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| import pandas_ta as ta | |
| import plotly.graph_objects as go | |
| import yfinance as yf | |
| from xgboost import XGBRegressor | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from dotenv import load_dotenv | |
| # --- HEALTH AGENT BLOCK --- | |
| os.environ["PYTHONUNBUFFERED"] = "1" | |
| def run_agent(): | |
| print("π©Ί Starting Health Agent...") | |
| result = subprocess.run( | |
| ["python", "health_agent.py"], | |
| cwd=".", | |
| capture_output=False, | |
| text=True | |
| ) | |
| print(f"π©Ί Agent complete: {result.returncode}") | |
| run_agent() | |
| print("π©Ί Health Agent launched & complete!") | |
| load_dotenv() | |
| # --- UNIFIED PATHS & CONSTANTS --- | |
| WATCHLIST_DB = os.path.join(os.getcwd(), "watchlist_manager.db") | |
| DB_PATH = "/tmp/brie_brain.db" | |
| MODEL_PATH = "/tmp/brie_model.pkl" | |
| MOMENTUM_THRESHOLD = 75 | |
| OVERBOUGHT_RSI = 70 | |
| FEATURES = [ | |
| "rsi", "macd_h", "ema_20_dist", "ema_50_dist", "vwap_dist", | |
| "atr_pct", "bb_width", "vol_spike", "ret_1d", "ret_5d", | |
| "day_of_week", "sentiment_score", "gap_pct", "vix_level" | |
| ] | |
| SECTOR_ETFS = ["XLF", "XLK", "XLE", "XLY", "XLP", "XLV", "XLI", "XLU", "XLB", "XLRE", "XLC"] | |
| VOLATILITY_INDEX = "^VIX" | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| HF_REPO_ID = os.getenv("HF_REPO_ID") | |
| # --- DATABASE HELPERS --- | |
| def get_current_watchlist(): | |
| conn = sqlite3.connect(WATCHLIST_DB) | |
| cursor = conn.cursor() | |
| cursor.execute("CREATE TABLE IF NOT EXISTS watchlist (ticker TEXT PRIMARY KEY)") | |
| cursor.execute("SELECT ticker FROM watchlist ORDER BY ticker") | |
| data = cursor.fetchall() | |
| conn.close() | |
| return pd.DataFrame(data, columns=["Ticker"]) | |
| def add_ticker_to_db(ticker): | |
| if ticker: | |
| ticker = ticker.upper().strip() | |
| conn = sqlite3.connect(WATCHLIST_DB) | |
| cursor = conn.cursor() | |
| cursor.execute("INSERT OR IGNORE INTO watchlist (ticker) VALUES (?)", (ticker,)) | |
| conn.commit() | |
| conn.close() | |
| return get_current_watchlist(), "" | |
| def remove_ticker_from_db(ticker): | |
| if ticker: | |
| ticker = ticker.upper().strip() | |
| conn = sqlite3.connect(WATCHLIST_DB) | |
| cursor = conn.cursor() | |
| cursor.execute("DELETE FROM watchlist WHERE ticker = ?", (ticker,)) | |
| conn.commit() | |
| conn.close() | |
| return get_current_watchlist(), "" | |
| def trigger_discord(): | |
| try: | |
| from brie_agent import run_alpaca_briefing | |
| watchlist_df = get_current_watchlist() | |
| current_list = watchlist_df["Ticker"].tolist() | |
| if not current_list: | |
| return "β οΈ Watchlist is empty." | |
| return str(run_alpaca_briefing(current_list)) | |
| except Exception as e: | |
| return f"β Bridge Error: {str(e)}" | |
| # --- CLOUD SYNC & DB INIT --- | |
| def init_db(): | |
| with duckdb.connect(DB_PATH) as con: | |
| feat_cols = ", ".join([f'"{f}" FLOAT' for f in FEATURES]) | |
| con.execute( | |
| f""" | |
| CREATE TABLE IF NOT EXISTS feature_store ( | |
| ticker TEXT, | |
| timestamp TIMESTAMP, | |
| {feat_cols}, | |
| target_next_day_ret FLOAT, | |
| PRIMARY KEY (ticker, timestamp) | |
| ) | |
| """ | |
| ) | |
| con.execute( | |
| """ | |
| CREATE TABLE IF NOT EXISTS performance_logs ( | |
| ticker TEXT, | |
| timestamp TIMESTAMP, | |
| predicted_ret FLOAT, | |
| entry_price FLOAT, | |
| actual_ret FLOAT, | |
| is_verified BOOLEAN DEFAULT FALSE | |
| ) | |
| """ | |
| ) | |
| def load_from_cloud(): | |
| if not HF_TOKEN or not HF_REPO_ID: | |
| return | |
| try: | |
| for f in ["brie_model.pkl", "brie_brain.db"]: | |
| hf_hub_download( | |
| repo_id=HF_REPO_ID, | |
| filename=f, | |
| local_dir="/tmp", | |
| repo_type="dataset", | |
| token=HF_TOKEN | |
| ) | |
| print("β Cloud models/data loaded") | |
| except Exception as e: | |
| print(f"β οΈ Cloud load failed: {e}") | |
| def save_to_cloud(): | |
| if not HF_TOKEN or not HF_REPO_ID: | |
| return "β οΈ HF_TOKEN missing" | |
| api = HfApi() | |
| try: | |
| for path, filename in [(MODEL_PATH, "brie_model.pkl"), (DB_PATH, "brie_brain.db")]: | |
| if os.path.exists(path): | |
| api.upload_file( | |
| path_or_fileobj=path, | |
| path_in_repo=filename, | |
| repo_id=HF_REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN | |
| ) | |
| return "β Sync Success" | |
| except Exception as e: | |
| return f"β Sync Failed: {str(e)[:30]}" | |
| # --- ANALYTICS ENGINE --- | |
| def fetch_history_yf(ticker, period="5y", interval="1d"): | |
| try: | |
| df = yf.download( | |
| ticker, | |
| period=period, | |
| interval=interval, | |
| auto_adjust=False, | |
| progress=False | |
| ) | |
| if df.empty: | |
| return pd.DataFrame() | |
| if isinstance(df.columns, pd.MultiIndex): | |
| df.columns = df.columns.get_level_values(0) | |
| df.columns = [str(c).lower().replace(" ", "_") for c in df.columns] | |
| df.index = pd.to_datetime(df.index).tz_localize(None) | |
| return df[["open", "high", "low", "close", "volume"]] | |
| except: | |
| return pd.DataFrame() | |
| def build_feature_set(df, sentiment_val=0.0, labeling=False, vix_df=None): | |
| if len(df) < 100: | |
| return pd.DataFrame() | |
| ind = pd.DataFrame(index=df.index) | |
| ind["rsi"] = ta.rsi(df["close"], length=14).fillna(50.0) | |
| macd = ta.macd(df["close"]) | |
| ind["macd_h"] = macd.iloc[:, 1].fillna(0.0) if macd is not None else 0.0 | |
| bbands = ta.bbands(df["close"], length=20, std=2) | |
| ind["bb_width"] = ((bbands.iloc[:, 2] - bbands.iloc[:, 0]) / bbands.iloc[:, 1]).fillna(0.0) if bbands is not None else 0.0 | |
| for length in [20, 50]: | |
| ema = ta.ema(df["close"], length=length) | |
| ind[f"ema_{length}_dist"] = ((df["close"] - ema) / ema).fillna(0.0) | |
| vwap = ta.vwap(df["high"], df["low"], df["close"], df["volume"]) | |
| ind["vwap_dist"] = ((df["close"] - vwap) / vwap).fillna(0.0) | |
| ind["atr_pct"] = (ta.atr(df["high"], df["low"], df["close"]) / df["close"]).fillna(0.0) | |
| ind["vol_spike"] = (df["volume"] / df["volume"].rolling(20).mean()).fillna(1.0) | |
| ind["ret_1d"] = df["close"].pct_change(1).fillna(0.0) | |
| ind["ret_5d"] = df["close"].pct_change(5).fillna(0.0) | |
| ind["day_of_week"] = df.index.dayofweek.astype(float) | |
| ind["sentiment_score"] = float(sentiment_val) | |
| ind["gap_pct"] = ((df["open"] - df["close"].shift(1)) / df["close"].shift(1)).fillna(0.0) | |
| if vix_df is not None and not vix_df.empty: | |
| ind["vix_level"] = vix_df["close"].reindex(df.index, method="ffill").fillna(20.0) | |
| else: | |
| ind["vix_level"] = pd.Series(20.0, index=df.index) | |
| if labeling: | |
| ind["target_next_day_ret"] = df["close"].pct_change(1).shift(-1) | |
| cols = FEATURES + (["target_next_day_ret"] if labeling else []) | |
| return ind[cols].dropna() | |
| def calculate_momentum_score(pred_return, rsi, vol_spike): | |
| normalized_pred = np.clip((pred_return + 5) * 10, 0, 100) | |
| vol_bonus = 15 if vol_spike > 1.2 else 0 | |
| rsi_penalty = (rsi - OVERBOUGHT_RSI) * 2 if rsi > OVERBOUGHT_RSI else 0 | |
| return np.clip((normalized_pred * 0.7) + vol_bonus - rsi_penalty, 0, 100) | |
| def log_prediction_to_db(ticker, pred_val, entry_price): | |
| init_db() | |
| with duckdb.connect(DB_PATH) as con: | |
| con.execute( | |
| "INSERT INTO performance_logs (ticker, timestamp, predicted_ret, entry_price) VALUES (?, ?, ?, ?)", | |
| (ticker, datetime.now(), pred_val, entry_price) | |
| ) | |
| def update_performance_ledger(): | |
| init_db() | |
| with duckdb.connect(DB_PATH) as con: | |
| pending = con.execute( | |
| "SELECT * FROM performance_logs WHERE is_verified = FALSE AND timestamp < (CURRENT_TIMESTAMP - INTERVAL '1 DAY')" | |
| ).df() | |
| for _, row in pending.iterrows(): | |
| current_bars = fetch_history_yf(row["ticker"], period="1d") | |
| if not current_bars.empty: | |
| actual_ret = ((current_bars["close"].iloc[-1] - row["entry_price"]) / row["entry_price"]) * 100 | |
| con.execute( | |
| "UPDATE performance_logs SET actual_ret = ?, is_verified = TRUE WHERE ticker = ? AND timestamp = ?", | |
| (actual_ret, row["ticker"], row["timestamp"]) | |
| ) | |
| return "β Ledger Updated" | |
| def get_performance_dashboard(): | |
| update_performance_ledger() | |
| init_db() | |
| with duckdb.connect(DB_PATH) as con: | |
| df = con.execute("SELECT * FROM performance_logs WHERE is_verified = TRUE").df() | |
| if df.empty: | |
| return "### β οΈ No verified data yet. (Wait 24h)", None | |
| df["error"] = df["predicted_ret"] - df["actual_ret"] | |
| win_rate = (np.sign(df["predicted_ret"]) == np.sign(df["actual_ret"])).mean() * 100 | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter(x=df["predicted_ret"], y=df["actual_ret"], mode="markers", name="Predictions", marker=dict(color="#FFC107"))) | |
| fig.update_layout(template="plotly_dark", title="Prediction vs. Actual", xaxis_title="AI Forecast %", yaxis_title="Actual Result %") | |
| stats = f"### Directional Win Rate: {win_rate:.1f}% | N={len(df)}" | |
| return stats, fig | |
| def run_incremental_training(batch_str): | |
| tickers = [t.strip().upper() for t in batch_str.split(",") if t.strip()] | |
| vix_data = fetch_history_yf(VOLATILITY_INDEX) | |
| yield "π₯ Syncing Data..." | |
| all_data = [] | |
| for t in tickers: | |
| bars = fetch_history_yf(t) | |
| if bars.empty: | |
| continue | |
| f_set = build_feature_set(bars, vix_df=vix_data, labeling=True) | |
| if f_set.empty: | |
| continue | |
| f_set["ticker"] = t | |
| f_set = f_set.reset_index().rename(columns={"Date": "timestamp", "index": "timestamp"}) | |
| all_data.append(f_set) | |
| if not all_data: | |
| yield "β No data found." | |
| return | |
| df = pd.concat(all_data, ignore_index=True) | |
| init_db() | |
| with duckdb.connect(DB_PATH) as con: | |
| con.register("df_tmp", df) | |
| con.execute("INSERT OR IGNORE INTO feature_store SELECT ticker, timestamp, " + ", ".join([f'"{f}"' for f in FEATURES]) + ", target_next_day_ret FROM df_tmp") | |
| data = con.execute("SELECT * FROM feature_store").df() | |
| yield "π§ Training XGBoost..." | |
| model = XGBRegressor(n_estimators=200, max_depth=7, learning_rate=0.02) | |
| model.fit(data[FEATURES], data["target_next_day_ret"]) | |
| with open(MODEL_PATH, "wb") as f: | |
| pickle.dump(model, f) | |
| yield f"β Refreshed! {save_to_cloud()}" | |
| def analyze_asset(ticker): | |
| ticker = ticker.upper().strip() | |
| bars = fetch_history_yf(ticker) | |
| if bars.empty: | |
| return "β No data", None, "", "", "" | |
| last_price = bars["close"].iloc[-1] | |
| pred_text = "β οΈ Model not trained" | |
| if os.path.exists(MODEL_PATH): | |
| with open(MODEL_PATH, "rb") as f: | |
| reg = pickle.load(f) | |
| feat = build_feature_set(bars, vix_df=fetch_history_yf(VOLATILITY_INDEX, period="1mo")) | |
| if not feat.empty: | |
| latest = feat.tail(1) | |
| pred_val = float(reg.predict(latest[FEATURES])[0] * 100) | |
| log_prediction_to_db(ticker, pred_val, last_price) | |
| m_score = calculate_momentum_score(pred_val, float(latest["rsi"].iloc[0]), float(latest["vol_spike"].iloc[0])) | |
| if m_score > MOMENTUM_THRESHOLD: | |
| signal, color = "π₯ STRONG", "#00FF00" | |
| elif m_score > 50: | |
| signal, color = "βοΈ TREND", "#FFC107" | |
| else: | |
| signal, color = "β οΈ WEAK", "#FF5252" | |
| pred_text = f"<div style='text-align: center; border: 1px solid {color}; padding: 10px;'><h2>{m_score:.1f}/100</h2><h3>{signal}</h3><p>Forecast: {pred_val:+.2f}%</p></div>" | |
| fig = go.Figure(data=[go.Candlestick(x=bars.index, open=bars["open"], high=bars["high"], low=bars["low"], close=bars["close"])]) | |
| fig.update_layout(template="plotly_dark", xaxis_rangeslider_visible=False, height=450) | |
| return f"### {ticker} Analysis", fig, pred_text, f"${last_price:.2f}", "" | |
| def get_sector_analysis(): | |
| if not os.path.exists(MODEL_PATH): | |
| return "β Train First", None, "" | |
| with open(MODEL_PATH, "rb") as f: | |
| reg = pickle.load(f) | |
| vix = fetch_history_yf(VOLATILITY_INDEX) | |
| rows = [] | |
| for t in SECTOR_ETFS: | |
| bars = fetch_history_yf(t, period="2y") | |
| feat = build_feature_set(bars, vix_df=vix) | |
| if feat.empty: | |
| continue | |
| rows.append({"Sector": t, "Return": reg.predict(feat.tail(1)[FEATURES])[0] * 100}) | |
| if not rows: | |
| return "β No sector data", None, "" | |
| df_res = pd.DataFrame(rows).sort_values("Return", ascending=False) | |
| fig = go.Figure(go.Bar(x=df_res["Sector"], y=df_res["Return"], marker_color="#FFC107")) | |
| fig.update_layout(template="plotly_dark", title="Sector Sentiment", height=400) | |
| return f"### Strongest: {df_res['Sector'].iloc[0]}", fig, "Macro synced." | |
| # --- GRADIO INTERFACE --- | |
| with gr.Blocks() as brie: | |
| gr.Markdown("# π§ Brie Ultra AI") | |
| with gr.Tabs(): | |
| with gr.Tab("π Scanner"): | |
| with gr.Row(): | |
| ticker_in = gr.Textbox(label="Ticker", scale=4) | |
| scan_btn = gr.Button("Predict", variant="primary", scale=1) | |
| chart = gr.Plot() | |
| with gr.Row(): | |
| res_txt, pred_out, price_lbl = gr.Markdown(), gr.HTML(), gr.Label(label="Last Close") | |
| scan_btn.click(analyze_asset, ticker_in, [res_txt, chart, pred_out, price_lbl]) | |
| with gr.Tab("π― Accuracy Dashboard"): | |
| perf_btn = gr.Button("Refresh Accuracy Stats") | |
| perf_stats, perf_chart = gr.Markdown(), gr.Plot() | |
| perf_btn.click(get_performance_dashboard, None, [perf_stats, perf_chart]) | |
| with gr.Tab("π Sector Impact"): | |
| sector_btn = gr.Button("Analyze Macro") | |
| sector_top, sector_chart, sector_ai = gr.Markdown(), gr.Plot(), gr.Markdown() | |
| sector_btn.click(get_sector_analysis, None, [sector_top, sector_chart, sector_ai]) | |
| with gr.Tab("βοΈ Continuous Learning"): | |
| gr.Markdown("### Watchlist") | |
| with gr.Row(): | |
| ticker_input = gr.Textbox(label="Ticker", scale=3) | |
| add_btn, remove_btn = gr.Button("β Add"), gr.Button("ποΈ Remove") | |
| watchlist_display = gr.Dataframe(headers=["Ticker"], value=get_current_watchlist()) | |
| gr.Markdown("---") | |
| cal_btn = gr.Button("Learn & Sync", variant="stop") | |
| cal_out = gr.Markdown("Ready.") | |
| cal_btn.click(run_incremental_training, gr.Textbox(value=",".join(SECTOR_ETFS), visible=False), [cal_out]) | |
| gr.Markdown("---") | |
| discord_btn = gr.Button("π Send Briefing", variant="primary") | |
| discord_status = gr.Label(value="Ready") | |
| add_btn.click(add_ticker_to_db, [ticker_input], [watchlist_display, ticker_input]) | |
| remove_btn.click(remove_ticker_from_db, [ticker_input], [watchlist_display, ticker_input]) | |
| discord_btn.click(trigger_discord, None, [discord_status]) | |
| if __name__ == "__main__": | |
| init_db() | |
| load_from_cloud() | |
| init_db() | |
| brie.queue().launch( | |
| theme=gr.themes.Default(primary_hue="amber"), | |
| server_name="0.0.0.0", | |
| server_port=int(os.getenv("PORT", 7860)) | |
| ) |