ghstedpixel commited on
Commit
6c92fdf
Β·
verified Β·
1 Parent(s): 76a319d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -65
app.py CHANGED
@@ -62,6 +62,7 @@ SECTOR_ETFS = ["XLF", "XLK", "XLE", "XLY", "XLP", "XLV", "XLI", "XLU", "XLB", "X
62
  MARKET_BENCH = "SPY"
63
 
64
  # --- DATABASE & CLOUD ---
 
65
  def init_db():
66
  with duckdb.connect(DB_PATH) as con:
67
  feat_cols = ", ".join([f'"{f}" FLOAT' for f in FEATURES])
@@ -88,32 +89,21 @@ def save_to_cloud():
88
 
89
  def fetch_history_yf(ticker, period="5y", interval="1d"):
90
  try:
91
- # Use Ticker object for single assets to avoid the concat error
92
  dat = yf.Ticker(ticker)
93
  df = dat.history(period=period, interval=interval, auto_adjust=False)
94
-
95
  if df is None or df.empty:
96
- # Fallback to download if history() fails
97
  df = yf.download(ticker, period=period, interval=interval, auto_adjust=False, progress=False)
98
-
99
  if df is None or df.empty:
100
  return pd.DataFrame()
101
-
102
- df = df.copy()
103
 
104
- # Flatten MultiIndex if present
105
  if isinstance(df.columns, pd.MultiIndex):
106
  df.columns = df.columns.get_level_values(0)
107
-
108
- # Clean column names
109
  df.columns = [str(c).lower().replace(" ", "_") for c in df.columns]
110
 
111
- # Standardize columns
112
  needed = ["open", "high", "low", "close", "volume"]
113
  for col in needed:
114
- if col not in df.columns:
115
- return pd.DataFrame()
116
-
117
  return df[needed]
118
  except Exception as e:
119
  print(f"⚠️ yfinance error for {ticker}: {e}")
@@ -139,6 +129,7 @@ def build_feature_set(df, sentiment_val=0.0, labeling=False, bench_close=None):
139
  ind["ret_5d"] = df["close"].pct_change(5).fillna(0.0)
140
  ind["day_of_week"] = df.index.dayofweek.astype(float)
141
  ind["sentiment_score"] = float(sentiment_val)
 
142
  if labeling and bench_close is not None:
143
  rel_ret = (df["close"].shift(-3) / df["close"]) - (bench_close.reindex(df.index).ffill().shift(-3) / bench_close.reindex(df.index).ffill())
144
  ind["target_up_2pct_3d"] = (rel_ret > 0.02).astype(int)
@@ -159,97 +150,120 @@ def run_calibration(batch_str):
159
  f_set["ticker"] = t
160
  all_data.append(f_set)
161
 
162
- if not all_data:
163
- yield "❌ No data", 1.0
164
  return
165
 
166
  yield "πŸ’Ύ Training Alpha Model...", 0.7
167
  combined = pd.concat(all_data, ignore_index=True)
168
  with duckdb.connect(DB_PATH) as con:
169
  con.register("temp", combined)
170
- con.execute("""
171
- INSERT OR IGNORE INTO feature_store
172
- SELECT ticker, timestamp::TIMESTAMP as timestamp,
173
- "rsi", "macd_h", "ema_20_dist", "ema_50_dist", "vwap_dist",
174
- "atr_pct", "bb_width", "vol_spike", "ret_1d", "ret_5d",
175
- "day_of_week", "sentiment_score", target_up_2pct_3d
176
- FROM temp
177
- """)
178
  df = con.execute("SELECT * FROM feature_store").df()
179
 
180
  model = CalibratedClassifierCV(estimator=XGBClassifier(n_estimators=50, max_depth=4), cv=TimeSeriesSplit(n_splits=3))
181
  model.fit(df[FEATURES], df["target_up_2pct_3d"])
182
- with open(MODEL_PATH, "wb") as f:
183
- pickle.dump(model, f)
184
  yield f"βœ… DONE! {save_to_cloud()}", 1.0
185
 
186
- # --- SECTOR SPECIFIC LOGIC ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  def get_sector_analysis():
189
  if not os.path.exists(MODEL_PATH):
190
- return "❌ Please Calibrate first.", None, ""
191
 
192
  with open(MODEL_PATH, "rb") as f:
193
  clf = pickle.load(f)
194
 
195
  rows = []
196
- # Use the SECTOR_ETFS list defined in your config
197
  for t in SECTOR_ETFS:
198
- if not t: continue # Skip empty entries
199
  bars = fetch_history_yf(t, period="1y")
200
- # ... rest of your loop ...
201
  if bars.empty: continue
202
  feat = build_feature_set(bars)
 
203
  prob = clf.predict_proba(feat.tail(1)[FEATURES])[0][1] * 100
204
  rows.append({"Sector": t, "Alpha Prob": prob})
205
 
 
 
206
  df = pd.DataFrame(rows).sort_values("Alpha Prob", ascending=False)
207
  fig = go.Figure(go.Bar(x=df["Sector"], y=df["Alpha Prob"], marker_color='orange'))
208
- fig.update_layout(template="plotly_dark", title="Sector Outperformance Prob (Rel to SPY)", height=400)
209
 
210
  context = ", ".join([f"{r['Sector']}: {r['Alpha Prob']:.1f}%" for _, r in df.iterrows()])
211
  ai_view = "🧠 **Brie's Sector View:** "
212
  try:
213
  res = or_client.chat.completions.create(
214
  model="google/gemini-2.0-flash-lite-preview-02-05:free",
215
- messages=[{"role": "user", "content": f"Summarize sector rotation for these probabilities: {context}. 3 sentences."}]
216
  )
217
  ai_view += res.choices[0].message.content
218
- except: ai_view += "Macro analysis complete."
 
219
  return f"### Top Pick: {df['Sector'].iloc[0]}", fig, ai_view
220
 
221
- def analyze_asset(ticker):
222
- if not ticker or not ticker.strip():
223
- return "⚠️ Please enter a ticker.", None, "0%", "N/A"
 
224
 
225
- ticker = ticker.upper().strip()
226
- try:
227
- bars = fetch_history_yf(ticker)
228
- if bars is None or bars.empty:
229
- return f"❌ No data found for {ticker}", None, "0%", "N/A"
230
 
231
- prob = 50.0
232
- if os.path.exists(MODEL_PATH):
233
- with open(MODEL_PATH, "rb") as f:
234
- clf = pickle.load(f)
235
- feat = build_feature_set(bars)
236
- if not feat.empty:
237
- prob = clf.predict_proba(feat.tail(1)[FEATURES])[0][1] * 100
 
 
 
238
 
239
- fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3], vertical_spacing=0.05)
240
- fig.add_trace(go.Candlestick(
241
- x=bars.index, open=bars["open"], high=bars["high"],
242
- low=bars["low"], close=bars["close"], name="Price"
243
- ), row=1, col=1)
244
-
245
- fig.update_layout(
246
- template="plotly_dark",
247
- height=600,
248
- xaxis_rangeslider_visible=False,
249
- margin=dict(l=10, r=10, t=30, b=10)
250
- )
251
-
252
- last_price = f"${bars['close'].iloc[-1]:.2f}"
253
- return f"### Analysis for {ticker}", fig, f"{prob:.1f}%", last_price
254
- except Exception as e:
255
- return f"⚠️ Error: {str(e)[:50]}", None, "0%", "N/A"
 
 
 
