Spaces:
Running
Running
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +513 -1
src/streamlit_app.py
CHANGED
|
@@ -18,6 +18,7 @@ from numpy.lib.stride_tricks import sliding_window_view
|
|
| 18 |
from scipy.stats import spearmanr, binom as binom_dist
|
| 19 |
from sklearn.ensemble import GradientBoostingClassifier
|
| 20 |
from huggingface_hub import HfApi, hf_hub_download
|
|
|
|
| 21 |
|
| 22 |
st.set_page_config(page_title="Market Dashboard", page_icon="π", layout="wide")
|
| 23 |
|
|
@@ -3273,6 +3274,513 @@ mention "proceeds" near "repay.")
|
|
| 3273 |
"treating silence as 'all clear.'")
|
| 3274 |
|
| 3275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3276 |
# =========================================================
|
| 3277 |
# MAIN LAYOUT
|
| 3278 |
# =========================================================
|
|
@@ -3285,6 +3793,7 @@ tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
|
|
| 3285 |
"π§ Rotation Map",
|
| 3286 |
"π― Combined Scanner",
|
| 3287 |
"πͺ Catch the Knife",
|
|
|
|
| 3288 |
])
|
| 3289 |
|
| 3290 |
with tab1:
|
|
@@ -3306,4 +3815,7 @@ with tab6:
|
|
| 3306 |
render_combined_scanner()
|
| 3307 |
|
| 3308 |
with tab7:
|
| 3309 |
-
render_catch_the_knife()
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from scipy.stats import spearmanr, binom as binom_dist
|
| 19 |
from sklearn.ensemble import GradientBoostingClassifier
|
| 20 |
from huggingface_hub import HfApi, hf_hub_download
|
| 21 |
+
from scipy.signal import find_peaks
|
| 22 |
|
| 23 |
st.set_page_config(page_title="Market Dashboard", page_icon="π", layout="wide")
|
| 24 |
|
|
|
|
| 3274 |
"treating silence as 'all clear.'")
|
| 3275 |
|
| 3276 |
|
| 3277 |
+
# =========================================================
|
| 3278 |
+
# TAB 8: CYCLE PROJECTOR (manual resolution)
|
| 3279 |
+
# =========================================================
|
| 3280 |
+
#
|
| 3281 |
+
# Nested Daily/Weekly/Yearly pivot-low cycle detection, phase-modulated
|
| 3282 |
+
# weekly model + transition-adaptive yearly model. Yearly cycle length is
|
| 3283 |
+
# set MANUALLY per ticker (e.g. BTC needs ~6y or the 2018 low gets merged
|
| 3284 |
+
# into the COVID low) -- automatic cycle-length discovery was tried and
|
| 3285 |
+
# found to underperform manual tuning on every tested ticker, so this tab
|
| 3286 |
+
# keeps the resolution as a direct user input rather than guessing it.
|
| 3287 |
+
#
|
| 3288 |
+
|
| 3289 |
+
def cp_find_cycle_lows(price: pd.Series, expected_cycle_days: float,
|
| 3290 |
+
prominence_pct: float = 0.05,
|
| 3291 |
+
trend_window_days: float = None) -> pd.DatetimeIndex:
|
| 3292 |
+
"""Detect pivot lows in the DETRENDED series. trend_window_days is
|
| 3293 |
+
independent of expected_cycle_days (min spacing only)."""
|
| 3294 |
+
log_price = np.log(price.dropna())
|
| 3295 |
+
if trend_window_days is None:
|
| 3296 |
+
trend_window_days = expected_cycle_days * 2
|
| 3297 |
+
trend_window = int(trend_window_days)
|
| 3298 |
+
trend = log_price.rolling(trend_window, center=True,
|
| 3299 |
+
min_periods=max(int(trend_window * 0.25), 30)).mean()
|
| 3300 |
+
detrended = (log_price - trend).dropna()
|
| 3301 |
+
min_spacing = max(int(expected_cycle_days * 0.5), 30)
|
| 3302 |
+
troughs, _ = find_peaks(-detrended.values, distance=min_spacing, prominence=prominence_pct)
|
| 3303 |
+
return detrended.index[troughs]
|
| 3304 |
+
|
| 3305 |
+
|
| 3306 |
+
def cp_cycle_stats(lows: pd.DatetimeIndex) -> dict:
|
| 3307 |
+
if len(lows) < 2:
|
| 3308 |
+
return {"mean_days": np.nan, "std_days": np.nan, "n_cycles": 0, "spacing_days": []}
|
| 3309 |
+
spacing = np.diff(lows).astype("timedelta64[D]").astype(int)
|
| 3310 |
+
return {"mean_days": spacing.mean(), "std_days": spacing.std(),
|
| 3311 |
+
"n_cycles": len(spacing), "spacing_days": spacing.tolist()}
|
| 3312 |
+
|
| 3313 |
+
|
| 3314 |
+
def cp_project_next_low(lows: pd.DatetimeIndex, stats: dict) -> dict:
|
| 3315 |
+
if len(lows) == 0 or np.isnan(stats["mean_days"]):
|
| 3316 |
+
return {}
|
| 3317 |
+
last_low = lows[-1]
|
| 3318 |
+
eta = last_low + pd.Timedelta(days=stats["mean_days"])
|
| 3319 |
+
std = stats["std_days"] if stats["n_cycles"] >= 4 else stats["mean_days"] * 0.35
|
| 3320 |
+
return {"last_low": last_low, "eta": eta,
|
| 3321 |
+
"window_start": eta - pd.Timedelta(days=std),
|
| 3322 |
+
"window_end": eta + pd.Timedelta(days=std),
|
| 3323 |
+
"low_reliability_warning": stats["n_cycles"] < 4, "n_cycles_used": stats["n_cycles"]}
|
| 3324 |
+
|
| 3325 |
+
|
| 3326 |
+
def cp_classify_translation(price: pd.Series, low_start: pd.Timestamp, low_end: pd.Timestamp) -> dict:
|
| 3327 |
+
cycle_slice = price[(price.index >= low_start) & (price.index <= low_end)]
|
| 3328 |
+
if len(cycle_slice) < 5:
|
| 3329 |
+
return {"translation": "insufficient data", "peak_date": None}
|
| 3330 |
+
peak_date = cycle_slice.idxmax()
|
| 3331 |
+
midpoint = low_start + (low_end - low_start) / 2
|
| 3332 |
+
translation = "right (bullish structure)" if peak_date > midpoint else "left (bearish structure)"
|
| 3333 |
+
pct_through = (peak_date - low_start) / (low_end - low_start) * 100
|
| 3334 |
+
return {"translation": translation, "peak_date": peak_date, "pct_through_cycle": pct_through}
|
| 3335 |
+
|
| 3336 |
+
|
| 3337 |
+
def cp_get_confirmed_and_candidate_low(price: pd.Series, lows: pd.DatetimeIndex,
|
| 3338 |
+
confirmation_pct: float = 0.05) -> dict:
|
| 3339 |
+
if len(lows) == 0:
|
| 3340 |
+
return {"confirmed_low": None, "candidate_low": None}
|
| 3341 |
+
confirmed_low, candidate_low = None, None
|
| 3342 |
+
for low_date in lows:
|
| 3343 |
+
low_price = price.loc[low_date]
|
| 3344 |
+
after = price.loc[low_date:]
|
| 3345 |
+
threshold = low_price * (1 + confirmation_pct)
|
| 3346 |
+
if (after >= threshold).any():
|
| 3347 |
+
confirmed_low = low_date
|
| 3348 |
+
else:
|
| 3349 |
+
candidate_low = low_date
|
| 3350 |
+
today = price.index[-1]
|
| 3351 |
+
result = {"confirmed_low": confirmed_low, "candidate_low": candidate_low}
|
| 3352 |
+
if confirmed_low is not None:
|
| 3353 |
+
result["days_since_confirmed"] = (today - confirmed_low).days
|
| 3354 |
+
if candidate_low is not None:
|
| 3355 |
+
result["days_since_candidate"] = (today - candidate_low).days
|
| 3356 |
+
return result
|
| 3357 |
+
|
| 3358 |
+
|
| 3359 |
+
def cp_macro_phase_at_date(date: pd.Timestamp, yearly_lows: pd.DatetimeIndex) -> float:
|
| 3360 |
+
if len(yearly_lows) < 2:
|
| 3361 |
+
return np.nan
|
| 3362 |
+
yearly_lows = yearly_lows.sort_values()
|
| 3363 |
+
for i in range(len(yearly_lows) - 1):
|
| 3364 |
+
start, end = yearly_lows[i], yearly_lows[i + 1]
|
| 3365 |
+
if start <= date <= end:
|
| 3366 |
+
duration = (end - start).days
|
| 3367 |
+
if duration <= 0:
|
| 3368 |
+
return np.nan
|
| 3369 |
+
return np.clip((date - start).days / duration, 0.0, 1.0)
|
| 3370 |
+
if date > yearly_lows[-1]:
|
| 3371 |
+
previous, latest = yearly_lows[-2], yearly_lows[-1]
|
| 3372 |
+
cycle_days = (latest - previous).days
|
| 3373 |
+
if cycle_days <= 0:
|
| 3374 |
+
return np.nan
|
| 3375 |
+
return ((date - latest).days / cycle_days) % 1.0
|
| 3376 |
+
return np.nan
|
| 3377 |
+
|
| 3378 |
+
|
| 3379 |
+
def cp_classify_cycle_lengths(spacing_days: np.ndarray):
|
| 3380 |
+
q1, q2 = np.quantile(spacing_days, [1 / 3, 2 / 3])
|
| 3381 |
+
|
| 3382 |
+
def classify(x):
|
| 3383 |
+
return "Short" if x <= q1 else ("Normal" if x <= q2 else "Long")
|
| 3384 |
+
return q1, q2, np.array([classify(x) for x in spacing_days])
|
| 3385 |
+
|
| 3386 |
+
|
| 3387 |
+
def cp_fit_phase_modulation(weekly_lows: pd.DatetimeIndex, yearly_lows: pd.DatetimeIndex) -> dict:
|
| 3388 |
+
if len(weekly_lows) < 5 or len(yearly_lows) < 2:
|
| 3389 |
+
return {"valid": False}
|
| 3390 |
+
spacing = np.diff(weekly_lows).astype("timedelta64[D]").astype(int)
|
| 3391 |
+
phases, durations = [], []
|
| 3392 |
+
for i, duration in enumerate(spacing):
|
| 3393 |
+
start, end = weekly_lows[i], weekly_lows[i + 1]
|
| 3394 |
+
midpoint = start + (end - start) / 2
|
| 3395 |
+
phase = cp_macro_phase_at_date(midpoint, yearly_lows)
|
| 3396 |
+
if np.isfinite(phase):
|
| 3397 |
+
phases.append(phase)
|
| 3398 |
+
durations.append(duration)
|
| 3399 |
+
if len(durations) < 8:
|
| 3400 |
+
return {"valid": False}
|
| 3401 |
+
phases, durations = np.asarray(phases, dtype=float), np.asarray(durations, dtype=float)
|
| 3402 |
+
X = np.column_stack([np.ones(len(phases)), np.sin(2*np.pi*phases), np.cos(2*np.pi*phases)])
|
| 3403 |
+
beta, *_ = np.linalg.lstsq(X, durations, rcond=None)
|
| 3404 |
+
return {"valid": True, "beta": beta, "global_mean": float(durations.mean())}
|
| 3405 |
+
|
| 3406 |
+
|
| 3407 |
+
def cp_transition_adjustment(spacing_days: np.ndarray) -> dict:
|
| 3408 |
+
if len(spacing_days) < 9:
|
| 3409 |
+
return {"valid": False}
|
| 3410 |
+
q1, q2, categories = cp_classify_cycle_lengths(spacing_days)
|
| 3411 |
+
transition_data = {"Short": [], "Normal": [], "Long": []}
|
| 3412 |
+
for i in range(len(spacing_days) - 1):
|
| 3413 |
+
transition_data[categories[i]].append(spacing_days[i + 1])
|
| 3414 |
+
global_mean = spacing_days.mean()
|
| 3415 |
+
prior_strength = 8
|
| 3416 |
+
multipliers, n_per_category = {}, {}
|
| 3417 |
+
for category, values in transition_data.items():
|
| 3418 |
+
n_per_category[category] = len(values)
|
| 3419 |
+
if len(values) == 0:
|
| 3420 |
+
multipliers[category] = 1.0
|
| 3421 |
+
continue
|
| 3422 |
+
raw_mean = np.mean(values)
|
| 3423 |
+
shrunk = (raw_mean * len(values) + global_mean * prior_strength) / (len(values) + prior_strength)
|
| 3424 |
+
multipliers[category] = shrunk / global_mean
|
| 3425 |
+
return {"valid": True, "q1": q1, "q2": q2, "multipliers": multipliers,
|
| 3426 |
+
"n_per_category": n_per_category, "global_mean": global_mean}
|
| 3427 |
+
|
| 3428 |
+
|
| 3429 |
+
def cp_build_phase_modulated_wcl_model(weekly_lows, yearly_lows) -> dict:
|
| 3430 |
+
if len(weekly_lows) < 5:
|
| 3431 |
+
return {"valid": False}
|
| 3432 |
+
spacing = np.diff(weekly_lows).astype("timedelta64[D]").astype(int)
|
| 3433 |
+
return {"valid": True, "spacing_days": spacing, "global_mean": float(np.mean(spacing)),
|
| 3434 |
+
"phase_model": cp_fit_phase_modulation(weekly_lows, yearly_lows),
|
| 3435 |
+
"transition_model": cp_transition_adjustment(spacing)}
|
| 3436 |
+
|
| 3437 |
+
|
| 3438 |
+
def cp_predict_next_wcl_days(model: dict, last_weekly_low, yearly_lows) -> dict:
|
| 3439 |
+
if not model.get("valid"):
|
| 3440 |
+
return {}
|
| 3441 |
+
global_mean = model["global_mean"]
|
| 3442 |
+
current_phase = cp_macro_phase_at_date(last_weekly_low, yearly_lows)
|
| 3443 |
+
phase_model = model["phase_model"]
|
| 3444 |
+
if phase_model.get("valid") and np.isfinite(current_phase):
|
| 3445 |
+
beta = phase_model["beta"]
|
| 3446 |
+
phase_pred = beta[0] + beta[1]*np.sin(2*np.pi*current_phase) + beta[2]*np.cos(2*np.pi*current_phase)
|
| 3447 |
+
phase_pred = np.clip(phase_pred, global_mean*0.60, global_mean*1.45)
|
| 3448 |
+
else:
|
| 3449 |
+
phase_pred = global_mean
|
| 3450 |
+
transition_model = model["transition_model"]
|
| 3451 |
+
if transition_model.get("valid"):
|
| 3452 |
+
spacing = model["spacing_days"]
|
| 3453 |
+
prev_duration = spacing[-1]
|
| 3454 |
+
q1, q2 = transition_model["q1"], transition_model["q2"]
|
| 3455 |
+
prev_cat = "Short" if prev_duration <= q1 else ("Normal" if prev_duration <= q2 else "Long")
|
| 3456 |
+
mult = transition_model["multipliers"][prev_cat]
|
| 3457 |
+
else:
|
| 3458 |
+
mult = 1.0
|
| 3459 |
+
predicted_days = np.clip(phase_pred * mult, global_mean*0.60, global_mean*1.50)
|
| 3460 |
+
return {"predicted_days": float(predicted_days)}
|
| 3461 |
+
|
| 3462 |
+
|
| 3463 |
+
def cp_build_transition_only_model(lows, stats) -> dict:
|
| 3464 |
+
if len(lows) < 2:
|
| 3465 |
+
return {"valid": False}
|
| 3466 |
+
spacing = np.array(stats["spacing_days"], dtype=float)
|
| 3467 |
+
global_mean = stats["mean_days"]
|
| 3468 |
+
if len(spacing) == 0 or np.isnan(global_mean):
|
| 3469 |
+
return {"valid": False}
|
| 3470 |
+
tm = cp_transition_adjustment(spacing)
|
| 3471 |
+
if not tm.get("valid"):
|
| 3472 |
+
return {"valid": True, "predicted_days": float(global_mean), "previous_category": "n/a",
|
| 3473 |
+
"n_obs_in_category": 0, "spacing_days": spacing, "used_transition": False}
|
| 3474 |
+
q1, q2 = tm["q1"], tm["q2"]
|
| 3475 |
+
prev_duration = spacing[-1]
|
| 3476 |
+
prev_cat = "Short" if prev_duration <= q1 else ("Normal" if prev_duration <= q2 else "Long")
|
| 3477 |
+
mult = tm["multipliers"][prev_cat]
|
| 3478 |
+
n_obs = tm["n_per_category"][prev_cat]
|
| 3479 |
+
predicted_days = float(np.clip(global_mean * mult, global_mean*0.6, global_mean*1.5))
|
| 3480 |
+
return {"valid": True, "predicted_days": predicted_days, "previous_category": prev_cat,
|
| 3481 |
+
"n_obs_in_category": n_obs, "spacing_days": spacing, "used_transition": True}
|
| 3482 |
+
|
| 3483 |
+
|
| 3484 |
+
def cp_project_next_wcl_low(lows, predicted_days, model) -> dict:
|
| 3485 |
+
if len(lows) == 0 or not np.isfinite(predicted_days):
|
| 3486 |
+
return {}
|
| 3487 |
+
last_low = lows[-1]
|
| 3488 |
+
eta = last_low + pd.Timedelta(days=predicted_days)
|
| 3489 |
+
spacing = np.asarray(model["spacing_days"], dtype=float)
|
| 3490 |
+
median = np.median(spacing)
|
| 3491 |
+
mad = np.median(np.abs(spacing - median))
|
| 3492 |
+
robust_std = 1.4826 * mad
|
| 3493 |
+
if not np.isfinite(robust_std) or robust_std <= 0:
|
| 3494 |
+
robust_std = np.std(spacing)
|
| 3495 |
+
window_days = max(robust_std, predicted_days * 0.15)
|
| 3496 |
+
return {"last_low": last_low, "eta": eta,
|
| 3497 |
+
"window_start": eta - pd.Timedelta(days=window_days),
|
| 3498 |
+
"window_end": eta + pd.Timedelta(days=window_days),
|
| 3499 |
+
"predicted_days": predicted_days, "n_cycles_used": len(spacing)}
|
| 3500 |
+
|
| 3501 |
+
|
| 3502 |
+
def cp_phase_locked_wave(price, lows, predicted_low, view_start, y_frac=0.25, amplitude_frac=0.10):
|
| 3503 |
+
if len(lows) < 2:
|
| 3504 |
+
return None, None
|
| 3505 |
+
wave_start = max(pd.Timestamp(view_start), lows[0])
|
| 3506 |
+
dates, values = [], []
|
| 3507 |
+
price_min, price_max = float(price.min()), float(price.max())
|
| 3508 |
+
log_range = np.log(price_max) - np.log(price_min)
|
| 3509 |
+
y_center = np.exp(np.log(price_min) + log_range * y_frac)
|
| 3510 |
+
amplitude = y_center * amplitude_frac
|
| 3511 |
+
|
| 3512 |
+
def make_segment(start, end):
|
| 3513 |
+
if end <= start:
|
| 3514 |
+
return None, None
|
| 3515 |
+
seg_dates = pd.date_range(start, end, freq="D")
|
| 3516 |
+
duration = max((end - start).days, 1)
|
| 3517 |
+
progress = (seg_dates - start).days / duration
|
| 3518 |
+
phase = -np.pi / 2 + 2 * np.pi * progress
|
| 3519 |
+
return seg_dates, y_center + amplitude * np.sin(phase)
|
| 3520 |
+
|
| 3521 |
+
for i in range(len(lows) - 1):
|
| 3522 |
+
start, end = lows[i], lows[i + 1]
|
| 3523 |
+
if end < wave_start:
|
| 3524 |
+
continue
|
| 3525 |
+
start = max(start, wave_start)
|
| 3526 |
+
d, v = make_segment(start, end)
|
| 3527 |
+
if d is None:
|
| 3528 |
+
continue
|
| 3529 |
+
if len(dates) > 0:
|
| 3530 |
+
d, v = d[1:], v[1:]
|
| 3531 |
+
dates.extend(d)
|
| 3532 |
+
values.extend(v)
|
| 3533 |
+
|
| 3534 |
+
if predicted_low:
|
| 3535 |
+
start = max(lows[-1], wave_start)
|
| 3536 |
+
end = predicted_low["eta"]
|
| 3537 |
+
d, v = make_segment(start, end)
|
| 3538 |
+
if d is not None:
|
| 3539 |
+
if len(dates) > 0:
|
| 3540 |
+
d, v = d[1:], v[1:]
|
| 3541 |
+
dates.extend(d)
|
| 3542 |
+
values.extend(v)
|
| 3543 |
+
|
| 3544 |
+
if not dates:
|
| 3545 |
+
return None, None
|
| 3546 |
+
return pd.DatetimeIndex(dates), np.asarray(values)
|
| 3547 |
+
|
| 3548 |
+
|
| 3549 |
+
def cp_build_nested_cycle_report(price: pd.Series, daily_days=40, weekly_days=200,
|
| 3550 |
+
yearly_days=1460, prominence_daily=0.03,
|
| 3551 |
+
prominence_weekly=0.05, prominence_yearly=0.08) -> dict:
|
| 3552 |
+
daily_lows = cp_find_cycle_lows(price, daily_days, prominence_daily, trend_window_days=weekly_days*1.5)
|
| 3553 |
+
weekly_lows = cp_find_cycle_lows(price, weekly_days, prominence_weekly, trend_window_days=weekly_days*2)
|
| 3554 |
+
yearly_lows = cp_find_cycle_lows(price, yearly_days, prominence_yearly, trend_window_days=yearly_days*2)
|
| 3555 |
+
|
| 3556 |
+
daily_stats = cp_cycle_stats(daily_lows)
|
| 3557 |
+
weekly_stats = cp_cycle_stats(weekly_lows)
|
| 3558 |
+
yearly_stats = cp_cycle_stats(yearly_lows)
|
| 3559 |
+
|
| 3560 |
+
wcl_model = cp_build_phase_modulated_wcl_model(weekly_lows, yearly_lows)
|
| 3561 |
+
if wcl_model.get("valid") and len(weekly_lows) > 0:
|
| 3562 |
+
next_wcl = cp_predict_next_wcl_days(wcl_model, weekly_lows[-1], yearly_lows)
|
| 3563 |
+
weekly_adaptive = cp_project_next_wcl_low(weekly_lows, next_wcl["predicted_days"], wcl_model)
|
| 3564 |
+
else:
|
| 3565 |
+
weekly_adaptive = {}
|
| 3566 |
+
standard_weekly_projection = cp_project_next_low(weekly_lows, weekly_stats)
|
| 3567 |
+
|
| 3568 |
+
yearly_transition_model = cp_build_transition_only_model(yearly_lows, yearly_stats)
|
| 3569 |
+
if yearly_transition_model.get("valid"):
|
| 3570 |
+
yearly_adaptive = cp_project_next_wcl_low(yearly_lows, yearly_transition_model["predicted_days"],
|
| 3571 |
+
yearly_transition_model)
|
| 3572 |
+
else:
|
| 3573 |
+
yearly_adaptive = {}
|
| 3574 |
+
standard_yearly_projection = cp_project_next_low(yearly_lows, yearly_stats)
|
| 3575 |
+
|
| 3576 |
+
weekly_translations, yearly_translations = [], []
|
| 3577 |
+
for i in range(len(weekly_lows) - 1):
|
| 3578 |
+
t = cp_classify_translation(price, weekly_lows[i], weekly_lows[i+1])
|
| 3579 |
+
t["cycle_start"], t["cycle_end"] = weekly_lows[i], weekly_lows[i+1]
|
| 3580 |
+
weekly_translations.append(t)
|
| 3581 |
+
for i in range(len(yearly_lows) - 1):
|
| 3582 |
+
t = cp_classify_translation(price, yearly_lows[i], yearly_lows[i+1])
|
| 3583 |
+
t["cycle_start"], t["cycle_end"] = yearly_lows[i], yearly_lows[i+1]
|
| 3584 |
+
yearly_translations.append(t)
|
| 3585 |
+
|
| 3586 |
+
return {
|
| 3587 |
+
"daily": {"lows": daily_lows, "stats": daily_stats,
|
| 3588 |
+
"projection": cp_project_next_low(daily_lows, daily_stats)},
|
| 3589 |
+
"weekly": {"lows": weekly_lows, "stats": weekly_stats,
|
| 3590 |
+
"projection": standard_weekly_projection, "adaptive_projection": weekly_adaptive,
|
| 3591 |
+
"wcl_model": wcl_model, "translations": weekly_translations},
|
| 3592 |
+
"yearly": {"lows": yearly_lows, "stats": yearly_stats,
|
| 3593 |
+
"projection": standard_yearly_projection, "adaptive_projection": yearly_adaptive,
|
| 3594 |
+
"transition_model": yearly_transition_model, "translations": yearly_translations},
|
| 3595 |
+
}
|
| 3596 |
+
|
| 3597 |
+
|
| 3598 |
+
def cp_plot_nested_dashboard(price: pd.Series, nested: dict, asset_name: str,
|
| 3599 |
+
view_start: str = "2000-01-01"):
|
| 3600 |
+
view_start_ts = pd.Timestamp(view_start)
|
| 3601 |
+
fig, ax = plt.subplots(figsize=(14, 7))
|
| 3602 |
+
fig.patch.set_facecolor("#0d1321")
|
| 3603 |
+
ax.set_facecolor("#0d1321")
|
| 3604 |
+
ax.plot(price.index, price.values, color="#e8e8e8", lw=1.1, zorder=6)
|
| 3605 |
+
ax.set_yscale("log")
|
| 3606 |
+
|
| 3607 |
+
for low in nested["daily"]["lows"]:
|
| 3608 |
+
if low >= view_start_ts:
|
| 3609 |
+
ax.plot(low, price.loc[low], marker=".", color="#7aa8d8", ms=4, alpha=0.6, zorder=3)
|
| 3610 |
+
|
| 3611 |
+
weekly_lows = nested["weekly"]["lows"]
|
| 3612 |
+
for low in weekly_lows:
|
| 3613 |
+
if low >= view_start_ts:
|
| 3614 |
+
ax.plot(low, price.loc[low], marker="^", color="#4a90d9", ms=8, zorder=4)
|
| 3615 |
+
for i in range(len(weekly_lows) - 1):
|
| 3616 |
+
if weekly_lows[i+1] < view_start_ts:
|
| 3617 |
+
continue
|
| 3618 |
+
gap_weeks = (weekly_lows[i+1] - weekly_lows[i]).days / 7
|
| 3619 |
+
mid = weekly_lows[i] + (weekly_lows[i+1] - weekly_lows[i]) / 2
|
| 3620 |
+
y = price.loc[weekly_lows[i]:weekly_lows[i+1]].min() * 0.90
|
| 3621 |
+
ax.annotate(f"{gap_weeks:.0f}W", (mid, y), color="#4a90d9", fontsize=7.5, ha="center", alpha=0.85)
|
| 3622 |
+
|
| 3623 |
+
yearly_lows = nested["yearly"]["lows"]
|
| 3624 |
+
for low in yearly_lows:
|
| 3625 |
+
if low >= view_start_ts:
|
| 3626 |
+
ax.axvline(low, color="#c9302c", ls=":", lw=0.9, alpha=0.7)
|
| 3627 |
+
ax.plot(low, price.loc[low], marker="D", color="#e8b84b", ms=11, zorder=5,
|
| 3628 |
+
markeredgecolor="#7a5a30", markeredgewidth=0.8)
|
| 3629 |
+
|
| 3630 |
+
weekly_adaptive = nested["weekly"].get("adaptive_projection", {})
|
| 3631 |
+
wcl_model = nested["weekly"].get("wcl_model", {})
|
| 3632 |
+
weekly_wave_source = weekly_adaptive if wcl_model.get("valid") and weekly_adaptive else nested["weekly"]["projection"]
|
| 3633 |
+
wd, wv = cp_phase_locked_wave(price, weekly_lows, weekly_wave_source, view_start_ts, y_frac=0.25, amplitude_frac=0.10)
|
| 3634 |
+
if wd is not None:
|
| 3635 |
+
ax.plot(wd, wv, color="#4a90d9", lw=1.8, alpha=0.85, zorder=2,
|
| 3636 |
+
label="Weekly cycle rhythm" + (" (adaptive)" if wcl_model.get("valid") else ""))
|
| 3637 |
+
|
| 3638 |
+
yearly_adaptive = nested["yearly"].get("adaptive_projection", {})
|
| 3639 |
+
yearly_transition_model = nested["yearly"].get("transition_model", {})
|
| 3640 |
+
yearly_wave_source = yearly_adaptive if yearly_adaptive else nested["yearly"]["projection"]
|
| 3641 |
+
yd, yv = cp_phase_locked_wave(price, yearly_lows, yearly_wave_source, view_start_ts, y_frac=0.75, amplitude_frac=0.14)
|
| 3642 |
+
if yd is not None:
|
| 3643 |
+
ax.plot(yd, yv, color="#e8b84b", lw=2, alpha=0.85, zorder=2,
|
| 3644 |
+
label="Yearly cycle rhythm" + (" (adaptive)" if yearly_transition_model.get("used_transition") else ""))
|
| 3645 |
+
|
| 3646 |
+
wproj = weekly_wave_source
|
| 3647 |
+
if wproj:
|
| 3648 |
+
ax.axvspan(wproj["window_start"], wproj["window_end"], color="#4a90d9", alpha=0.15)
|
| 3649 |
+
ax.axvline(wproj["eta"], color="#4a90d9", ls="--", lw=1.2, alpha=0.9)
|
| 3650 |
+
yproj = yearly_wave_source
|
| 3651 |
+
if yproj:
|
| 3652 |
+
ax.axvspan(yproj["window_start"], yproj["window_end"], color="#e8b84b", alpha=0.15)
|
| 3653 |
+
ax.axvline(yproj["eta"], color="#e8b84b", ls="--", lw=1.4, alpha=0.9)
|
| 3654 |
+
|
| 3655 |
+
ax.set_xlim(left=view_start_ts)
|
| 3656 |
+
ax.set_title(f"{asset_name}: nested Daily / Weekly / Yearly cycle lows", color="white", fontsize=12)
|
| 3657 |
+
ax.tick_params(colors="white")
|
| 3658 |
+
for spine in ax.spines.values():
|
| 3659 |
+
spine.set_color("#444")
|
| 3660 |
+
|
| 3661 |
+
legend_elems = [
|
| 3662 |
+
plt.Line2D([0], [0], marker='.', color='w', markerfacecolor='#7aa8d8', ms=8,
|
| 3663 |
+
label=f"Daily-tier low ({nested['daily']['stats']['n_cycles']} cycles)", ls=''),
|
| 3664 |
+
plt.Line2D([0], [0], marker='^', color='w', markerfacecolor='#4a90d9', ms=9,
|
| 3665 |
+
label=f"Weekly-tier low ({nested['weekly']['stats']['n_cycles']} cycles)", ls=''),
|
| 3666 |
+
plt.Line2D([0], [0], marker='D', color='w', markerfacecolor='#e8b84b', ms=9,
|
| 3667 |
+
label=f"Yearly-tier low ({nested['yearly']['stats']['n_cycles']} cycles)", ls=''),
|
| 3668 |
+
]
|
| 3669 |
+
if wproj:
|
| 3670 |
+
legend_elems.append(plt.Line2D([0], [0], color='#4a90d9', ls='--', lw=1.5,
|
| 3671 |
+
label=f"Next weekly low: {wproj['eta'].date()}"))
|
| 3672 |
+
if yproj:
|
| 3673 |
+
low_rel = nested["yearly"]["stats"]["n_cycles"] < 4
|
| 3674 |
+
tm = nested["yearly"].get("transition_model", {})
|
| 3675 |
+
n_obs = tm.get("n_obs_in_category")
|
| 3676 |
+
obs_note = f", n={n_obs} in category" if tm.get("used_transition") and n_obs is not None else ""
|
| 3677 |
+
legend_elems.append(plt.Line2D([0], [0], color='#e8b84b', ls='--', lw=1.5,
|
| 3678 |
+
label=f"Next yearly low: {yproj['eta'].date()}"
|
| 3679 |
+
+ (" [low reliability]" if low_rel else "") + obs_note))
|
| 3680 |
+
ax.legend(handles=legend_elems, loc="upper left", facecolor="#1a2036",
|
| 3681 |
+
labelcolor="white", framealpha=0.85, fontsize=8.5)
|
| 3682 |
+
plt.tight_layout()
|
| 3683 |
+
return fig
|
| 3684 |
+
|
| 3685 |
+
|
| 3686 |
+
def render_cycle_projector_tab():
|
| 3687 |
+
st.title("πͺ Cycle Projector")
|
| 3688 |
+
st.caption(
|
| 3689 |
+
"Nested Daily/Weekly/Yearly pivot-low detection with a phase-modulated weekly model "
|
| 3690 |
+
"and a transition-adaptive yearly model (Short/Normal/Long-conditioned band, not a "
|
| 3691 |
+
"point forecast). Yearly resolution is set MANUALLY per ticker β auto-detection was "
|
| 3692 |
+
"tested and found to underperform manual tuning on BTC, gold, and Nasdaq alike, so "
|
| 3693 |
+
"this tab keeps you in the loop on that call."
|
| 3694 |
+
)
|
| 3695 |
+
|
| 3696 |
+
with st.sidebar:
|
| 3697 |
+
st.markdown("---")
|
| 3698 |
+
st.header("Cycle Projector")
|
| 3699 |
+
cp_ticker = st.text_input("Ticker (yfinance format)", value="BTC-USD", key="cp_ticker")
|
| 3700 |
+
cp_yearly_years = st.number_input(
|
| 3701 |
+
"Yearly cycle resolution (years)", min_value=1.0, max_value=15.0,
|
| 3702 |
+
value=6.0, step=0.25, key="cp_yearly_years",
|
| 3703 |
+
help="BTC needed ~6y or the 2018 low merges into the COVID low. "
|
| 3704 |
+
"Gold and Nasdaq will likely need different values β tune per ticker."
|
| 3705 |
+
)
|
| 3706 |
+
with st.expander("Advanced settings"):
|
| 3707 |
+
cp_daily_days = st.number_input("Daily cycle length (days)", value=40, step=5, key="cp_daily_days")
|
| 3708 |
+
cp_weekly_days = st.number_input("Weekly cycle length (days)", value=200, step=10, key="cp_weekly_days")
|
| 3709 |
+
cp_prom_daily = st.slider("Daily prominence", 0.01, 0.20, 0.03, 0.01, key="cp_prom_daily")
|
| 3710 |
+
cp_prom_weekly = st.slider("Weekly prominence", 0.01, 0.20, 0.05, 0.01, key="cp_prom_weekly")
|
| 3711 |
+
cp_prom_yearly = st.slider("Yearly prominence", 0.01, 0.30, 0.08, 0.01, key="cp_prom_yearly")
|
| 3712 |
+
cp_view_start = st.text_input("Chart view start (YYYY-MM-DD)", value="2000-01-01", key="cp_view_start")
|
| 3713 |
+
cp_run = st.button("βΆοΈ Run", key="cp_run")
|
| 3714 |
+
|
| 3715 |
+
if not cp_run:
|
| 3716 |
+
st.info("Set a ticker and yearly resolution in the sidebar, then click Run.")
|
| 3717 |
+
return
|
| 3718 |
+
|
| 3719 |
+
with st.spinner(f"Fetching {cp_ticker}β¦"):
|
| 3720 |
+
data = yf.download(cp_ticker, period="max", auto_adjust=True, progress=False)
|
| 3721 |
+
if data.empty:
|
| 3722 |
+
st.error(f"No data returned for '{cp_ticker}'.")
|
| 3723 |
+
return
|
| 3724 |
+
price = data["Close"]
|
| 3725 |
+
if isinstance(price, pd.DataFrame):
|
| 3726 |
+
price = price.iloc[:, 0]
|
| 3727 |
+
|
| 3728 |
+
nested = cp_build_nested_cycle_report(
|
| 3729 |
+
price, daily_days=cp_daily_days, weekly_days=cp_weekly_days,
|
| 3730 |
+
yearly_days=cp_yearly_years * 365.25,
|
| 3731 |
+
prominence_daily=cp_prom_daily, prominence_weekly=cp_prom_weekly,
|
| 3732 |
+
prominence_yearly=cp_prom_yearly,
|
| 3733 |
+
)
|
| 3734 |
+
|
| 3735 |
+
if nested["weekly"]["stats"]["n_cycles"] == 0 and nested["yearly"]["stats"]["n_cycles"] == 0:
|
| 3736 |
+
st.warning("No valid lows found at this resolution/prominence β try adjusting the sliders.")
|
| 3737 |
+
return
|
| 3738 |
+
|
| 3739 |
+
wstats, ystats = nested["weekly"]["stats"], nested["yearly"]["stats"]
|
| 3740 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 3741 |
+
c1.metric("Weekly cycle avg", f"{wstats['mean_days']/7:.0f}w" if wstats["n_cycles"] else "n/a")
|
| 3742 |
+
c2.metric("Yearly cycle avg", f"{ystats['mean_days']/365.25:.2f}y" if ystats["n_cycles"] else "n/a")
|
| 3743 |
+
c3.metric("Weekly cycles found", wstats["n_cycles"])
|
| 3744 |
+
c4.metric("Yearly cycles found", ystats["n_cycles"])
|
| 3745 |
+
|
| 3746 |
+
if ystats["n_cycles"] < 4:
|
| 3747 |
+
st.warning(f"Only {ystats['n_cycles']} completed yearly cycles β treat the yearly window as very rough.")
|
| 3748 |
+
|
| 3749 |
+
wproj = nested["weekly"]["adaptive_projection"] or nested["weekly"]["projection"]
|
| 3750 |
+
yproj = nested["yearly"]["adaptive_projection"] or nested["yearly"]["projection"]
|
| 3751 |
+
if wproj:
|
| 3752 |
+
st.info(f"**Next weekly-tier low:** {wproj['eta'].strftime('%Y-%m-%d')} "
|
| 3753 |
+
f"(window: {wproj['window_start'].strftime('%Y-%m-%d')} to {wproj['window_end'].strftime('%Y-%m-%d')})")
|
| 3754 |
+
if yproj:
|
| 3755 |
+
ytm = nested["yearly"]["transition_model"]
|
| 3756 |
+
note = ""
|
| 3757 |
+
if ytm.get("used_transition"):
|
| 3758 |
+
note = f" (adaptive, {ytm['previous_category']} category, n={ytm['n_obs_in_category']} prior obs)"
|
| 3759 |
+
st.info(f"**Next yearly-tier low{note}:** {yproj['eta'].strftime('%Y-%m-%d')} "
|
| 3760 |
+
f"(window: {yproj['window_start'].strftime('%Y-%m-%d')} to {yproj['window_end'].strftime('%Y-%m-%d')})")
|
| 3761 |
+
|
| 3762 |
+
fig = cp_plot_nested_dashboard(price, nested, cp_ticker, view_start=cp_view_start)
|
| 3763 |
+
st.pyplot(fig)
|
| 3764 |
+
plt.close(fig)
|
| 3765 |
+
|
| 3766 |
+
conf = cp_get_confirmed_and_candidate_low(price, nested["weekly"]["lows"])
|
| 3767 |
+
cA, cB = st.columns(2)
|
| 3768 |
+
if conf.get("confirmed_low") is not None:
|
| 3769 |
+
cA.success(f"β Confirmed weekly-tier low: {conf['confirmed_low'].date()} ({conf['days_since_confirmed']}d ago)")
|
| 3770 |
+
else:
|
| 3771 |
+
cA.info("β Confirmed low: none yet")
|
| 3772 |
+
if conf.get("candidate_low") is not None:
|
| 3773 |
+
cB.warning(f"β Unconfirmed candidate: {conf['candidate_low'].date()} ({conf['days_since_candidate']}d ago)")
|
| 3774 |
+
else:
|
| 3775 |
+
cB.info("β Unconfirmed candidate: none")
|
| 3776 |
+
|
| 3777 |
+
with st.expander("Weekly-tier translation per completed cycle"):
|
| 3778 |
+
for t in nested["weekly"]["translations"]:
|
| 3779 |
+
peak_str = t['peak_date'].date() if t['peak_date'] else 'n/a'
|
| 3780 |
+
st.write(f"{t['cycle_start'].date()} β {t['cycle_end'].date()}: **{t['translation']}** "
|
| 3781 |
+
f"(peak at {t['pct_through_cycle']:.0f}% through the cycle, {peak_str})")
|
| 3782 |
+
|
| 3783 |
+
|
| 3784 |
# =========================================================
|
| 3785 |
# MAIN LAYOUT
|
| 3786 |
# =========================================================
|
|
|
|
| 3793 |
"π§ Rotation Map",
|
| 3794 |
"π― Combined Scanner",
|
| 3795 |
"πͺ Catch the Knife",
|
| 3796 |
+
"πͺ Cycle Projector",
|
| 3797 |
])
|
| 3798 |
|
| 3799 |
with tab1:
|
|
|
|
| 3815 |
render_combined_scanner()
|
| 3816 |
|
| 3817 |
with tab7:
|
| 3818 |
+
render_catch_the_knife()
|
| 3819 |
+
|
| 3820 |
+
with tab8:
|
| 3821 |
+
render_cycle_projector_tab()
|