How can I calculate and plot VAR and CVar... I've got this code: # MONTECARLO SIMULATION…
- User
How can I calculate and plot VAR and CVar... I've got this code: # MONTECARLO SIMULATION – GEOMETRIC BROWNIAN MOTION
Import the necessary module import scipy.stats
Define all the required parameters M = 1000 # Number of paths d = 250 # Number of steps (approx. number of trading days in a year) spot = df['Total'].iloc[-1] # Spot price of our asset T = 1 # Time to maturity (1 year) delta_t = T/d # Time step for the simulation r = 0.05 # Interest rate sigma = 0.12 # Volatility
Generate random variables y1 = np.random.rand(M, d) # Replace df['Total'] with random numbers
Initialize the inverse normal function and generate normal random variables norminv = scipy.stats.norm.ppf z1 = norminv(y1)
Create a matrix for asset prices ASSET1 = np.zeros((M, d+1)) ASSET1[:, 0] = spot # Set initial spot price for all paths
Generate the simulation paths for i in range(M): for j in range(d): ASSET1[i, j+1] = ASSET1[i, j] * np.exp((r-0.5*sigma**2)delta_t + sigmanp.sqrt(delta_t)*z1[i, j])
Plot the paths plt.figure(figsize=(12, 6)) plt.plot(ASSET1[:100, :].T, alpha=0.3) plt.plot(ASSET1[0, :], c='darkblue', linewidth=2)
Get the last value of 'Fecha' last_fecha = df['Fecha'].iloc[-1]
Create date range including the last 'Fecha' value new_ticks = pd.date_range(start=last_fecha, periods=d+1)
Set x-axis ticks and labels plt.xticks(range(0, d+1, 50), labels=new_ticks[::50].strftime('%Y-%m-%d'), rotation=45)
plt.yticks(fontsize=12) plt.xticks(fontsize=12) plt.ylabel("Asset's price", fontsize=14) plt.xlabel("Date", fontsize=14) plt.title("Geometric Brownian Motion - Monte Carlo Simulation", size=16)
plt.tight_layout() plt.show()
- Assistant
- User
MONTECARLO SIMULATION – GEOMETRIC BROWNIAN MOTION
import scipy.stats
Calculate historical returns
df['Returns'] = df['Total'].pct_change()
Calculate historical volatility (annualized)
historical_volatility = df['Returns'].std() * np.sqrt(252) # Assuming 252 trading days in a year
- Assistant