62
  MARKET_BENCH = "SPY"
63
 
64
  # --- DATABASE & CLOUD ---
65
+
66
  def init_db():
67
  with duckdb.connect(DB_PATH) as con:
68
  feat_cols = ", ".join([f'"{f}" FLOAT' for f in FEATURES])
 
89
 
90
  def fetch_history_yf(ticker, period="5y", interval="1d"):
91
  try:
 
92
  dat = yf.Ticker(ticker)
93
  df = dat.history(period=period, interval=interval, auto_adjust=False)
 
94
  if df is None or df.empty:
 
95
  df = yf.download(ticker, period=period, interval=interval, auto_adjust=False, progress=False)
 
96
  if df is None or df.empty:
97
  return pd.DataFrame()
 
 
98
 
99
+ df = df.copy()
100
  if isinstance(df.columns, pd.MultiIndex):
101
  df.columns = df.columns.get_level_values(0)
 
 
102
  df.columns = [str(c).lower().replace(" ", "_") for c in df.columns]
103
 
 
104
  needed = ["open", "high", "low", "close", "volume"]
105
  for col in needed:
106
+ if col not in df.columns: return pd.DataFrame()
 
 
107
  return df[needed]
108
  except Exception as e:
109
  print(f"⚠️ yfinance error for {ticker}: {e}")
 
