diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/MonteCarlo.iml b/.idea/MonteCarlo.iml new file mode 100644 index 0000000..8417878 --- /dev/null +++ b/.idea/MonteCarlo.iml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/git_toolbox_blame.xml b/.idea/git_toolbox_blame.xml new file mode 100644 index 0000000..7dc1249 --- /dev/null +++ b/.idea/git_toolbox_blame.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..5e96bc2 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,39 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..a6218fe --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..d90b5d7 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/other.xml b/.idea/other.xml new file mode 100644 index 0000000..2e75c2e --- /dev/null +++ b/.idea/other.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/PI.gif b/PI.gif new file mode 100644 index 0000000..c585b21 Binary files /dev/null and b/PI.gif differ diff --git a/README.md b/README.md index 151bc96..54341c4 100644 --- a/README.md +++ b/README.md @@ -1 +1,28 @@ -# MonteCarlo \ No newline at end of file +# MonteCarlo +## Monte Carlo Simulation to Estimate Pi + +This program uses a Monte Carlo simulation to estimate the value of Pi. The program generates random points within a square of side length 2, centered at the origin, and calculates how many of those points fall inside a unit circle. The ratio of the points inside the circle to the total number of points is used to estimate Pi. + +### How to Run + +1. Make sure you have `numpy` and `matplotlib` installed, if not you can install them using the following command: + ```bash + pip install requirements.txt + ``` +2. Save the script as `pi.py`. +3. Run the script using the command `python pi.py` or `py pi.py` if you have installed python from the microsoft store. + +### Output +The output is an animation of the Monte Carlo simulation and a GIF file named PI.gif saved in the same directory. + + +## Portfolio Analysis with Real Stock Data +This program performs a Monte Carlo simulation to analyze the potential future returns of a portfolio composed of real stocks. Historical data is fetched from Yahoo Finance. + +### How to Run +1. Make sure you have `numpy`, `pandas`, `matplotlib`, and `yfinance` installed, just as before if dont have them installed you can install them with the following command: +```bash +pip install requirements.txt +``` +2. Save the script as `portfolio.py`. +3. Run the script using the command `python portfolio.py` or `py pi.py` if you have installed python from the microsoft store. \ No newline at end of file diff --git a/fictportfolio.py b/fictportfolio.py new file mode 100644 index 0000000..68adb3b --- /dev/null +++ b/fictportfolio.py @@ -0,0 +1,58 @@ +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt + +# Sample historical return data (in real use, replace with actual data) +data = { + 'Asset1': np.random.normal(0.01, 0.02, 1000), + 'Asset2': np.random.normal(0.015, 0.025, 1000), + 'Asset3': np.random.normal(0.02, 0.03, 1000), +} + +returns = pd.DataFrame(data) + +# Calculate mean returns and covariance matrix +mean_returns = returns.mean() +cov_matrix = returns.cov() + +# Portfolio weights (assuming an equally weighted portfolio) +weights = np.array([1 / 3, 1 / 3, 1 / 3]) + +# Number of simulations +num_simulations = 100000 + +# Time horizon (e.g., 252 trading days in a year) +time_horizon = 252 + +# Initialize arrays to store simulation results +simulated_portfolio_returns = np.zeros(num_simulations) + +# Run Monte Carlo simulations +for i in range(num_simulations): + # Generate random returns for each asset + random_returns = np.random.multivariate_normal(mean_returns, cov_matrix, time_horizon) + + # Calculate portfolio return for each time period + portfolio_returns = np.dot(random_returns, weights) + + # Calculate cumulative return over the time horizon + cumulative_return = np.prod(1 + portfolio_returns) - 1 + + # Store the cumulative return in the results array + simulated_portfolio_returns[i] = cumulative_return + +# Plot the distribution of simulated portfolio returns +plt.hist(simulated_portfolio_returns, bins=50, edgecolor='k', alpha=0.7) +plt.title('Distribution of Simulated Portfolio Returns') +plt.xlabel('Cumulative Return') +plt.ylabel('Frequency') +plt.show() + +# Summary statistics +mean_simulated_return = np.mean(simulated_portfolio_returns) +std_dev_simulated_return = np.std(simulated_portfolio_returns) +var_95 = np.percentile(simulated_portfolio_returns, 5) + +print(f"Mean Simulated Return: {mean_simulated_return:.2%}") +print(f"Standard Deviation of Simulated Return: {std_dev_simulated_return:.2%}") +print(f"Value at Risk (95% confidence level): {var_95:.2%}") diff --git a/pi.py b/pi.py index 8b13789..b22985c 100644 --- a/pi.py +++ b/pi.py @@ -1 +1,46 @@ +import numpy as np +from numpy.random import uniform +import matplotlib.pyplot as plt +from matplotlib.animation import FuncAnimation, PillowWriter +num_of_frames = 50 +num_of_samples = 150_000 + +x = uniform(low=-1.0, high=1.0, size=num_of_samples) +y = uniform(low=-1.0, high=1.0, size=num_of_samples) + +radius = 1.0 +theta = np.linspace(0, 2 * np.pi, 1000) +x_circle = radius * np.cos(theta) +y_circle = radius * np.sin(theta) + +fig, ax = plt.subplots(figsize=(4.8, 4.8)) + + +def animate(i): + ax.clear() + x_samples = x[:int(num_of_samples * (i + 1) / num_of_frames)] + y_samples = y[:int(num_of_samples * (i + 1) / num_of_frames)] + inside_circle = np.sqrt(x_samples ** 2 + y_samples ** 2) <= 1 + x_inside = x_samples[inside_circle] + x_outside = x_samples[~inside_circle] + y_inside = y_samples[inside_circle] + y_outside = y_samples[~inside_circle] + ax.scatter(x_inside, y_inside, 1, c='b', alpha=0.5) + ax.scatter(x_outside, y_outside, 1, c='r', alpha=0.5) + ax.plot(x_circle, y_circle, 'k') + ax.axis('equal') + ax.set_xlim(-1, 1) + ax.set_ylim(-1, 1) + ax.set_title(fr'$n = ${len(x_samples):,} $\pi \approx {4 * len(x_inside) / len(x_samples):.4f}$') + return ax + + +# Create animation object +ani = FuncAnimation(fig, animate, frames=num_of_frames, interval=200, blit=False) + +# Display the animation in a window +plt.show() + +# Save the animation as a GIF +ani.save("PI.gif", dpi=300, writer=PillowWriter(fps=60)) diff --git a/portfolio.py b/portfolio.py new file mode 100644 index 0000000..9897877 --- /dev/null +++ b/portfolio.py @@ -0,0 +1,57 @@ +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import yfinance as yf + +# Define the list of stock tickers and the portfolio weights +tickers = ['AAPL', 'MSFT', 'GOOGL'] +weights = np.array([0.3, 0.4, 0.3]) # Example weights, should sum to 1 + +# Fetch historical data for the tickers +data = yf.download(tickers, start="2020-01-01", end="2023-01-01")['Adj Close'] + +# Calculate daily returns +returns = data.pct_change().dropna() + +# Calculate mean returns and covariance matrix +mean_returns = returns.mean() +cov_matrix = returns.cov() + +# Number of simulations +num_simulations = 10000 + +# Time horizon (e.g., 252 trading days in a year) +time_horizon = 252 + +# Initialize arrays to store simulation results +simulated_portfolio_returns = np.zeros(num_simulations) + +# Run Monte Carlo simulations +for i in range(num_simulations): + # Generate random returns for each asset + random_returns = np.random.multivariate_normal(mean_returns, cov_matrix, time_horizon) + + # Calculate portfolio return for each time period + portfolio_returns = np.dot(random_returns, weights) + + # Calculate cumulative return over the time horizon + cumulative_return = np.prod(1 + portfolio_returns) - 1 + + # Store the cumulative return in the results array + simulated_portfolio_returns[i] = cumulative_return + +# Plot the distribution of simulated portfolio returns +plt.hist(simulated_portfolio_returns, bins=50, edgecolor='k', alpha=0.7) +plt.title('Distribution of Simulated Portfolio Returns') +plt.xlabel('Cumulative Return') +plt.ylabel('Frequency') +plt.show() + +# Summary statistics +mean_simulated_return = np.mean(simulated_portfolio_returns) +std_dev_simulated_return = np.std(simulated_portfolio_returns) +var_95 = np.percentile(simulated_portfolio_returns, 5) + +print(f"Mean Simulated Return: {mean_simulated_return:.2%}") +print(f"Standard Deviation of Simulated Return: {std_dev_simulated_return:.2%}") +print(f"Value at Risk (95% confidence level): {var_95:.2%}") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e288cf1 Binary files /dev/null and b/requirements.txt differ