Guest User

Untitled

a guest
Jul 5th, 2026
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. import yfinance as yf
  2. import numpy as np
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5.  
  6. # ===========================
  7. # 1. DESCARGA DE DATOS
  8. # ===========================
  9.  
  10. tickers = ['^GSPC', '^TNX']
  11.  
  12. df = yf.download(
  13. tickers,
  14. period="3y",
  15. auto_adjust=True,
  16. progress=False
  17. )["Close"]
  18.  
  19. df = df.dropna()
  20.  
  21. sp500 = df['^GSPC']
  22. tnx = df['^TNX']
  23.  
  24. # ===========================
  25. # 2. RENDIMIENTOS
  26. # ===========================
  27.  
  28. # Rendimientos logarítmicos
  29. ret_sp = np.log(sp500 / sp500.shift(1))
  30. ret_tnx = np.log(tnx / tnx.shift(1))
  31.  
  32. datos = pd.concat([ret_sp, ret_tnx], axis=1)
  33. datos.columns = ['SP500', 'TNX']
  34. datos = datos.dropna()
  35.  
  36. # ===========================
  37. # 3. ESTADÍSTICAS
  38. # ===========================
  39.  
  40. media = datos.mean().values # Vector de medias
  41. cov = datos.cov().values # Matriz de covarianzas
  42.  
  43. correlacion = datos.corr().iloc[0,1]
  44.  
  45. print("="*50)
  46. print("Correlación histórica S&P500 - Bono 10Y")
  47. print(f"{correlacion:.3f}")
  48. print("="*50)
  49.  
  50. # ===========================
  51. # 4. PARÁMETROS
  52. # ===========================
  53.  
  54. S0 = sp500.iloc[-1]
  55.  
  56. dias = 126 # 6 meses
  57. trayectorias = 1000
  58.  
  59. sim_sp = np.zeros((dias, trayectorias))
  60. sim_tnx = np.zeros((dias, trayectorias))
  61.  
  62. sim_sp[0] = S0
  63. sim_tnx[0] = tnx.iloc[-1]
  64.  
  65. # ===========================
  66. # 5. MONTE CARLO CONJUNTO
  67. # ===========================
  68.  
  69. for t in range(1, dias):
  70.  
  71. shocks = np.random.multivariate_normal(
  72. mean=media,
  73. cov=cov,
  74. size=trayectorias
  75. )
  76.  
  77. shock_sp = shocks[:,0]
  78. shock_tnx = shocks[:,1]
  79.  
  80. sim_sp[t] = sim_sp[t-1] * np.exp(shock_sp)
  81.  
  82. sim_tnx[t] = sim_tnx[t-1] * np.exp(shock_tnx)
  83.  
  84. # ===========================
  85. # 6. GRÁFICO
  86. # ===========================
  87.  
  88. plt.figure(figsize=(14,8))
  89.  
  90. plt.plot(sim_sp, alpha=0.15)
  91.  
  92. plt.axhline(
  93. S0,
  94. color="red",
  95. linestyle="--",
  96. linewidth=2,
  97. label=f"Precio actual {S0:.2f}"
  98. )
  99.  
  100. plt.title("Monte Carlo S&P500 considerando la correlación con el Bono USA 10Y",
  101. fontsize=15)
  102.  
  103. plt.xlabel("Días bursátiles")
  104. plt.ylabel("S&P500")
  105.  
  106. plt.grid(alpha=0.25)
  107. plt.legend()
  108.  
  109. plt.show()
  110.  
  111. # ===========================
  112. # 7. RESULTADOS
  113. # ===========================
  114.  
  115. finales = sim_sp[-1]
  116.  
  117. print("\n========= PREDICCIÓN =========\n")
  118.  
  119. print(f"Precio actual: {S0:.2f}")
  120.  
  121. print(f"Media: {np.mean(finales):.2f}")
  122.  
  123. print(f"Mediana: {np.median(finales):.2f}")
  124.  
  125. print(f"P10 (muy bajista): {np.percentile(finales,10):.2f}")
  126.  
  127. print(f"P25 (bajista): {np.percentile(finales,25):.2f}")
  128.  
  129. print(f"P75 (alcista): {np.percentile(finales,75):.2f}")
  130.  
  131. print(f"P90 (muy alcista): {np.percentile(finales,90):.2f}")
  132.  
  133. print(f"\nProbabilidad de subir: {(finales>S0).mean()*100:.1f}%")
  134.  
  135. print(f"Probabilidad de bajar: {(finales<S0).mean()*100:.1f}%")
Advertisement
Add Comment
Please, Sign In to add comment