129
  ind["ret_5d"] = df["close"].pct_change(5).fillna(0.0)
130
  ind["day_of_week"] = df.index.dayofweek.astype(float)
131
  ind["sentiment_score"] = float(sentiment_val)
132
+
133
  if labeling and bench_close is not None:
134
  rel_ret = (df["close"].shift(-3) / df["close"]) - (bench_close.reindex(df.index).ffill().shift(-3) / bench_close.reindex(df.index).ffill())
135
  ind["target_up_2pct_3d"] = (rel_ret > 0.02).astype(int)
 
150
  f_set["ticker"] = t
151
  all_data.append(f_set)
152
 
153
+ if not all_data:
154
+ yield "❌ No data to train on.", 1.0
155
  return
156
 
157
  yield "πŸ’Ύ Training Alpha Model...", 0.7
158
  combined = pd.concat(all_data, ignore_index=True)
159
  with duckdb.connect(DB_PATH) as con:
160
  con.register("temp", combined)
161
+ con.execute(f"INSERT OR IGNORE INTO feature_store SELECT * FROM temp")
 
 
 
 
 
 
 
162
  df = con.execute("SELECT * FROM feature_store").df()
163
 
164
  model = CalibratedClassifierCV(estimator=XGBClassifier(n_estimators=50, max_depth=4), cv=TimeSeriesSplit(n_splits=3))
165
  model.fit(df[FEATURES], df["target_up_2pct_3d"])
166
+ with open(MODEL_PATH, "wb") as f: pickle.dump(model, f)
 
167
  yield f"βœ… DONE! {save_to_cloud()}", 1.0
168
 
169
+ def analyze_asset(ticker):
170
+ if not ticker or not ticker.strip():
171
+ return "⚠️ Please enter a ticker.", None, "0%", "N/A"
172
+
173
+ ticker = ticker.upper().strip()
174
+ try:
175
+ bars = fetch_history_yf(ticker)
176
+ if bars is None or bars.empty:
177
+ return f"❌ No data for {ticker}", None, "0%", "N/A"
178
+
179
+ prob = 50.0
180
+ if os.path.exists(MODEL_PATH):
181
+ with open(MODEL_PATH, "rb") as f:
182
+ clf = pickle.load(f)
183
+ feat = build_feature_set(bars)
184
+ if not feat.empty:
185
+ prob = clf.predict_proba(feat.tail(1)[FEATURES])[0][1] * 100
186
+
187
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3], vertical_spacing=0.05)
188
+ 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)
189
+ fig.update_layout(template="plotly_dark", height=600, xaxis_rangeslider_visible=False, margin=dict(l=10, r=10, t=30, b=10))
190
+
191
+ last_price = f"${bars['close'].iloc[-1]:.2f}"
192
+ return f"### Analysis for {ticker}", fig, f"{prob:.1f}%", last_price
193
+ except Exception as e:
194
+ return f"⚠️ Error: {str(e)[:30]}", None, "0%", "N/A"
195
 
