Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yfinance as yf
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- # ===========================
- # 1. DESCARGA DE DATOS
- # ===========================
- tickers = ['^GSPC', '^TNX']
- df = yf.download(
- tickers,
- period="3y",
- auto_adjust=True,
- progress=False
- )["Close"]
- df = df.dropna()
- sp500 = df['^GSPC']
- tnx = df['^TNX']
- # ===========================
- # 2. RENDIMIENTOS
- # ===========================
- # Rendimientos logarítmicos
- ret_sp = np.log(sp500 / sp500.shift(1))
- ret_tnx = np.log(tnx / tnx.shift(1))
- datos = pd.concat([ret_sp, ret_tnx], axis=1)
- datos.columns = ['SP500', 'TNX']
- datos = datos.dropna()
- # ===========================
- # 3. ESTADÍSTICAS
- # ===========================
- media = datos.mean().values # Vector de medias
- cov = datos.cov().values # Matriz de covarianzas
- correlacion = datos.corr().iloc[0,1]
- print("="*50)
- print("Correlación histórica S&P500 - Bono 10Y")
- print(f"{correlacion:.3f}")
- print("="*50)
- # ===========================
- # 4. PARÁMETROS
- # ===========================
- S0 = sp500.iloc[-1]
- dias = 126 # 6 meses
- trayectorias = 1000
- sim_sp = np.zeros((dias, trayectorias))
- sim_tnx = np.zeros((dias, trayectorias))
- sim_sp[0] = S0
- sim_tnx[0] = tnx.iloc[-1]
- # ===========================
- # 5. MONTE CARLO CONJUNTO
- # ===========================
- for t in range(1, dias):
- shocks = np.random.multivariate_normal(
- mean=media,
- cov=cov,
- size=trayectorias
- )
- shock_sp = shocks[:,0]
- shock_tnx = shocks[:,1]
- sim_sp[t] = sim_sp[t-1] * np.exp(shock_sp)
- sim_tnx[t] = sim_tnx[t-1] * np.exp(shock_tnx)
- # ===========================
- # 6. GRÁFICO
- # ===========================
- plt.figure(figsize=(14,8))
- plt.plot(sim_sp, alpha=0.15)
- plt.axhline(
- S0,
- color="red",
- linestyle="--",
- linewidth=2,
- label=f"Precio actual {S0:.2f}"
- )
- plt.title("Monte Carlo S&P500 considerando la correlación con el Bono USA 10Y",
- fontsize=15)
- plt.xlabel("Días bursátiles")
- plt.ylabel("S&P500")
- plt.grid(alpha=0.25)
- plt.legend()
- plt.show()
- # ===========================
- # 7. RESULTADOS
- # ===========================
- finales = sim_sp[-1]
- print("\n========= PREDICCIÓN =========\n")
- print(f"Precio actual: {S0:.2f}")
- print(f"Media: {np.mean(finales):.2f}")
- print(f"Mediana: {np.median(finales):.2f}")
- print(f"P10 (muy bajista): {np.percentile(finales,10):.2f}")
- print(f"P25 (bajista): {np.percentile(finales,25):.2f}")
- print(f"P75 (alcista): {np.percentile(finales,75):.2f}")
- print(f"P90 (muy alcista): {np.percentile(finales,90):.2f}")
- print(f"\nProbabilidad de subir: {(finales>S0).mean()*100:.1f}%")
- print(f"Probabilidad de bajar: {(finales<S0).mean()*100:.1f}%")
Advertisement
Add Comment
Please, Sign In to add comment