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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import yfinance as yf
|
| 5 |
+
from scipy.signal import hilbert
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
import warnings
|
| 10 |
+
warnings.filterwarnings('ignore')
|
| 11 |
+
|
| 12 |
+
st.set_page_config(page_title="Motor TFE", page_icon="🌊", layout="wide")
|
| 13 |
+
|
| 14 |
+
# ============================================================
|
| 15 |
+
# MOTOR TFE
|
| 16 |
+
# ============================================================
|
| 17 |
+
class FrCalculator:
|
| 18 |
+
def __init__(self, W_macro=63, W_micro=21):
|
| 19 |
+
self.W_macro = W_macro
|
| 20 |
+
self.W_micro = W_micro
|
| 21 |
+
|
| 22 |
+
def compute_inertia_series(self, macro_returns):
|
| 23 |
+
rho = macro_returns.rolling(window=self.W_macro).apply(
|
| 24 |
+
lambda x: pd.Series(x).autocorr(lag=1) if len(x) > 1 else np.nan, raw=False)
|
| 25 |
+
rho_clipped = np.clip(rho, -0.99, 0.98)
|
| 26 |
+
tau_memory = 1.0 / (1.0 - rho_clipped)
|
| 27 |
+
var_movil = macro_returns.rolling(window=self.W_macro).var()
|
| 28 |
+
var_norm = var_movil / var_movil.expanding().mean()
|
| 29 |
+
return tau_memory * np.clip(var_norm, 1.0, 5.0)
|
| 30 |
+
|
| 31 |
+
def compute_coherence_series(self, micro_returns):
|
| 32 |
+
q_series = np.full(len(micro_returns), np.nan)
|
| 33 |
+
matriz = micro_returns.values
|
| 34 |
+
for i in range(self.W_micro, len(matriz)):
|
| 35 |
+
win = matriz[i - self.W_micro:i]
|
| 36 |
+
if np.min(np.std(win, axis=0)) > 1e-10:
|
| 37 |
+
corr = np.corrcoef(win, rowvar=False)
|
| 38 |
+
eigenvalues = np.linalg.eigvalsh(corr)
|
| 39 |
+
q_series[i] = eigenvalues[-1] / np.sum(eigenvalues)
|
| 40 |
+
return pd.Series(q_series, index=micro_returns.index)
|
| 41 |
+
|
| 42 |
+
def compute_fr_series(self, macro_returns, micro_returns):
|
| 43 |
+
tau = self.compute_inertia_series(macro_returns)
|
| 44 |
+
q = self.compute_coherence_series(micro_returns)
|
| 45 |
+
df = pd.DataFrame({'tau': tau, 'q': q}).dropna()
|
| 46 |
+
df['fr'] = df['tau'] * df['q']
|
| 47 |
+
exp_mean = df['fr'].expanding(min_periods=252).mean()
|
| 48 |
+
exp_std = df['fr'].expanding(min_periods=252).std()
|
| 49 |
+
df['fr_normalized'] = (df['fr'] - exp_mean) / exp_std
|
| 50 |
+
return df.dropna()
|
| 51 |
+
|
| 52 |
+
class EMDDecomposer:
|
| 53 |
+
def __init__(self):
|
| 54 |
+
self.scales = {'short': (5, 21), 'medium': (21, 63), 'long': (63, 252)}
|
| 55 |
+
|
| 56 |
+
def decompose(self, signal_series):
|
| 57 |
+
signal = signal_series.fillna(method='ffill').fillna(0).values
|
| 58 |
+
N = len(signal)
|
| 59 |
+
if N < 100:
|
| 60 |
+
return None
|
| 61 |
+
fft_signal = np.fft.fft(signal)
|
| 62 |
+
freqs = np.fft.fftfreq(N, d=1.0)
|
| 63 |
+
components = {}
|
| 64 |
+
for name, (period_min, period_max) in self.scales.items():
|
| 65 |
+
f_max = 1.0 / period_min
|
| 66 |
+
f_min = 1.0 / period_max
|
| 67 |
+
mask = ((np.abs(freqs) >= f_min) & (np.abs(freqs) <= f_max))
|
| 68 |
+
fft_filtered = fft_signal * mask
|
| 69 |
+
component = np.real(np.fft.ifft(fft_filtered))
|
| 70 |
+
components[name] = pd.Series(component, index=signal_series.index)
|
| 71 |
+
return components
|
| 72 |
+
|
| 73 |
+
class PhaseAnalyzer:
|
| 74 |
+
@staticmethod
|
| 75 |
+
def analyze(signal_component):
|
| 76 |
+
s = signal_component.fillna(method='ffill').fillna(0).values
|
| 77 |
+
if len(s) < 50:
|
| 78 |
+
return None
|
| 79 |
+
s_centered = s - np.mean(s)
|
| 80 |
+
analytic = hilbert(s_centered)
|
| 81 |
+
return {
|
| 82 |
+
'phase': pd.Series(np.unwrap(np.angle(analytic)), index=signal_component.index),
|
| 83 |
+
'amplitude': pd.Series(np.abs(analytic), index=signal_component.index),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
class SyncAnalyzer:
|
| 87 |
+
@staticmethod
|
| 88 |
+
def kuramoto(phases_dict, amplitudes_dict=None):
|
| 89 |
+
df_phases = pd.DataFrame(phases_dict).dropna()
|
| 90 |
+
if df_phases.empty:
|
| 91 |
+
return pd.Series(dtype=float)
|
| 92 |
+
if amplitudes_dict is not None:
|
| 93 |
+
df_amp = pd.DataFrame(amplitudes_dict).reindex(df_phases.index).fillna(method='ffill')
|
| 94 |
+
complex_sum = (df_amp * np.exp(1j * df_phases)).sum(axis=1)
|
| 95 |
+
R = np.abs(complex_sum) / df_amp.sum(axis=1).replace(0, np.nan)
|
| 96 |
+
else:
|
| 97 |
+
R = np.abs(np.exp(1j * df_phases).mean(axis=1))
|
| 98 |
+
return R.fillna(0)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def plv(phase_i, phase_j, window=63):
|
| 102 |
+
df = pd.DataFrame({'i': phase_i, 'j': phase_j}).dropna()
|
| 103 |
+
if len(df) < window:
|
| 104 |
+
return pd.Series(dtype=float)
|
| 105 |
+
diff = df['i'] - df['j']
|
| 106 |
+
plv = pd.Series(index=df.index, dtype=float)
|
| 107 |
+
for k in range(window, len(df)):
|
| 108 |
+
wd = diff.iloc[k - window:k].values
|
| 109 |
+
plv.iloc[k] = np.abs(np.mean(np.exp(1j * wd)))
|
| 110 |
+
return plv
|
| 111 |
+
|
| 112 |
+
TOPOLOGIA = {
|
| 113 |
+
'CAPITAL_GLOBAL': {'macro': 'SPY', 'micro': ['XLK','XLF','XLE','XLV','XLI','XLY'],
|
| 114 |
+
'W_macro': 63, 'W_micro': 21, 'desc': 'Mercado accionario EE.UU.'},
|
| 115 |
+
'GRAVEDAD_SISTEMICA': {'macro': '^TNX', 'micro': ['^IRX','^FVX','^TYX'],
|
| 116 |
+
'W_macro': 63, 'W_micro': 63, 'desc': 'Curva de tasas Tesoro'},
|
| 117 |
+
'MATERIA_FISICA': {'macro': 'CL=F', 'micro': ['GC=F','ZS=F','HG=F'],
|
| 118 |
+
'W_macro': 63, 'W_micro': 63, 'desc': 'Commodities'},
|
| 119 |
+
'DIGITAL_OCCIDENTE': {'macro': 'BTC-USD', 'micro': ['ETH-USD','SOL-USD','LINK-USD'],
|
| 120 |
+
'W_macro': 30, 'W_micro': 21, 'desc': 'Cripto'},
|
| 121 |
+
'SOBERANO_ARGENTINA': {'macro': 'ARGT', 'micro': ['YPF','GGAL','PAM','CEPU'],
|
| 122 |
+
'W_macro': 63, 'W_micro': 21, 'desc': 'Argentina'},
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
@st.cache_data(ttl=3600)
|
| 126 |
+
def cargar_datos(macro_ticker, micro_tickers, period="20y"):
|
| 127 |
+
tickers = [macro_ticker] + list(micro_tickers)
|
| 128 |
+
data = yf.download(tickers, period=period, progress=False, auto_adjust=True)['Close']
|
| 129 |
+
if isinstance(data, pd.Series):
|
| 130 |
+
data = data.to_frame()
|
| 131 |
+
data = data.ffill().bfill().dropna()
|
| 132 |
+
if len(data) < 252:
|
| 133 |
+
return None, None
|
| 134 |
+
returns = np.log(data / data.shift(1)).dropna()
|
| 135 |
+
if macro_ticker in returns.columns:
|
| 136 |
+
return returns[macro_ticker], returns[list(micro_tickers)]
|
| 137 |
+
return None, None
|
| 138 |
+
|
| 139 |
+
@st.cache_data(ttl=3600)
|
| 140 |
+
def procesar_subsistema(nombre):
|
| 141 |
+
config = TOPOLOGIA[nombre]
|
| 142 |
+
period = "max" if 'BTC' in config['macro'] else "20y"
|
| 143 |
+
macro, micro = cargar_datos(config['macro'], config['micro'], period)
|
| 144 |
+
if macro is None or len(macro) < 252:
|
| 145 |
+
return None
|
| 146 |
+
fr_calc = FrCalculator(W_macro=config['W_macro'], W_micro=config['W_micro'])
|
| 147 |
+
df_fr = fr_calc.compute_fr_series(macro, micro)
|
| 148 |
+
if df_fr is None or len(df_fr) < 252:
|
| 149 |
+
return None
|
| 150 |
+
emd = EMDDecomposer()
|
| 151 |
+
components = emd.decompose(df_fr['fr_normalized'])
|
| 152 |
+
if components is None:
|
| 153 |
+
return None
|
| 154 |
+
analyses = {}
|
| 155 |
+
for cn, cs in components.items():
|
| 156 |
+
r = PhaseAnalyzer.analyze(cs)
|
| 157 |
+
if r is not None:
|
| 158 |
+
analyses[cn] = r
|
| 159 |
+
return {'fr_series': df_fr, 'wave_analyses': analyses,
|
| 160 |
+
'first_date': df_fr.index[0], 'last_date': df_fr.index[-1],
|
| 161 |
+
'desc': config['desc']}
|
| 162 |
+
|
| 163 |
+
def calcular_sync(processed, scale='medium'):
|
| 164 |
+
phases, amps = {}, {}
|
| 165 |
+
for n, d in processed.items():
|
| 166 |
+
if d is None or scale not in d['wave_analyses']:
|
| 167 |
+
continue
|
| 168 |
+
w = d['wave_analyses'][scale]
|
| 169 |
+
phases[n] = w['phase']
|
| 170 |
+
amps[n] = w['amplitude']
|
| 171 |
+
if len(phases) < 2:
|
| 172 |
+
return None, None
|
| 173 |
+
R = SyncAnalyzer.kuramoto(phases, amps)
|
| 174 |
+
names = list(phases.keys())
|
| 175 |
+
plv = pd.DataFrame(index=names, columns=names, dtype=float)
|
| 176 |
+
for i, n1 in enumerate(names):
|
| 177 |
+
for j, n2 in enumerate(names):
|
| 178 |
+
if i == j:
|
| 179 |
+
plv.loc[n1, n2] = 1.0
|
| 180 |
+
elif i < j:
|
| 181 |
+
ps = SyncAnalyzer.plv(phases[n1], phases[n2], 63)
|
| 182 |
+
lp = float(ps.iloc[-1]) if len(ps) > 0 else np.nan
|
| 183 |
+
plv.loc[n1, n2] = lp
|
| 184 |
+
plv.loc[n2, n1] = lp
|
| 185 |
+
return R, plv
|
| 186 |
+
|
| 187 |
+
# ============================================================
|
| 188 |
+
# INTERFAZ
|
| 189 |
+
# ============================================================
|
| 190 |
+
st.title("🌊 Motor TFE — Sincronización Sistémica")
|
| 191 |
+
st.caption("Teoría de Fragilidad Espectral · Detección de coherencia entre subsistemas vía Kuramoto + Hilbert")
|
| 192 |
+
|
| 193 |
+
st.sidebar.header("Control")
|
| 194 |
+
if st.sidebar.button("🔄 Actualizar datos"):
|
| 195 |
+
st.cache_data.clear()
|
| 196 |
+
st.rerun()
|
| 197 |
+
|
| 198 |
+
st.sidebar.markdown("---")
|
| 199 |
+
st.sidebar.markdown("**Subsistemas activos:**")
|
| 200 |
+
for k, v in TOPOLOGIA.items():
|
| 201 |
+
st.sidebar.text(f"• {k}")
|
| 202 |
+
st.sidebar.markdown("---")
|
| 203 |
+
st.sidebar.caption(f"Última carga: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
|
| 204 |
+
|
| 205 |
+
with st.spinner("Procesando subsistemas (puede tardar 1-2 minutos la primera vez)..."):
|
| 206 |
+
processed = {}
|
| 207 |
+
progress = st.progress(0)
|
| 208 |
+
for i, nombre in enumerate(TOPOLOGIA):
|
| 209 |
+
processed[nombre] = procesar_subsistema(nombre)
|
| 210 |
+
progress.progress((i + 1) / len(TOPOLOGIA))
|
| 211 |
+
progress.empty()
|
| 212 |
+
|
| 213 |
+
# Estado por subsistema
|
| 214 |
+
st.subheader("📊 Estado actual por subsistema")
|
| 215 |
+
cols = st.columns(len(TOPOLOGIA))
|
| 216 |
+
for col, (nombre, data) in zip(cols, processed.items()):
|
| 217 |
+
with col:
|
| 218 |
+
if data is None:
|
| 219 |
+
st.metric(nombre, "—", "sin datos")
|
| 220 |
+
continue
|
| 221 |
+
last = data['fr_series'].iloc[-1]
|
| 222 |
+
delta_color = "inverse" if last['fr_normalized'] > 1 else "normal"
|
| 223 |
+
st.metric(label=nombre, value=f"Q={last['q']:.3f}",
|
| 224 |
+
delta=f"τ={last['tau']:.2f} | Fr={last['fr_normalized']:+.2f}σ",
|
| 225 |
+
delta_color=delta_color)
|
| 226 |
+
st.caption(data['desc'])
|
| 227 |
+
|
| 228 |
+
# Sincronización por escala
|
| 229 |
+
st.subheader("🔬 Sincronización Kuramoto multi-escala")
|
| 230 |
+
st.caption("R(t) = parámetro de orden. R→1 = ondas en fase (resonancia). R→0 = sistema disipado.")
|
| 231 |
+
|
| 232 |
+
cols = st.columns(3)
|
| 233 |
+
for col, scale in zip(cols, ['short', 'medium', 'long']):
|
| 234 |
+
with col:
|
| 235 |
+
R, _ = calcular_sync(processed, scale)
|
| 236 |
+
if R is None or len(R) == 0:
|
| 237 |
+
st.warning(f"{scale}: sin datos")
|
| 238 |
+
continue
|
| 239 |
+
recent = R.iloc[-21:]
|
| 240 |
+
R_now = recent.iloc[-1]
|
| 241 |
+
R_max = recent.max()
|
| 242 |
+
slope = np.polyfit(np.arange(len(recent)), recent.values, 1)[0]
|
| 243 |
+
label = {'short': '⚡ Corto (5-21d)', 'medium': '🌊 Medio (21-63d)',
|
| 244 |
+
'long': '🏔️ Largo (63-252d)'}[scale]
|
| 245 |
+
st.metric(label, f"R = {R_now:.3f}",
|
| 246 |
+
delta=f"max 21d: {R_max:.3f} | dR/dt: {slope:+.4f}")
|
| 247 |
+
|
| 248 |
+
# Gráfico de R(t)
|
| 249 |
+
st.subheader("📈 Evolución histórica de R(t)")
|
| 250 |
+
fig, axes = plt.subplots(3, 1, figsize=(14, 9), sharex=True)
|
| 251 |
+
labels = {'short': 'CORTO (5-21d) - Shocks',
|
| 252 |
+
'medium': 'MEDIO (21-63d) - Incubaciones',
|
| 253 |
+
'long': 'LARGO (63-252d) - Régimen'}
|
| 254 |
+
for ax, scale in zip(axes, ['short', 'medium', 'long']):
|
| 255 |
+
R, _ = calcular_sync(processed, scale)
|
| 256 |
+
if R is None or len(R) == 0:
|
| 257 |
+
continue
|
| 258 |
+
ax.plot(R.index, R.values, color='steelblue', lw=0.8)
|
| 259 |
+
ax.axhline(0.70, color='orange', ls='--', alpha=0.7, label='Aviso (0.70)')
|
| 260 |
+
ax.axhline(0.85, color='red', ls='--', alpha=0.7, label='Crítico (0.85)')
|
| 261 |
+
ax.fill_between(R.index, 0, R.values, alpha=0.15, color='steelblue')
|
| 262 |
+
ax.set_ylabel(f'R - {scale}')
|
| 263 |
+
ax.set_title(labels[scale])
|
| 264 |
+
ax.set_ylim(0, 1.05)
|
| 265 |
+
ax.legend(loc='upper left', fontsize=8)
|
| 266 |
+
ax.grid(alpha=0.3)
|
| 267 |
+
plt.tight_layout()
|
| 268 |
+
st.pyplot(fig)
|
| 269 |
+
|
| 270 |
+
# PLV
|
| 271 |
+
st.subheader("🔗 Phase Locking Value entre subsistemas (escala media)")
|
| 272 |
+
_, plv = calcular_sync(processed, 'medium')
|
| 273 |
+
if plv is not None:
|
| 274 |
+
fig2, ax2 = plt.subplots(figsize=(9, 7))
|
| 275 |
+
sns.heatmap(plv.astype(float), annot=True, fmt='.2f',
|
| 276 |
+
cmap='RdYlBu_r', center=0.5, vmin=0, vmax=1,
|
| 277 |
+
cbar_kws={'label': 'PLV'}, ax=ax2)
|
| 278 |
+
ax2.set_title('PLV > 0.80 = par fuertemente acoplado')
|
| 279 |
+
plt.tight_layout()
|
| 280 |
+
st.pyplot(fig2)
|
| 281 |
+
|
| 282 |
+
st.markdown("---")
|
| 283 |
+
st.caption("Motor TFE v2.2 · Datos: Yahoo Finance · Cache: 1 hora · "
|
| 284 |
+
"Fundamento: Kuramoto (1984), Scheffer (2009), Vicente (2012)")
|