|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +TDD Test Suite: D10 — Sintese Interdisciplinar (N4 - Pesquisa) |
| 4 | +Baseado em: Farinelli, "Geometric Arbitrage Theory and Market Dynamics Reloaded" |
| 5 | + arXiv:0910.1671v10 (2021) |
| 6 | +
|
| 7 | +Verifica implementacoes reais dos conceitos centrais da GAT: |
| 8 | + D10-N4-01: Teoria unificadora geometria + finanzas + hidrodinamica |
| 9 | + D10-N4-02: Problema de fronteira interdisciplinar |
| 10 | + D10-N4-03: Gemeo digital de sistema complexo |
| 11 | +""" |
| 12 | + |
| 13 | +import sys, math |
| 14 | +from typing import List, Tuple, Dict |
| 15 | + |
| 16 | +# ══════════════════════════════════════════════════════════════════════ |
| 17 | +# SECAO 1 — Derivadas de Nelson (Teoria Estocastica Geometrica) |
| 18 | +# Ref: GAT §3.4, eq (33). Nelson D, D*, D = (D+D*)/2 |
| 19 | +# ══════════════════════════════════════════════════════════════════════ |
| 20 | + |
| 21 | +def nelson_forward(x: List[float], dt: float = 1.0) -> List[float]: |
| 22 | + """Derivada forward D: Dx_t = lim_{h->0+} E[(x_{t+h}-x_t)/h | P_t] |
| 23 | + Para processo deterministico, reduz-se a (x_{t+1}-x_t)/dt.""" |
| 24 | + return [(x[i+1] - x[i]) / dt for i in range(len(x)-1)] |
| 25 | + |
| 26 | +def nelson_backward(x: List[float], dt: float = 1.0) -> List[float]: |
| 27 | + """Derivada backward D*: D*x_t = lim_{h->0+} E[(x_t-x_{t-h})/h | F_t]""" |
| 28 | + return [(x[i] - x[i-1]) / dt for i in range(1, len(x))] |
| 29 | + |
| 30 | +def nelson_mean(x: List[float], dt: float = 1.0) -> List[float]: |
| 31 | + """Derivada media D = (D+D*)/2 — corresponde a Stratonovich. |
| 32 | + Alinha forward[t] com backward[t]: Dx_t = (x_{t+1}-x_t)/dt, |
| 33 | + D*x_t = (x_t-x_{t-1})/dt, D_t = (Dx_t + D*x_t)/2 para t=1..n-2.""" |
| 34 | + n = len(x) |
| 35 | + result = [] |
| 36 | + for i in range(1, n - 1): |
| 37 | + fwd_i = (x[i+1] - x[i]) / dt # Dx_i (forward at time i) |
| 38 | + bwd_i = (x[i] - x[i-1]) / dt # D*x_i (backward at time i) |
| 39 | + result.append((fwd_i + bwd_i) / 2.0) |
| 40 | + return result |
| 41 | + |
| 42 | +def test_nelson_linear(): |
| 43 | + """D10-N4-01: Para x_t = a*t + b, D = D* = D = a (constante).""" |
| 44 | + a, b = 3.0, 5.0 |
| 45 | + x = [a * t + b for t in range(10)] |
| 46 | + fwd = nelson_forward(x) |
| 47 | + bwd = nelson_backward(x) |
| 48 | + mean = nelson_mean(x) |
| 49 | + |
| 50 | + for v in fwd: |
| 51 | + assert abs(v - a) < 1e-10, f"Forward: {v} != {a}" |
| 52 | + for v in bwd: |
| 53 | + assert abs(v - a) < 1e-10, f"Backward: {v} != {a}" |
| 54 | + for v in mean: |
| 55 | + assert abs(v - a) < 1e-10, f"Mean: {v} != {a}" |
| 56 | + print(" [D10-N4-01] Nelson D=D*=D=a para processo linear... PASS") |
| 57 | + return True |
| 58 | + |
| 59 | +def test_nelson_quadratic(): |
| 60 | + """D10-N4-01: Para x_t = t^2, D = 2t+1, D* = 2t-1, D = 2t.""" |
| 61 | + x = [t * t for t in range(10)] |
| 62 | + fwd = nelson_forward(x) |
| 63 | + bwd = nelson_backward(x) |
| 64 | + mean = nelson_mean(x) |
| 65 | + |
| 66 | + for i, v in enumerate(fwd): |
| 67 | + expected = 2 * i + 1 # ((t+1)^2 - t^2) = 2t+1 |
| 68 | + assert abs(v - expected) < 1e-10, f"Fwd t={i}: {v} != {expected}" |
| 69 | + for i, v in enumerate(bwd): |
| 70 | + expected = 2 * (i+1) - 1 # (t^2 - (t-1)^2) = 2t-1 |
| 71 | + assert abs(v - expected) < 1e-10, f"Bwd t={i+1}: {v} != {expected}" |
| 72 | + for i, v in enumerate(mean): |
| 73 | + t = i + 1 # mean[0] corresponde a t=1 |
| 74 | + expected = 2 * t # D(x=t^2) = 2t em Stratonovich |
| 75 | + assert abs(v - expected) < 1e-10, f"Mean t={t}: {v} != {expected}" |
| 76 | + print(" [D10-N4-01] Nelson D=2t+1, D*=2t-1, D=2t para quadratico... PASS") |
| 77 | + return True |
| 78 | + |
| 79 | + |
| 80 | +# ══════════════════════════════════════════════════════════════════════ |
| 81 | +# SECAO 2 — Conexao e Curvatura (Mercado de 2 Ativos) |
| 82 | +# Ref: GAT §3.5-3.7, eq (43), (62), (66) |
| 83 | +# Arbitrage = Curvature != 0 |
| 84 | +# ══════════════════════════════════════════════════════════════════════ |
| 85 | + |
| 86 | +def connection_form(D: List[float], r: List[float], x: List[float]) -> List[float]: |
| 87 | + """Conexao χ(x,t,g)(δx,δt) = (D^{δx}_t/D^x_t - r^x_t δt) g |
| 88 | + Simplificado: 1-forma de conexao para portfolio x com deflator D e short rate r. |
| 89 | + χ_j = D_j/D^x_t dx^j - r^x dt (termo em dx^j) |
| 90 | + """ |
| 91 | + Dx = sum(xj * dj for xj, dj in zip(x, D)) |
| 92 | + # Componentes da conexao χ_j = D_j / D^x |
| 93 | + return [dj / Dx for dj in D] |
| 94 | + |
| 95 | +def curvature_form(D: List[float], r: List[float], x: List[float]) -> List[float]: |
| 96 | + """Curvatura R da eq (66): |
| 97 | + R_j = (D_j/D^x) * [r^x + D log(D^x) - r_j - D log(D_j)] |
| 98 | + Se R_j != 0 para algum j => existe arbitragem. |
| 99 | + """ |
| 100 | + Dx = sum(xj * dj for xj, dj in zip(x, D)) |
| 101 | + rx = sum(xj * dj * rj for xj, dj, rj in zip(x, D, r)) / Dx |
| 102 | + |
| 103 | + curvature = [] |
| 104 | + for j, (dj, rj) in enumerate(zip(D, r)): |
| 105 | + # D log(D^x) e D log(D_j) requerem derivadas de Nelson |
| 106 | + # Para mercado estatico (sem drift): D log(D) = 0 |
| 107 | + Rj = (dj / Dx) * (rx + 0 - rj - 0) if Dx != 0 else 0.0 |
| 108 | + curvature.append(Rj) |
| 109 | + return curvature |
| 110 | + |
| 111 | +def test_no_arbitrage_zero_curvature(): |
| 112 | + """D10-N4-02: Mercado sem arbitragem => curvatura zero (Theorem 34). |
| 113 | + Se todos os ativos tem o mesmo short rate r_j = r_0, entao R=0. |
| 114 | + """ |
| 115 | + # Mercado com 2 ativos + cash |
| 116 | + D = [1.0, 2.0, 3.0] # deflators (precos descontados) |
| 117 | + r = [0.05, 0.05, 0.05] # mesmo short rate = sem arbitragem |
| 118 | + x = [1.0, 1.0, 0.0] # portfolio |
| 119 | + |
| 120 | + R = curvature_form(D, r, x) |
| 121 | + for j, Rj in enumerate(R): |
| 122 | + assert abs(Rj) < 1e-10, f"Curvatura R[{j}]={Rj} deveria ser 0" |
| 123 | + print(" [D10-N4-02] Mercado sem arbitragem => R=0 (Theorem 34)... PASS") |
| 124 | + return True |
| 125 | + |
| 126 | +def test_arbitrage_nonzero_curvature(): |
| 127 | + """D10-N4-02: Mercado com arbitragem => curvatura != 0. |
| 128 | + Short rates diferentes entre ativos geram curvatura. |
| 129 | + """ |
| 130 | + D = [1.0, 2.0, 3.0] |
| 131 | + r = [0.05, 0.10, 0.02] # taxas diferentes = arbitragem potencial |
| 132 | + x = [1.0, 1.0, 0.0] |
| 133 | + |
| 134 | + R = curvature_form(D, r, x) |
| 135 | + # Pelo menos um R_j deve ser nao-nulo |
| 136 | + any_nonzero = any(abs(Rj) > 1e-10 for Rj in R) |
| 137 | + assert any_nonzero, "Curvatura deveria ser nao-nula com taxas diferentes" |
| 138 | + print(f" [D10-N4-02] Mercado com arbitragem => R=[{R[0]:.4f},{R[1]:.4f},{R[2]:.4f}] != 0... PASS") |
| 139 | + return True |
| 140 | + |
| 141 | +def test_connection_is_1form(): |
| 142 | + """D10-N4-02: A conexao χ e uma 1-forma com valores na algebra de Lie g. |
| 143 | + Propriedade: χ e linear nos argumentos (δx, δt).""" |
| 144 | + D = [1.0, 2.0] |
| 145 | + r = [0.05, 0.05] |
| 146 | + x = [1.0, 1.0] |
| 147 | + |
| 148 | + chi = connection_form(D, r, x) |
| 149 | + # χ deve ter N componentes (uma por ativo) |
| 150 | + assert len(chi) == len(D), f"Conexao deveria ter {len(D)} componentes" |
| 151 | + # Cada componente e um numero real (1-forma avaliada em direcao dx^j) |
| 152 | + for c in chi: |
| 153 | + assert isinstance(c, float) |
| 154 | + print(" [D10-N4-02] Conexao χ e 1-forma com N componentes... PASS") |
| 155 | + return True |
| 156 | + |
| 157 | + |
| 158 | +# ══════════════════════════════════════════════════════════════════════ |
| 159 | +# SECAO 3 — Equacao de Continuidade (Fluxo de Valor) |
| 160 | +# Ref: GAT §3.8, eq (80)-(82) |
| 161 | +# Dρ^β + div_x J = 0 <=> NFLVR |
| 162 | +# ══════════════════════════════════════════════════════════════════════ |
| 163 | + |
| 164 | +def log_value_density(D: List[float], beta: float = 1.0) -> List[float]: |
| 165 | + """Densidade de log-valor ρ^β(x,t) = log(β_t * D^x_t). Eq (79).""" |
| 166 | + return [math.log(beta * d) for d in D] |
| 167 | + |
| 168 | +def log_value_current(D: List[float], r: List[float], x: List[float]) -> List[float]: |
| 169 | + """Corrente de log-valor J_j = (integral sobre portfolios) * r_j. Eq (78). |
| 170 | + Simplificado: J_j ~ D_j * r_j / D^x (aproximacao de primeira ordem).""" |
| 171 | + Dx = sum(xj * dj for xj, dj in zip(x, D)) |
| 172 | + return [dj * rj / Dx if Dx != 0 else 0.0 for dj, rj in zip(D, r)] |
| 173 | + |
| 174 | +def continuity_divergence(D: List[float], r: List[float], x: List[float]) -> float: |
| 175 | + """div_x J = sum_j ∂J_j/∂x_j. |
| 176 | + No modelo estatico, div_x J = r^x (short rate do portfolio). Eq (81).""" |
| 177 | + Dx = sum(xj * dj for xj, dj in zip(x, D)) |
| 178 | + if Dx == 0: |
| 179 | + return 0.0 |
| 180 | + return sum(xj * dj * rj for xj, dj, rj in zip(x, D, r)) / Dx |
| 181 | + |
| 182 | +def test_continuity_divergence_equals_short_rate(): |
| 183 | + """D10-N4-03: div_x J = r^x (eq 81). |
| 184 | + Verifica que a divergencia da corrente de valor e igual ao short rate do portfolio.""" |
| 185 | + D = [1.0, 2.0, 3.0] |
| 186 | + r = [0.05, 0.08, 0.03] |
| 187 | + x = [1.0, 1.0, 1.0] |
| 188 | + |
| 189 | + divJ = continuity_divergence(D, r, x) |
| 190 | + # r^x = sum x_j D_j r_j / sum x_j D_j |
| 191 | + rx_expected = sum(xj * dj * rj for xj, dj, rj in zip(x, D, r)) / sum(xj * dj for xj, dj in zip(x, D)) |
| 192 | + assert abs(divJ - rx_expected) < 1e-10, f"divJ={divJ} != rx={rx_expected}" |
| 193 | + print(f" [D10-N4-03] div_x J = r^x = {rx_expected:.4f}... PASS") |
| 194 | + return True |
| 195 | + |
| 196 | +def test_nflvr_zero_divergence_balance(): |
| 197 | + """D10-N4-03: NFLVR => Dρ^β + div_x J = 0 (eq 80). |
| 198 | + Em mercado estatico (Dρ=0), NFLVR requer div J = 0 => r^x = 0.""" |
| 199 | + D = [1.0, 1.0, 1.0] |
| 200 | + r = [0.0, 0.0, 0.0] # taxas zero = sem fluxo de arbitragem |
| 201 | + x = [1.0, 1.0, 1.0] |
| 202 | + |
| 203 | + divJ = continuity_divergence(D, r, x) |
| 204 | + assert abs(divJ) < 1e-10, f"NFLVR requer divJ=0, obtido {divJ}" |
| 205 | + print(" [D10-N4-03] NFLVR => Dρ+divJ=0 verificado (r=0 => divJ=0)... PASS") |
| 206 | + return True |
| 207 | + |
| 208 | + |
| 209 | +# ══════════════════════════════════════════════════════════════════════ |
| 210 | +# SECAO 4 — Holonomia e Topologia (Ambrose-Singer) |
| 211 | +# Ref: GAT §3.5, Definition 31, Theorem 34(iv)(v) |
| 212 | +# Holonomia trivial <=> Curvatura zero |
| 213 | +# ══════════════════════════════════════════════════════════════════════ |
| 214 | + |
| 215 | +def parallel_transport_nominal(D: List[float], x_from: List[float], |
| 216 | + x_to: List[float]) -> float: |
| 217 | + """Transporte paralelo ao longo de direcao nominal (x). |
| 218 | + Eq (47): g(τ) = g1 * (sum x_j(τ1) D_j) / (sum x_j(τ) D_j). |
| 219 | + Interpretacao financeira: taxa de cambio entre portfolios.""" |
| 220 | + val_from = sum(xf * d for xf, d in zip(x_from, D)) |
| 221 | + val_to = sum(xt * d for xt, d in zip(x_to, D)) |
| 222 | + return val_from / val_to if val_to != 0 else float('inf') |
| 223 | + |
| 224 | +def parallel_transport_time(D: float, r: float, t_from: float, t_to: float) -> float: |
| 225 | + """Transporte paralelo ao longo do tempo. |
| 226 | + Eq (49): g(τ) = g1 * exp(∫ r du). |
| 227 | + Interpretacao financeira: fator de desconto estocastico.""" |
| 228 | + return math.exp(r * (t_to - t_from)) |
| 229 | + |
| 230 | +def test_parallel_transport_exchange(): |
| 231 | + """D10-N4-02: Transporte nominal = taxa de cambio (Theorem 29).""" |
| 232 | + D = [2.0, 3.0, 5.0] # precos de 3 ativos |
| 233 | + x_usd = [1.0, 0.0, 0.0] |
| 234 | + x_eur = [0.0, 1.0, 0.0] |
| 235 | + |
| 236 | + fx = parallel_transport_nominal(D, x_usd, x_eur) |
| 237 | + expected_fx = 2.0 / 3.0 # USD/EUR = D_USD/D_EUR |
| 238 | + assert abs(fx - expected_fx) < 1e-10 |
| 239 | + print(f" [D10-N4-02] Transporte nominal USD/EUR = {fx:.4f}... PASS") |
| 240 | + return True |
| 241 | + |
| 242 | +def test_parallel_transport_discount(): |
| 243 | + """D10-N4-02: Transporte temporal = desconto (Theorem 29).""" |
| 244 | + D0 = 100.0 |
| 245 | + r = 0.05 |
| 246 | + t = 1.0 |
| 247 | + |
| 248 | + discount = parallel_transport_time(D0, r, 0, t) |
| 249 | + expected = math.exp(-0.05) # fator de desconto: e^{-rt}? Nao: transporte paralelo |
| 250 | + # Eq (49): g(τ) = g1 * exp(∫r du) = g1 * exp(r*t) |
| 251 | + # Interpretacao: DIVISAO pelo fator de desconto |
| 252 | + # Se g1 = 1, g(τ) = exp(r*t) = valor futuro de 1 unidade |
| 253 | + expected_val = math.exp(r * t) |
| 254 | + assert abs(discount - expected_val) < 1e-10 |
| 255 | + print(f" [D10-N4-02] Transporte temporal exp(r*t) = {discount:.4f}... PASS") |
| 256 | + return True |
| 257 | + |
| 258 | +def test_holonomy_trivial_when_zero_curvature(): |
| 259 | + """D10-N4-02: Holonomia trivial <=> Curvatura zero (Ambrose-Singer). |
| 260 | + Transporte paralelo ao longo de curva fechada retorna identidade.""" |
| 261 | + # Curva fechada: x1 -> x2 -> x1 no mesmo instante t |
| 262 | + D = [1.0, 2.0] |
| 263 | + x_a = [1.0, 0.0] |
| 264 | + x_b = [0.0, 1.0] |
| 265 | + |
| 266 | + # ida |
| 267 | + fwd = parallel_transport_nominal(D, x_a, x_b) |
| 268 | + # volta |
| 269 | + bwd = parallel_transport_nominal(D, x_b, x_a) |
| 270 | + # holonomia = ida * volta (grupo abeliano) |
| 271 | + holonomy = fwd * bwd |
| 272 | + assert abs(holonomy - 1.0) < 1e-10 |
| 273 | + print(" [D10-N4-02] Holonomia trivial (curva fechada => identidade)... PASS") |
| 274 | + return True |
| 275 | + |
| 276 | + |
| 277 | +# ══════════════════════════════════════════════════════════════════════ |
| 278 | +# RUNNER |
| 279 | +# ══════════════════════════════════════════════════════════════════════ |
| 280 | + |
| 281 | +def main(): |
| 282 | + tests = [ |
| 283 | + # Nelson derivatives (D10-N4-01) |
| 284 | + ("Nelson linear", test_nelson_linear), |
| 285 | + ("Nelson quadratic", test_nelson_quadratic), |
| 286 | + # Curvature & Arbitrage (D10-N4-02) |
| 287 | + ("No-arbitrage => R=0", test_no_arbitrage_zero_curvature), |
| 288 | + ("Arbitrage => R!=0", test_arbitrage_nonzero_curvature), |
| 289 | + ("Connection 1-form", test_connection_is_1form), |
| 290 | + # Holonomy & Parallel Transport (D10-N4-02) |
| 291 | + ("Transport nominal = FX", test_parallel_transport_exchange), |
| 292 | + ("Transport temporal = desconto", test_parallel_transport_discount), |
| 293 | + ("Holonomia trivial", test_holonomy_trivial_when_zero_curvature), |
| 294 | + # Continuity Equation (D10-N4-03) |
| 295 | + ("div J = r^x", test_continuity_divergence_equals_short_rate), |
| 296 | + ("NFLVR => div J = 0", test_nflvr_zero_divergence_balance), |
| 297 | + ] |
| 298 | + |
| 299 | + print("=" * 60) |
| 300 | + print(" TDD TEST SUITE: D10 — Sintese Interdisciplinar (N4)") |
| 301 | + print(" Fonte: Farinelli, Geometric Arbitrage Theory (2021)") |
| 302 | + print("=" * 60) |
| 303 | + |
| 304 | + passed = 0 |
| 305 | + failed = 0 |
| 306 | + for name, test_fn in tests: |
| 307 | + try: |
| 308 | + test_fn() |
| 309 | + passed += 1 |
| 310 | + except AssertionError as e: |
| 311 | + print(f" [{name}] FAIL: {e}") |
| 312 | + failed += 1 |
| 313 | + except Exception as e: |
| 314 | + print(f" [{name}] ERROR: {e}") |
| 315 | + failed += 1 |
| 316 | + |
| 317 | + print(f"\n RESULT: {passed}/{passed+failed} passed, {failed} failed") |
| 318 | + print("=" * 60) |
| 319 | + return failed == 0 |
| 320 | + |
| 321 | +if __name__ == "__main__": |
| 322 | + sys.exit(0 if main() else 1) |
0 commit comments