196
  def get_sector_analysis():
197
  if not os.path.exists(MODEL_PATH):
198
+ return "❌ Please Calibrate first.", None, "Run calibration to see macro view."
199
 
200
  with open(MODEL_PATH, "rb") as f:
201
  clf = pickle.load(f)
202
 
203
  rows = []
 
204
  for t in SECTOR_ETFS:
 
205
  bars = fetch_history_yf(t, period="1y")
 
206
  if bars.empty: continue
207
  feat = build_feature_set(bars)
208
+ if feat.empty: continue
209
  prob = clf.predict_proba(feat.tail(1)[FEATURES])[0][1] * 100
210
  rows.append({"Sector": t, "Alpha Prob": prob})
211
 
212
+ if not rows: return "❌ Data Fetching Failed.", None, ""
213
+
214
  df = pd.DataFrame(rows).sort_values("Alpha Prob", ascending=False)
215
  fig = go.Figure(go.Bar(x=df["Sector"], y=df["Alpha Prob"], marker_color='orange'))
216
+ fig.update_layout(template="plotly_dark", title="Sector Alpha Probabilities", height=400)
217
 
218
  context = ", ".join([f"{r['Sector']}: {r['Alpha Prob']:.1f}%" for _, r in df.iterrows()])
219
  ai_view = "🧠 **Brie's Sector View:** "
220
  try:
221
  res = or_client.chat.completions.create(
222
  model="google/gemini-2.0-flash-lite-preview-02-05:free",
223
+ messages=[{"role": "user", "content": f"Summarize sector rotation for: {context}. 3 sentences max."}]
224
  )
225
  ai_view += res.choices[0].message.content
226
+ except: ai_view += "Macro rotation analysis complete."
227
+
228
  return f"### Top Pick: {df['Sector'].iloc[0]}", fig, ai_view
229
 
230
+ # --- GRADIO INTERFACE ---
231
+
232
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="amber")) as brie:
233
+ gr.Markdown("# πŸ§€ Brie Ultra AI")
234
 
235
+ with gr.Tab("πŸ” Scanner"):
236
+ with gr.Row():
237
+ ticker_in = gr.Textbox(label="Ticker", placeholder="NVDA", scale=4)
238
+ scan_btn = gr.Button("Scan", variant="primary", scale=1)
 
239
 
240
+ with gr.Row():
241
+ chart = gr.Plot(container=True)
242
+
243
+ with gr.Row():
244
+ with gr.Column():
245
+ res_txt = gr.Markdown()
246
+ with gr.Column():
247
+ prob_lbl = gr.Label(label="Alpha Probability")
248
+ with gr.Column():
249
+ price_lbl = gr.Label(label="Last Close")
250
 
251
+ scan_btn.click(analyze_asset, ticker_in, [res_txt, chart, prob_lbl, price_lbl])
252
+
253
+ with gr.Tab("πŸ“Š Sector Impact"):
254
+ sector_btn = gr.Button("Refresh Macro View")
255
+ sector_top = gr.Markdown()
256
+ sector_chart = gr.Plot()
257
+ sector_ai = gr.Markdown()
258
+ sector_btn.click(get_sector_analysis, None, [sector_top, sector_chart, sector_ai])
259
+
260
+ with gr.Tab("βš™οΈ Calibration"):
261
+ cal_btn = gr.Button("Train & Sync")
262
+ cal_out = gr.Markdown("Ready")
263
+ # Gr.State is used here to handle the internal progress/state tracking
264
+ cal_btn.click(run_calibration, gr.Textbox(value=",".join(SECTOR_ETFS), visible=False), [cal_out, gr.State()])
265
+
266
+ if __name__ == "__main__":
267
+ init_db()
268
+ load_from_cloud()
269
+ brie.launch()