Spaces:
Sleeping
Sleeping
Update app.py
Browse files381 unmodified lines382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433381 unmodified linesprog.progress(85, text="Computing interpretation...")# Dynamic Interpretation (same logic as raw)try:phase_series = pd.Series(phase, index=comp.index)current_date = phase_series.index[-1]current_phase = phase_series.iloc[-1]current_comp = comp_sm.loc[current_date]current_slope = slope.loc[current_date]current_spx_yoy = spx_yoy.loc[current_date]interp = ""if current_phase == 'Early':interp = (f"As of {current_date.date()}, the composite is {current_comp:.2f} "f"(+{current_slope:.3f} over {int(slope_window)}m) and S&P YoY is {current_spx_yoy:.1f}%. ""Early-phase conditions indicate nascent expansion. ""Leading activity indicators have bottomed and credit spreads are narrowing. ""Selective exposure to cyclical sectors may capture emerging growth while risks remain contained.")elif current_phase == 'Mid-Late':interp = (f"As of {current_date.date()}, the composite stands at {current_comp:.2f} "f"(slope {current_slope:.3f}) with S&P YoY {current_spx_yoy:.1f}%. ""Mid-to-late cycle signals peak growth. ""Inflationary pressures and monetary tightening typically intensify in this phase. ""Shift allocation toward high-quality equities and defensive sectors to protect gains.")elif current_phase == 'Decline':interp = (f"As of {current_date.date()}, the composite reads {current_comp:.2f} "f"(slope {current_slope:.3f}) and S&P YoY is {current_spx_yoy:.1f}%. ""Decline-phase patterns signal contraction. ""Risk sentiment deteriorates and liquidity tightens. ""Consider de-risking portfolios: increase fixed income, cash buffers, and low-volatility assets.")elif current_phase == 'Uncertain':interp = (f"As of {current_date.date()}, the composite is neutral at {current_comp:.2f} "f"(slope {current_slope:.3f}) with S&P YoY {current_spx_yoy:.1f}%. ""Signals conflict and volatility often rises. ""Maintain balanced allocations, await clearer directional cues, and manage risk with disciplined stops.")else:interp = "Phase classification unavailable."with st.expander("Dynamic Interpretation", expanded=False):st.write(interp)except Exception:st.error("Failed to produce the interpretation.")381 unmodified lines382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492381 unmodified linesprog.progress(85, text="Computing interpretation...")# Dynamic Interpretation (richer, more explanatory)try:phase_series = pd.Series(phase, index=comp.index)current_date = phase_series.index[-1]current_phase = phase_series.iloc[-1]current_comp = comp_sm.loc[current_date]current_comp_raw = comp.loc[current_date]current_slope = slope.loc[current_date]current_spx_yoy = spx_yoy.loc[current_date]# Percentiles (rank-based, full sample)comp_pct = float(comp_sm.dropna().rank(pct=True).loc[current_date] * 100)spx_pct = float(spx_yoy.dropna().rank(pct=True).loc[current_date] * 100)# Phase run length (periods and months)changes = phase_series.ne(phase_series.shift())last_change_idx = changes[changes].index[-1]periods_in_phase = phase_series.index.get_loc(current_date) - phase_series.index.get_loc(last_change_idx) + 1if freq == "QE":months_in_phase = periods_in_phase * 3period_label = "quarters"else:months_in_phase = periods_in_phaseperiod_label = "months"# Breadth and contributorsz_now = z.loc[current_date].dropna()inputs_now = z_now.reindex(inputs).dropna()breadth_pos = float((inputs_now > 0).mean() * 100)top_pos = inputs_now.sort_values(ascending=False).head(3)top_neg = inputs_now.sort_values(ascending=True).head(3)def fmt_contrib(s):return ", ".join([f"{k} ({v:+.1f}σ)" for k, v in s.items()]) if len(s) else "n/a"# Phase-specific read-through and triggersphase_notes = []triggers = []if current_phase == 'Early':phase_notes += ["Growth is turning up from a weak base.","Leading activity improves. Credit spreads narrow.","Rate momentum eases on a 12-month view."]triggers += [f"Upside: composite raw > {comp_thr:.2f}.",f"Risk: slope < -{slope_thr:.3f} or composite raw > {-comp_thr:.2f}."]elif current_phase == 'Mid-Late':phase_notes += ["Growth remains above average but is slowing.","Pricing pressure and policy tightness rise.","Quality bias tends to help risk control."]triggers += [f"Loss of momentum: composite raw < {comp_thr:.2f}.",f"Downside break: composite raw < {-comp_thr:.2f}."]elif current_phase == 'Decline':phase_notes += ["Activity contracts. Risk appetite weakens.","Credit and liquidity conditions worsen.","Drawdown risk is elevated relative to trend."]triggers += [f"Repair: slope > +{slope_thr:.3f}.",f"Exit contraction: composite raw > {-comp_thr:.2f}."]elif current_phase == 'Uncertain':phase_notes += ["Signals conflict. Noise is high.","Avoid strong tilts until direction clears.","Use position sizing and stops."]triggers += [f"Upside regime: composite raw > {comp_thr:.2f}.",f"Early setup: composite raw < {-comp_thr:.2f} and slope > +{slope_thr:.3f}.",f"Decline setup: composite raw < {-comp_thr:.2f} and slope < -{slope_thr:.3f}."]else:phase_notes.append("Phase classification unavailable.")# Build markdowninterp_md = f"""**As of {current_date.date()}**- Phase: **{current_phase}** for {periods_in_phase} {period_label} (~{months_in_phase} months).- Composite (smoothed): {current_comp:.2f} (p{comp_pct:.0f}). Raw: {current_comp_raw:.2f}.- Slope over {int(slope_window)}m: {current_slope:+.3f}.- S&P 500 YoY: {current_spx_yoy:.1f}% (p{spx_pct:.0f}).- Breadth: {breadth_pos:.0f}% of inputs > 0.**What drives the score now**- Positive: {fmt_contrib(top_pos)}- Negative: {fmt_contrib(top_neg)}**Phase read-through**""" + "\n".join([f"- {line}" for line in phase_notes]) + """**Triggers to watch**""" + "\n".join([f"- {t}" for t in triggers])with st.expander("Dynamic Interpretation", expanded=False):st.markdown(interp_md)except Exception:st.error("Failed to produce the interpretation.")
app.py+90-31