Spaces:
Running
Running
Update src/streamlit_app.py
Browse files17 unmodified lines1819202122233249 unmodified lines3273327432753276327732786 unmodified lines32853286328732883289329015 unmodified lines330633073308330917 unmodified linesfrom scipy.stats import spearmanr, binom as binom_distfrom sklearn.ensemble import GradientBoostingClassifierfrom huggingface_hub import HfApi, hf_hub_downloadst.set_page_config(page_title="Market Dashboard", page_icon="π", layout="wide")3249 unmodified lines"treating silence as 'all clear.'")# =========================================================# MAIN LAYOUT# =========================================================6 unmodified lines"π§ Rotation Map","π― Combined Scanner","πͺ Catch the Knife",])with tab1:15 unmodified linesrender_combined_scanner()with tab7:render_catch_the_knife()17 unmodified lines181920212223243249 unmodified lines3274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537866 unmodified lines379337943795379637973798379915 unmodified lines381538163817381838193820382117 unmodified linesfrom scipy.stats import spearmanr, binom as binom_distfrom sklearn.ensemble import GradientBoostingClassifierfrom huggingface_hub import HfApi, hf_hub_downloadfrom scipy.signal import find_peaksst.set_page_config(page_title="Market Dashboard", page_icon="π", layout="wide")3249 unmodified lines"treating silence as 'all clear.'")# =========================================================# TAB 8: CYCLE PROJECTOR (manual resolution)# =========================================================## Nested Daily/Weekly/Yearly pivot-low cycle detection, phase-modulated# weekly model + transition-adaptive yearly model. Yearly cycle length is# set MANUALLY per ticker (e.g. BTC needs ~6y or the 2018 low gets merged# into the COVID low) -- automatic cycle-length discovery was tried and# found to underperform manual tuning on every tested ticker, so this tab# keeps the resolution as a direct user input rather than guessing it.#def cp_find_cycle_lows(price: pd.Series, expected_cycle_days: float,prominence_pct: float = 0.05,trend_window_days: float = None) -> pd.DatetimeIndex:"""Detect pivot lows in the DETRENDED series. trend_window_days isindependent of expected_cycle_days (min spacing only)."""log_price = np.log(price.dropna())if trend_window_days is None:trend_window_days = expected_cycle_days * 2trend_window = int(trend_window_days)trend = log_price.rolling(trend_window, center=True,min_periods=max(int(trend_window * 0.25), 30)).mean()detrended = (log_price - trend).dropna()min_spacing = max(int(expected_cycle_days * 0.5), 30)troughs, _ = find_peaks(-detrended.values, distance=min_spacing, prominence=prominence_pct)return detrended.index[troughs]def cp_cycle_stats(lows: pd.DatetimeIndex) -> dict:if len(lows) < 2:return {"mean_days": np.nan, "std_days": np.nan, "n_cycles": 0, "spacing_days": []}spacing = np.diff(lows).astype("timedelta64[D]").astype(int)return {"mean_days": spacing.mean(), "std_days": spacing.std(),"n_cycles": len(spacing), "spacing_days": spacing.tolist()}def cp_project_next_low(lows: pd.DatetimeIndex, stats: dict) -> dict:if len(lows) == 0 or np.isnan(stats["mean_days"]):return {}last_low = lows[-1]eta = last_low + pd.Timedelta(days=stats["mean_days"])std = stats["std_days"] if stats["n_cycles"] >= 4 else stats["mean_days"] * 0.35return {"last_low": last_low, "eta": eta,"window_start": eta - pd.Timedelta(days=std),"window_end": eta + pd.Timedelta(days=std),"low_reliability_warning": stats["n_cycles"] < 4, "n_cycles_used": stats["n_cycles"]}def cp_classify_translation(price: pd.Series, low_start: pd.Timestamp, low_end: pd.Timestamp) -> dict:cycle_slice = price[(price.index >= low_start) & (price.index <= low_end)]if len(cycle_slice) < 5:return {"translation": "insufficient data", "peak_date": None}peak_date = cycle_slice.idxmax()midpoint = low_start + (low_end - low_start) / 2translation = "right (bullish structure)" if peak_date > midpoint else "left (bearish structure)"pct_through = (peak_date - low_start) / (low_end - low_start) * 100return {"translation": translation, "peak_date": peak_date, "pct_through_cycle": pct_through}def cp_get_confirmed_and_candidate_low(price: pd.Series, lows: pd.DatetimeIndex,confirmation_pct: float = 0.05) -> dict:if len(lows) == 0:return {"confirmed_low": None, "candidate_low": None}confirmed_low, candidate_low = None, Nonefor low_date in lows:low_price = price.loc[low_date]after = price.loc[low_date:]threshold = low_price * (1 + confirmation_pct)if (after >= threshold).any():confirmed_low = low_dateelse:candidate_low = low_datetoday = price.index[-1]result = {"confirmed_low": confirmed_low, "candidate_low": candidate_low}if confirmed_low is not None:result["days_since_confirmed"] = (today - confirmed_low).daysif candidate_low is not None:result["days_since_candidate"] = (today - candidate_low).daysreturn resultdef cp_macro_phase_at_date(date: pd.Timestamp, yearly_lows: pd.DatetimeIndex) -> float:if len(yearly_lows) < 2:return np.nanyearly_lows = yearly_lows.sort_values()for i in range(len(yearly_lows) - 1):start, end = yearly_lows[i], yearly_lows[i + 1]if start <= date <= end:duration = (end - start).daysif duration <= 0:return np.nanreturn np.clip((date - start).days / duration, 0.0, 1.0)if date > yearly_lows[-1]:previous, latest = yearly_lows[-2], yearly_lows[-1]cycle_days = (latest - previous).daysif cycle_days <= 0:return np.nanreturn ((date - latest).days / cycle_days) % 1.0return np.nandef cp_classify_cycle_lengths(spacing_days: np.ndarray):q1, q2 = np.quantile(spacing_days, [1 / 3, 2 / 3])def classify(x):return "Short" if x <= q1 else ("Normal" if x <= q2 else "Long")return q1, q2, np.array([classify(x) for x in spacing_days])def cp_fit_phase_modulation(weekly_lows: pd.DatetimeIndex, yearly_lows: pd.DatetimeIndex) -> dict:if len(weekly_lows) < 5 or len(yearly_lows) < 2:return {"valid": False}spacing = np.diff(weekly_lows).astype("timedelta64[D]").astype(int)phases, durations = [], []for i, duration in enumerate(spacing):start, end = weekly_lows[i], weekly_lows[i + 1]midpoint = start + (end - start) / 2phase = cp_macro_phase_at_date(midpoint, yearly_lows)if np.isfinite(phase):phases.append(phase)durations.append(duration)if len(durations) < 8:return {"valid": False}phases, durations = np.asarray(phases, dtype=float), np.asarray(durations, dtype=float)X = np.column_stack([np.ones(len(phases)), np.sin(2*np.pi*phases), np.cos(2*np.pi*phases)])beta, *_ = np.linalg.lstsq(X, durations, rcond=None)return {"valid": True, "beta": beta, "global_mean": float(durations.mean())}def cp_transition_adjustment(spacing_days: np.ndarray) -> dict:if len(spacing_days) < 9:return {"valid": False}q1, q2, categories = cp_classify_cycle_lengths(spacing_days)transition_data = {"Short": [], "Normal": [], "Long": []}for i in range(len(spacing_days) - 1):transition_data[categories[i]].append(spacing_days[i + 1])global_mean = spacing_days.mean()prior_strength = 8multipliers, n_per_category = {}, {}for category, values in transition_data.items():n_per_category[category] = len(values)if len(values) == 0:multipliers[category] = 1.0continueraw_mean = np.mean(values)shrunk = (raw_mean * len(values) + global_mean * prior_strength) / (len(values) + prior_strength)multipliers[category] = shrunk / global_meanreturn {"valid": True, "q1": q1, "q2": q2, "multipliers": multipliers,"n_per_category": n_per_category, "global_mean": global_mean}def cp_build_phase_modulated_wcl_model(weekly_lows, yearly_lows) -> dict:if len(weekly_lows) < 5:return {"valid": False}spacing = np.diff(weekly_lows).astype("timedelta64[D]").astype(int)return {"valid": True, "spacing_days": spacing, "global_mean": float(np.mean(spacing)),"phase_model": cp_fit_phase_modulation(weekly_lows, yearly_lows),"transition_model": cp_transition_adjustment(spacing)}def cp_predict_next_wcl_days(model: dict, last_weekly_low, yearly_lows) -> dict:if not model.get("valid"):return {}global_mean = model["global_mean"]current_phase = cp_macro_phase_at_date(last_weekly_low, yearly_lows)phase_model = model["phase_model"]if phase_model.get("valid") and np.isfinite(current_phase):beta = phase_model["beta"]phase_pred = beta[0] + beta[1]*np.sin(2*np.pi*current_phase) + beta[2]*np.cos(2*np.pi*current_phase)phase_pred = np.clip(phase_pred, global_mean*0.60, global_mean*1.45)else:phase_pred = global_meantransition_model = model["transition_model"]if transition_model.get("valid"):spacing = model["spacing_days"]prev_duration = spacing[-1]q1, q2 = transition_model["q1"], transition_model["q2"]prev_cat = "Short" if prev_duration <= q1 else ("Normal" if prev_duration <= q2 else "Long")mult = transition_model["multipliers"][prev_cat]else:mult = 1.0predicted_days = np.clip(phase_pred * mult, global_mean*0.60, global_mean*1.50)return {"predicted_days": float(predicted_days)}def cp_build_transition_only_model(lows, stats) -> dict:if len(lows) < 2:return {"valid": False}spacing = np.array(stats["spacing_days"], dtype=float)global_mean = stats["mean_days"]if len(spacing) == 0 or np.isnan(global_mean):return {"valid": False}tm = cp_transition_adjustment(spacing)if not tm.get("valid"):return {"valid": True, "predicted_days": float(global_mean), "previous_category": "n/a","n_obs_in_category": 0, "spacing_days": spacing, "used_transition": False}q1, q2 = tm["q1"], tm["q2"]prev_duration = spacing[-1]prev_cat = "Short" if prev_duration <= q1 else ("Normal" if prev_duration <= q2 else "Long")mult = tm["multipliers"][prev_cat]n_obs = tm["n_per_category"][prev_cat]predicted_days = float(np.clip(global_mean * mult, global_mean*0.6, global_mean*1.5))return {"valid": True, "predicted_days": predicted_days, "previous_category": prev_cat,"n_obs_in_category": n_obs, "spacing_days": spacing, "used_transition": True}def cp_project_next_wcl_low(lows, predicted_days, model) -> dict:if len(lows) == 0 or not np.isfinite(predicted_days):return {}last_low = lows[-1]eta = last_low + pd.Timedelta(days=predicted_days)spacing = np.asarray(model["spacing_days"], dtype=float)median = np.median(spacing)mad = np.median(np.abs(spacing - median))robust_std = 1.4826 * madif not np.isfinite(robust_std) or robust_std <= 0:robust_std = np.std(spacing)window_days = max(robust_std, predicted_days * 0.15)return {"last_low": last_low, "eta": eta,"window_start": eta - pd.Timedelta(days=window_days),"window_end": eta + pd.Timedelta(days=window_days),"predicted_days": predicted_days, "n_cycles_used": len(spacing)}def cp_phase_locked_wave(price, lows, predicted_low, view_start, y_frac=0.25, amplitude_frac=0.10):if len(lows) < 2:return None, Nonewave_start = max(pd.Timestamp(view_start), lows[0])dates, values = [], []price_min, price_max = float(price.min()), float(price.max())log_range = np.log(price_max) - np.log(price_min)y_center = np.exp(np.log(price_min) + log_range * y_frac)amplitude = y_center * amplitude_fracdef make_segment(start, end):if end <= start:return None, Noneseg_dates = pd.date_range(start, end, freq="D")duration = max((end - start).days, 1)progress = (seg_dates - start).days / durationphase = -np.pi / 2 + 2 * np.pi * progressreturn seg_dates, y_center + amplitude * np.sin(phase)for i in range(len(lows) - 1):start, end = lows[i], lows[i + 1]if end < wave_start:continuestart = max(start, wave_start)d, v = make_segment(start, end)if d is None:continueif len(dates) > 0:d, v = d[1:], v[1:]dates.extend(d)values.extend(v)if predicted_low:start = max(lows[-1], wave_start)end = predicted_low["eta"]d, v = make_segment(start, end)if d is not None:if len(dates) > 0:d, v = d[1:], v[1:]dates.extend(d)values.extend(v)if not dates:return None, Nonereturn pd.DatetimeIndex(dates), np.asarray(values)def cp_build_nested_cycle_report(price: pd.Series, daily_days=40, weekly_days=200,yearly_days=1460, prominence_daily=0.03,prominence_weekly=0.05, prominence_yearly=0.08) -> dict:daily_lows = cp_find_cycle_lows(price, daily_days, prominence_daily, trend_window_days=weekly_days*1.5)weekly_lows = cp_find_cycle_lows(price, weekly_days, prominence_weekly, trend_window_days=weekly_days*2)yearly_lows = cp_find_cycle_lows(price, yearly_days, prominence_yearly, trend_window_days=yearly_days*2)daily_stats = cp_cycle_stats(daily_lows)weekly_stats = cp_cycle_stats(weekly_lows)yearly_stats = cp_cycle_stats(yearly_lows)wcl_model = cp_build_phase_modulated_wcl_model(weekly_lows, yearly_lows)if wcl_model.get("valid") and len(weekly_lows) > 0:next_wcl = cp_predict_next_wcl_days(wcl_model, weekly_lows[-1], yearly_lows)weekly_adaptive = cp_project_next_wcl_low(weekly_lows, next_wcl["predicted_days"], wcl_model)else:weekly_adaptive = {}standard_weekly_projection = cp_project_next_low(weekly_lows, weekly_stats)yearly_transition_model = cp_build_transition_only_model(yearly_lows, yearly_stats)if yearly_transition_model.get("valid"):yearly_adaptive = cp_project_next_wcl_low(yearly_lows, yearly_transition_model["predicted_days"],yearly_transition_model)else:yearly_adaptive = {}standard_yearly_projection = cp_project_next_low(yearly_lows, yearly_stats)weekly_translations, yearly_translations = [], []for i in range(len(weekly_lows) - 1):t = cp_classify_translation(price, weekly_lows[i], weekly_lows[i+1])t["cycle_start"], t["cycle_end"] = weekly_lows[i], weekly_lows[i+1]weekly_translations.append(t)for i in range(len(yearly_lows) - 1):t = cp_classify_translation(price, yearly_lows[i], yearly_lows[i+1])t["cycle_start"], t["cycle_end"] = yearly_lows[i], yearly_lows[i+1]yearly_translations.append(t)return {"daily": {"lows": daily_lows, "stats": daily_stats,"projection": cp_project_next_low(daily_lows, daily_stats)},"weekly": {"lows": weekly_lows, "stats": weekly_stats,"projection": standard_weekly_projection, "adaptive_projection": weekly_adaptive,"wcl_model": wcl_model, "translations": weekly_translations},"yearly": {"lows": yearly_lows, "stats": yearly_stats,"projection": standard_yearly_projection, "adaptive_projection": yearly_adaptive,"transition_model": yearly_transition_model, "translations": yearly_translations},}def cp_plot_nested_dashboard(price: pd.Series, nested: dict, asset_name: str,view_start: str = "2000-01-01"):view_start_ts = pd.Timestamp(view_start)fig, ax = plt.subplots(figsize=(14, 7))fig.patch.set_facecolor("#0d1321")ax.set_facecolor("#0d1321")ax.plot(price.index, price.values, color="#e8e8e8", lw=1.1, zorder=6)ax.set_yscale("log")for low in nested["daily"]["lows"]:if low >= view_start_ts:ax.plot(low, price.loc[low], marker=".", color="#7aa8d8", ms=4, alpha=0.6, zorder=3)weekly_lows = nested["weekly"]["lows"]for low in weekly_lows:if low >= view_start_ts:ax.plot(low, price.loc[low], marker="^", color="#4a90d9", ms=8, zorder=4)for i in range(len(weekly_lows) - 1):if weekly_lows[i+1] < view_start_ts:continuegap_weeks = (weekly_lows[i+1] - weekly_lows[i]).days / 7mid = weekly_lows[i] + (weekly_lows[i+1] - weekly_lows[i]) / 2y = price.loc[weekly_lows[i]:weekly_lows[i+1]].min() * 0.90ax.annotate(f"{gap_weeks:.0f}W", (mid, y), color="#4a90d9", fontsize=7.5, ha="center", alpha=0.85)yearly_lows = nested["yearly"]["lows"]for low in yearly_lows:if low >= view_start_ts:ax.axvline(low, color="#c9302c", ls=":", lw=0.9, alpha=0.7)ax.plot(low, price.loc[low], marker="D", color="#e8b84b", ms=11, zorder=5,markeredgecolor="#7a5a30", markeredgewidth=0.8)weekly_adaptive = nested["weekly"].get("adaptive_projection", {})wcl_model = nested["weekly"].get("wcl_model", {})weekly_wave_source = weekly_adaptive if wcl_model.get("valid") and weekly_adaptive else nested["weekly"]["projection"]wd, wv = cp_phase_locked_wave(price, weekly_lows, weekly_wave_source, view_start_ts, y_frac=0.25, amplitude_frac=0.10)if wd is not None:ax.plot(wd, wv, color="#4a90d9", lw=1.8, alpha=0.85, zorder=2,label="Weekly cycle rhythm" + (" (adaptive)" if wcl_model.get("valid") else ""))yearly_adaptive = nested["yearly"].get("adaptive_projection", {})yearly_transition_model = nested["yearly"].get("transition_model", {})yearly_wave_source = yearly_adaptive if yearly_adaptive else nested["yearly"]["projection"]yd, yv = cp_phase_locked_wave(price, yearly_lows, yearly_wave_source, view_start_ts, y_frac=0.75, amplitude_frac=0.14)if yd is not None:ax.plot(yd, yv, color="#e8b84b", lw=2, alpha=0.85, zorder=2,label="Yearly cycle rhythm" + (" (adaptive)" if yearly_transition_model.get("used_transition") else ""))wproj = weekly_wave_sourceif wproj:ax.axvspan(wproj["window_start"], wproj["window_end"], color="#4a90d9", alpha=0.15)ax.axvline(wproj["eta"], color="#4a90d9", ls="--", lw=1.2, alpha=0.9)yproj = yearly_wave_sourceif yproj:ax.axvspan(yproj["window_start"], yproj["window_end"], color="#e8b84b", alpha=0.15)ax.axvline(yproj["eta"], color="#e8b84b", ls="--", lw=1.4, alpha=0.9)ax.set_xlim(left=view_start_ts)ax.set_title(f"{asset_name}: nested Daily / Weekly / Yearly cycle lows", color="white", fontsize=12)ax.tick_params(colors="white")for spine in ax.spines.values():spine.set_color("#444")legend_elems = [plt.Line2D([0], [0], marker='.', color='w', markerfacecolor='#7aa8d8', ms=8,label=f"Daily-tier low ({nested['daily']['stats']['n_cycles']} cycles)", ls=''),plt.Line2D([0], [0], marker='^', color='w', markerfacecolor='#4a90d9', ms=9,label=f"Weekly-tier low ({nested['weekly']['stats']['n_cycles']} cycles)", ls=''),plt.Line2D([0], [0], marker='D', color='w', markerfacecolor='#e8b84b', ms=9,label=f"Yearly-tier low ({nested['yearly']['stats']['n_cycles']} cycles)", ls=''),]if wproj:legend_elems.append(plt.Line2D([0], [0], color='#4a90d9', ls='--', lw=1.5,label=f"Next weekly low: {wproj['eta'].date()}"))if yproj:low_rel = nested["yearly"]["stats"]["n_cycles"] < 4tm = nested["yearly"].get("transition_model", {})n_obs = tm.get("n_obs_in_category")obs_note = f", n={n_obs} in category" if tm.get("used_transition") and n_obs is not None else ""legend_elems.append(plt.Line2D([0], [0], color='#e8b84b', ls='--', lw=1.5,label=f"Next yearly low: {yproj['eta'].date()}"+ (" [low reliability]" if low_rel else "") + obs_note))ax.legend(handles=legend_elems, loc="upper left", facecolor="#1a2036",labelcolor="white", framealpha=0.85, fontsize=8.5)plt.tight_layout()return figdef render_cycle_projector_tab():st.title("πͺ Cycle Projector")st.caption("Nested Daily/Weekly/Yearly pivot-low detection with a phase-modulated weekly model ""and a transition-adaptive yearly model (Short/Normal/Long-conditioned band, not a ""point forecast). Yearly resolution is set MANUALLY per ticker β auto-detection was ""tested and found to underperform manual tuning on BTC, gold, and Nasdaq alike, so ""this tab keeps you in the loop on that call.")with st.sidebar:st.markdown("---")st.header("Cycle Projector")cp_ticker = st.text_input("Ticker (yfinance format)", value="BTC-USD", key="cp_ticker")cp_yearly_years = st.number_input("Yearly cycle resolution (years)", min_value=1.0, max_value=15.0,value=6.0, step=0.25, key="cp_yearly_years",help="BTC needed ~6y or the 2018 low merges into the COVID low. ""Gold and Nasdaq will likely need different values β tune per ticker.")with st.expander("Advanced settings"):cp_daily_days = st.number_input("Daily cycle length (days)", value=40, step=5, key="cp_daily_days")cp_weekly_days = st.number_input("Weekly cycle length (days)", value=200, step=10, key="cp_weekly_days")cp_prom_daily = st.slider("Daily prominence", 0.01, 0.20, 0.03, 0.01, key="cp_prom_daily")cp_prom_weekly = st.slider("Weekly prominence", 0.01, 0.20, 0.05, 0.01, key="cp_prom_weekly")cp_prom_yearly = st.slider("Yearly prominence", 0.01, 0.30, 0.08, 0.01, key="cp_prom_yearly")cp_view_start = st.text_input("Chart view start (YYYY-MM-DD)", value="2000-01-01", key="cp_view_start")cp_run = st.button("βΆοΈ Run", key="cp_run")if not cp_run:st.info("Set a ticker and yearly resolution in the sidebar, then click Run.")returnwith st.spinner(f"Fetching {cp_ticker}β¦"):data = yf.download(cp_ticker, period="max", auto_adjust=True, progress=False)if data.empty:st.error(f"No data returned for '{cp_ticker}'.")returnprice = data["Close"]if isinstance(price, pd.DataFrame):price = price.iloc[:, 0]nested = cp_build_nested_cycle_report(price, daily_days=cp_daily_days, weekly_days=cp_weekly_days,yearly_days=cp_yearly_years * 365.25,prominence_daily=cp_prom_daily, prominence_weekly=cp_prom_weekly,prominence_yearly=cp_prom_yearly,)if nested["weekly"]["stats"]["n_cycles"] == 0 and nested["yearly"]["stats"]["n_cycles"] == 0:st.warning("No valid lows found at this resolution/prominence β try adjusting the sliders.")returnwstats, ystats = nested["weekly"]["stats"], nested["yearly"]["stats"]c1, c2, c3, c4 = st.columns(4)c1.metric("Weekly cycle avg", f"{wstats['mean_days']/7:.0f}w" if wstats["n_cycles"] else "n/a")c2.metric("Yearly cycle avg", f"{ystats['mean_days']/365.25:.2f}y" if ystats["n_cycles"] else "n/a")c3.metric("Weekly cycles found", wstats["n_cycles"])c4.metric("Yearly cycles found", ystats["n_cycles"])if ystats["n_cycles"] < 4:st.warning(f"Only {ystats['n_cycles']} completed yearly cycles β treat the yearly window as very rough.")wproj = nested["weekly"]["adaptive_projection"] or nested["weekly"]["projection"]yproj = nested["yearly"]["adaptive_projection"] or nested["yearly"]["projection"]if wproj:st.info(f"**Next weekly-tier low:** {wproj['eta'].strftime('%Y-%m-%d')} "f"(window: {wproj['window_start'].strftime('%Y-%m-%d')} to {wproj['window_end'].strftime('%Y-%m-%d')})")if yproj:ytm = nested["yearly"]["transition_model"]note = ""if ytm.get("used_transition"):note = f" (adaptive, {ytm['previous_category']} category, n={ytm['n_obs_in_category']} prior obs)"st.info(f"**Next yearly-tier low{note}:** {yproj['eta'].strftime('%Y-%m-%d')} "f"(window: {yproj['window_start'].strftime('%Y-%m-%d')} to {yproj['window_end'].strftime('%Y-%m-%d')})")fig = cp_plot_nested_dashboard(price, nested, cp_ticker, view_start=cp_view_start)st.pyplot(fig)plt.close(fig)conf = cp_get_confirmed_and_candidate_low(price, nested["weekly"]["lows"])cA, cB = st.columns(2)if conf.get("confirmed_low") is not None:cA.success(f"β Confirmed weekly-tier low: {conf['confirmed_low'].date()} ({conf['days_since_confirmed']}d ago)")else:cA.info("β Confirmed low: none yet")if conf.get("candidate_low") is not None:cB.warning(f"β Unconfirmed candidate: {conf['candidate_low'].date()} ({conf['days_since_candidate']}d ago)")else:cB.info("β Unconfirmed candidate: none")with st.expander("Weekly-tier translation per completed cycle"):for t in nested["weekly"]["translations"]:peak_str = t['peak_date'].date() if t['peak_date'] else 'n/a'st.write(f"{t['cycle_start'].date()} β {t['cycle_end'].date()}: **{t['translation']}** "f"(peak at {t['pct_through_cycle']:.0f}% through the cycle, {peak_str})")# =========================================================# MAIN LAYOUT# =========================================================6 unmodified lines"π§ Rotation Map","π― Combined Scanner","πͺ Catch the Knife","πͺ Cycle Projector",])with tab1:15 unmodified linesrender_combined_scanner()with tab7:render_catch_the_knife()with tab8:render_cycle_projector_tab()
src/streamlit_app.py+513-1