Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -60,7 +60,6 @@ or_client = OpenAI(
|
|
| 60 |
DB_PATH = "/tmp/brie_brain.db"
|
| 61 |
MODEL_PATH = "/tmp/brie_model.pkl"
|
| 62 |
|
| 63 |
-
# EXPANDED FEATURES for high accuracy next-day prediction
|
| 64 |
FEATURES = [
|
| 65 |
"rsi", "macd_h", "ema_20_dist", "ema_50_dist", "vwap_dist",
|
| 66 |
"atr_pct", "bb_width", "vol_spike", "ret_1d", "ret_5d",
|
|
@@ -135,7 +134,6 @@ def build_feature_set(df, sentiment_val=0.0, labeling=False, vix_df=None):
|
|
| 135 |
df = df.copy()
|
| 136 |
ind = pd.DataFrame(index=df.index)
|
| 137 |
|
| 138 |
-
# Fundamental Techs
|
| 139 |
ind["rsi"] = ta.rsi(df["close"], length=14).fillna(50.0)
|
| 140 |
macd = ta.macd(df["close"])
|
| 141 |
if macd is not None and not macd.empty:
|
|
@@ -168,16 +166,16 @@ def build_feature_set(df, sentiment_val=0.0, labeling=False, vix_df=None):
|
|
| 168 |
ind["day_of_week"] = df.index.dayofweek.astype(float)
|
| 169 |
ind["sentiment_score"] = float(sentiment_val)
|
| 170 |
|
| 171 |
-
#
|
| 172 |
-
|
| 173 |
-
if vix_df is not None:
|
| 174 |
vix_resampled = vix_df["close"].reindex(df.index, method="ffill")
|
| 175 |
ind["vix_level"] = vix_resampled.fillna(20.0)
|
| 176 |
else:
|
| 177 |
ind["vix_level"] = 20.0
|
| 178 |
|
|
|
|
|
|
|
| 179 |
if labeling:
|
| 180 |
-
# TARGET: Next Day Return (Regression)
|
| 181 |
ind["target_next_day_ret"] = df["close"].pct_change(1).shift(-1)
|
| 182 |
|
| 183 |
return ind[FEATURES + (["target_next_day_ret"] if labeling else [])].dropna()
|
|
@@ -189,6 +187,9 @@ def run_incremental_training(batch_str):
|
|
| 189 |
if alpha not in tickers: tickers.append(alpha)
|
| 190 |
|
| 191 |
vix_data = fetch_history_yf(VOLATILITY_INDEX)
|
|
|
|
|
|
|
|
|
|
| 192 |
yield "π₯ Fetching Fresh Data & VIX..."
|
| 193 |
|
| 194 |
all_data = []
|
|
@@ -209,7 +210,6 @@ def run_incremental_training(batch_str):
|
|
| 209 |
return
|
| 210 |
|
| 211 |
df = pd.concat(all_data, ignore_index=True)
|
| 212 |
-
|
| 213 |
yield "πΎ Updating Brain (DuckDB)..."
|
| 214 |
try:
|
| 215 |
with duckdb.connect(DB_PATH) as con:
|
|
@@ -221,42 +221,26 @@ def run_incremental_training(batch_str):
|
|
| 221 |
return
|
| 222 |
|
| 223 |
yield "π§ Incremental Learning in Progress..."
|
| 224 |
-
|
| 225 |
-
# Regression config for price magnitude prediction
|
| 226 |
-
xgb_params = {
|
| 227 |
-
"n_estimators": 200,
|
| 228 |
-
"max_depth": 7,
|
| 229 |
-
"learning_rate": 0.02,
|
| 230 |
-
"subsample": 0.8,
|
| 231 |
-
"colsample_bytree": 0.8,
|
| 232 |
-
"n_jobs": -1,
|
| 233 |
-
"objective": "reg:absoluteerror"
|
| 234 |
-
}
|
| 235 |
-
|
| 236 |
-
model = XGBRegressor(**xgb_params)
|
| 237 |
-
|
| 238 |
-
# Train on most recent data to capture latest trends
|
| 239 |
train_data = data.tail(2000)
|
| 240 |
model.fit(train_data[FEATURES], train_data["target_next_day_ret"])
|
| 241 |
|
| 242 |
with open(MODEL_PATH, "wb") as f:
|
| 243 |
pickle.dump(model, f)
|
| 244 |
-
|
| 245 |
yield f"β
Next-Day Model Refreshed! {save_to_cloud()}"
|
| 246 |
|
| 247 |
def analyze_asset(ticker):
|
| 248 |
if not ticker: return "β οΈ Enter ticker.", None, "0%", "N/A", ""
|
| 249 |
ticker = ticker.upper().strip()
|
| 250 |
-
|
| 251 |
bars = fetch_history_yf(ticker)
|
| 252 |
if bars.empty: return f"β No data for {ticker}", None, "0%", "N/A", ""
|
| 253 |
|
| 254 |
pred_val = 0.0
|
| 255 |
if os.path.exists(MODEL_PATH):
|
| 256 |
try:
|
| 257 |
-
with open(MODEL_PATH, "rb") as f:
|
| 258 |
-
reg = pickle.load(f)
|
| 259 |
vix_data = fetch_history_yf(VOLATILITY_INDEX, period="1mo")
|
|
|
|
| 260 |
feat = build_feature_set(bars, vix_df=vix_data)
|
| 261 |
if not feat.empty:
|
| 262 |
pred_val = reg.predict(feat.tail(1)[FEATURES])[0] * 100
|
|
@@ -265,17 +249,19 @@ def analyze_asset(ticker):
|
|
| 265 |
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3])
|
| 266 |
fig.add_trace(go.Candlestick(x=bars.index, open=bars["open"], high=bars["high"], low=bars["low"], close=bars["close"], name="Price"), row=1, col=1)
|
| 267 |
fig.update_layout(template="plotly_dark", height=500, xaxis_rangeslider_visible=False)
|
| 268 |
-
|
| 269 |
color = "green" if pred_val > 0 else "red"
|
| 270 |
pred_text = f"<span style='color:{color}; font-size:24px;'>{pred_val:+.2f}% Expected Tomorrow</span>"
|
| 271 |
-
|
| 272 |
return f"### {ticker} Forecast", fig, pred_text, f"${bars['close'].iloc[-1]:.2f}", ""
|
| 273 |
|
|
|
|
| 274 |
def get_sector_analysis():
|
| 275 |
if not os.path.exists(MODEL_PATH): return "β Calibrate first.", None, ""
|
| 276 |
with open(MODEL_PATH, "rb") as f: reg = pickle.load(f)
|
| 277 |
|
| 278 |
-
vix_data = fetch_history_yf(VOLATILITY_INDEX
|
|
|
|
|
|
|
|
|
|
| 279 |
rows = []
|
| 280 |
for t in SECTOR_ETFS:
|
| 281 |
bars = fetch_history_yf(t, period="2y")
|
|
@@ -285,63 +271,44 @@ def get_sector_analysis():
|
|
| 285 |
pred = reg.predict(feat.tail(1)[FEATURES])[0] * 100
|
| 286 |
rows.append({"Sector": t, "NextDay": pred})
|
| 287 |
|
|
|
|
|
|
|
| 288 |
df = pd.DataFrame(rows).sort_values("NextDay", ascending=False)
|
| 289 |
-
fig = go.Figure(go.Bar(x=df["Sector"], y=df["NextDay"], marker_color='#FFC107'))
|
| 290 |
fig.update_layout(template="plotly_dark", title="Expected Next-Day Returns %", height=400)
|
| 291 |
-
|
| 292 |
return f"### Strongest Outlook: {df['Sector'].iloc[0]}", fig, "Brie is projecting macro movement based on sector momentum."
|
| 293 |
|
| 294 |
# --- GRADIO INTERFACE ---
|
| 295 |
with gr.Blocks() as brie:
|
| 296 |
gr.Markdown("# π§ Brie Ultra AI: Next-Day Price Predictor")
|
| 297 |
-
|
| 298 |
with gr.Tabs():
|
| 299 |
with gr.Tab("π Next-Day Scanner"):
|
| 300 |
with gr.Row():
|
| 301 |
ticker_in = gr.Textbox(label="Ticker", placeholder="NVDA", scale=4)
|
| 302 |
scan_btn = gr.Button("Predict Tomorrow", variant="primary", scale=1)
|
| 303 |
-
|
| 304 |
chart = gr.Plot()
|
| 305 |
-
|
| 306 |
with gr.Row():
|
| 307 |
-
|
| 308 |
-
res_txt = gr.Markdown()
|
| 309 |
-
with gr.Column():
|
| 310 |
-
pred_out = gr.HTML(label="Forecast")
|
| 311 |
-
with gr.Column():
|
| 312 |
-
price_lbl = gr.Label(label="Last Close")
|
| 313 |
-
|
| 314 |
scan_btn.click(analyze_asset, ticker_in, [res_txt, chart, pred_out, price_lbl])
|
| 315 |
|
| 316 |
with gr.Tab("π Sector Impact"):
|
| 317 |
sector_btn = gr.Button("Update Macro Sentiment")
|
| 318 |
-
sector_top = gr.Markdown()
|
| 319 |
-
sector_chart = gr.Plot()
|
| 320 |
-
sector_ai = gr.Markdown()
|
| 321 |
sector_btn.click(get_sector_analysis, None, [sector_top, sector_chart, sector_ai])
|
| 322 |
|
| 323 |
with gr.Tab("βοΈ Continuous Learning"):
|
| 324 |
gr.Markdown("### Incremental Training Loop")
|
| 325 |
-
gr.Markdown("This updates the 'Brain' with the latest market data and retrains the model.")
|
| 326 |
-
|
| 327 |
-
# --- Existing Training UI ---
|
| 328 |
cal_input = gr.Textbox(value=",".join(SECTOR_ETFS), visible=False)
|
| 329 |
cal_btn = gr.Button("Learn & Sync to Cloud", variant="stop")
|
| 330 |
cal_out = gr.Markdown("Ready to learn.")
|
| 331 |
cal_btn.click(run_incremental_training, cal_input, [cal_out])
|
| 332 |
-
|
| 333 |
-
gr.Markdown("---") # Visual separator
|
| 334 |
-
|
| 335 |
-
# --- New Discord Briefing UI ---
|
| 336 |
gr.Markdown("### Discord Integration")
|
| 337 |
-
gr.Markdown("Send a high-speed Alpaca market snapshot and signal summary to your Discord.")
|
| 338 |
discord_btn = gr.Button("Send Briefing to Discord", variant="primary")
|
| 339 |
discord_out = gr.Markdown("Standing by...")
|
| 340 |
|
| 341 |
-
# Define the trigger within the UI scope
|
| 342 |
def trigger_discord():
|
| 343 |
from brie_agent import run_alpaca_briefing
|
| 344 |
-
# Uses your existing watchlist from the top of your script
|
| 345 |
watchlist = ["QBTS", "SPCE", "TMC", "GRML", "BATT"]
|
| 346 |
return run_alpaca_briefing(watchlist)
|
| 347 |
|
|
|
|
| 60 |
DB_PATH = "/tmp/brie_brain.db"
|
| 61 |
MODEL_PATH = "/tmp/brie_model.pkl"
|
| 62 |
|
|
|
|
| 63 |
FEATURES = [
|
| 64 |
"rsi", "macd_h", "ema_20_dist", "ema_50_dist", "vwap_dist",
|
| 65 |
"atr_pct", "bb_width", "vol_spike", "ret_1d", "ret_5d",
|
|
|
|
| 134 |
df = df.copy()
|
| 135 |
ind = pd.DataFrame(index=df.index)
|
| 136 |
|
|
|
|
| 137 |
ind["rsi"] = ta.rsi(df["close"], length=14).fillna(50.0)
|
| 138 |
macd = ta.macd(df["close"])
|
| 139 |
if macd is not None and not macd.empty:
|
|
|
|
| 166 |
ind["day_of_week"] = df.index.dayofweek.astype(float)
|
| 167 |
ind["sentiment_score"] = float(sentiment_val)
|
| 168 |
|
| 169 |
+
# Standard VIX Safe-Access logic
|
| 170 |
+
if vix_df is not None and not vix_df.empty and "close" in vix_df.columns:
|
|
|
|
| 171 |
vix_resampled = vix_df["close"].reindex(df.index, method="ffill")
|
| 172 |
ind["vix_level"] = vix_resampled.fillna(20.0)
|
| 173 |
else:
|
| 174 |
ind["vix_level"] = 20.0
|
| 175 |
|
| 176 |
+
ind["gap_pct"] = ((df["open"] - df["close"].shift(1)) / df["close"].shift(1)).fillna(0.0)
|
| 177 |
+
|
| 178 |
if labeling:
|
|
|
|
| 179 |
ind["target_next_day_ret"] = df["close"].pct_change(1).shift(-1)
|
| 180 |
|
| 181 |
return ind[FEATURES + (["target_next_day_ret"] if labeling else [])].dropna()
|
|
|
|
| 187 |
if alpha not in tickers: tickers.append(alpha)
|
| 188 |
|
| 189 |
vix_data = fetch_history_yf(VOLATILITY_INDEX)
|
| 190 |
+
if vix_data.empty:
|
| 191 |
+
vix_data = pd.DataFrame({'close': [20.0]}, index=[pd.Timestamp.now()])
|
| 192 |
+
|
| 193 |
yield "π₯ Fetching Fresh Data & VIX..."
|
| 194 |
|
| 195 |
all_data = []
|
|
|
|
| 210 |
return
|
| 211 |
|
| 212 |
df = pd.concat(all_data, ignore_index=True)
|
|
|
|
| 213 |
yield "πΎ Updating Brain (DuckDB)..."
|
| 214 |
try:
|
| 215 |
with duckdb.connect(DB_PATH) as con:
|
|
|
|
| 221 |
return
|
| 222 |
|
| 223 |
yield "π§ Incremental Learning in Progress..."
|
| 224 |
+
model = XGBRegressor(n_estimators=200, max_depth=7, learning_rate=0.02, n_jobs=-1, objective="reg:absoluteerror")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
train_data = data.tail(2000)
|
| 226 |
model.fit(train_data[FEATURES], train_data["target_next_day_ret"])
|
| 227 |
|
| 228 |
with open(MODEL_PATH, "wb") as f:
|
| 229 |
pickle.dump(model, f)
|
|
|
|
| 230 |
yield f"β
Next-Day Model Refreshed! {save_to_cloud()}"
|
| 231 |
|
| 232 |
def analyze_asset(ticker):
|
| 233 |
if not ticker: return "β οΈ Enter ticker.", None, "0%", "N/A", ""
|
| 234 |
ticker = ticker.upper().strip()
|
|
|
|
| 235 |
bars = fetch_history_yf(ticker)
|
| 236 |
if bars.empty: return f"β No data for {ticker}", None, "0%", "N/A", ""
|
| 237 |
|
| 238 |
pred_val = 0.0
|
| 239 |
if os.path.exists(MODEL_PATH):
|
| 240 |
try:
|
| 241 |
+
with open(MODEL_PATH, "rb") as f: reg = pickle.load(f)
|
|
|
|
| 242 |
vix_data = fetch_history_yf(VOLATILITY_INDEX, period="1mo")
|
| 243 |
+
if vix_data.empty: vix_data = pd.DataFrame({'close': [20.0]}, index=[pd.Timestamp.now()])
|
| 244 |
feat = build_feature_set(bars, vix_df=vix_data)
|
| 245 |
if not feat.empty:
|
| 246 |
pred_val = reg.predict(feat.tail(1)[FEATURES])[0] * 100
|
|
|
|
| 249 |
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3])
|
| 250 |
fig.add_trace(go.Candlestick(x=bars.index, open=bars["open"], high=bars["high"], low=bars["low"], close=bars["close"], name="Price"), row=1, col=1)
|
| 251 |
fig.update_layout(template="plotly_dark", height=500, xaxis_rangeslider_visible=False)
|
|
|
|
| 252 |
color = "green" if pred_val > 0 else "red"
|
| 253 |
pred_text = f"<span style='color:{color}; font-size:24px;'>{pred_val:+.2f}% Expected Tomorrow</span>"
|
|
|
|
| 254 |
return f"### {ticker} Forecast", fig, pred_text, f"${bars['close'].iloc[-1]:.2f}", ""
|
| 255 |
|
| 256 |
+
# --- ANALYTICS LOOP ---
|
| 257 |
def get_sector_analysis():
|
| 258 |
if not os.path.exists(MODEL_PATH): return "β Calibrate first.", None, ""
|
| 259 |
with open(MODEL_PATH, "rb") as f: reg = pickle.load(f)
|
| 260 |
|
| 261 |
+
vix_data = fetch_history_yf(VOLATILITY_INDEX)
|
| 262 |
+
if vix_data.empty:
|
| 263 |
+
vix_data = pd.DataFrame({'close': [20.0]}, index=[pd.Timestamp.now()])
|
| 264 |
+
|
| 265 |
rows = []
|
| 266 |
for t in SECTOR_ETFS:
|
| 267 |
bars = fetch_history_yf(t, period="2y")
|
|
|
|
| 271 |
pred = reg.predict(feat.tail(1)[FEATURES])[0] * 100
|
| 272 |
rows.append({"Sector": t, "NextDay": pred})
|
| 273 |
|
| 274 |
+
if not rows: return "β Analysis failed (YF limit reached).", None, ""
|
| 275 |
+
|
| 276 |
df = pd.DataFrame(rows).sort_values("NextDay", ascending=False)
|
| 277 |
+
fig = go.Figure(go.Bar(x=df["Sector"], y=df["NextDay"], marker_color='#FFC107'))
|
| 278 |
fig.update_layout(template="plotly_dark", title="Expected Next-Day Returns %", height=400)
|
|
|
|
| 279 |
return f"### Strongest Outlook: {df['Sector'].iloc[0]}", fig, "Brie is projecting macro movement based on sector momentum."
|
| 280 |
|
| 281 |
# --- GRADIO INTERFACE ---
|
| 282 |
with gr.Blocks() as brie:
|
| 283 |
gr.Markdown("# π§ Brie Ultra AI: Next-Day Price Predictor")
|
|
|
|
| 284 |
with gr.Tabs():
|
| 285 |
with gr.Tab("π Next-Day Scanner"):
|
| 286 |
with gr.Row():
|
| 287 |
ticker_in = gr.Textbox(label="Ticker", placeholder="NVDA", scale=4)
|
| 288 |
scan_btn = gr.Button("Predict Tomorrow", variant="primary", scale=1)
|
|
|
|
| 289 |
chart = gr.Plot()
|
|
|
|
| 290 |
with gr.Row():
|
| 291 |
+
res_txt, pred_out, price_lbl = gr.Markdown(), gr.HTML(label="Forecast"), gr.Label(label="Last Close")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
scan_btn.click(analyze_asset, ticker_in, [res_txt, chart, pred_out, price_lbl])
|
| 293 |
|
| 294 |
with gr.Tab("π Sector Impact"):
|
| 295 |
sector_btn = gr.Button("Update Macro Sentiment")
|
| 296 |
+
sector_top, sector_chart, sector_ai = gr.Markdown(), gr.Plot(), gr.Markdown()
|
|
|
|
|
|
|
| 297 |
sector_btn.click(get_sector_analysis, None, [sector_top, sector_chart, sector_ai])
|
| 298 |
|
| 299 |
with gr.Tab("βοΈ Continuous Learning"):
|
| 300 |
gr.Markdown("### Incremental Training Loop")
|
|
|
|
|
|
|
|
|
|
| 301 |
cal_input = gr.Textbox(value=",".join(SECTOR_ETFS), visible=False)
|
| 302 |
cal_btn = gr.Button("Learn & Sync to Cloud", variant="stop")
|
| 303 |
cal_out = gr.Markdown("Ready to learn.")
|
| 304 |
cal_btn.click(run_incremental_training, cal_input, [cal_out])
|
| 305 |
+
gr.Markdown("---")
|
|
|
|
|
|
|
|
|
|
| 306 |
gr.Markdown("### Discord Integration")
|
|
|
|
| 307 |
discord_btn = gr.Button("Send Briefing to Discord", variant="primary")
|
| 308 |
discord_out = gr.Markdown("Standing by...")
|
| 309 |
|
|
|
|
| 310 |
def trigger_discord():
|
| 311 |
from brie_agent import run_alpaca_briefing
|
|
|
|
| 312 |
watchlist = ["QBTS", "SPCE", "TMC", "GRML", "BATT"]
|
| 313 |
return run_alpaca_briefing(watchlist)
|
| 314 |
|