Having fun with statistics

This commit is contained in:
2024-06-28 17:55:26 +02:00
parent d278dc3e41
commit ce5101b7b4
15 changed files with 286 additions and 1 deletions
+8
View File
@@ -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
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.11" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PackageRequirementsSettings">
<option name="versionSpecifier" value="Greater or equal (&gt;=x.y.z)" />
<option name="removeUnused" value="true" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxBlameSettings">
<option name="version" value="2" />
</component>
</project>
+39
View File
@@ -0,0 +1,39 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="11">
<item index="0" class="java.lang.String" itemvalue="notebook_shim" />
<item index="1" class="java.lang.String" itemvalue="jupyter_server" />
<item index="2" class="java.lang.String" itemvalue="jupyterlab_widgets" />
<item index="3" class="java.lang.String" itemvalue="automium_web" />
<item index="4" class="java.lang.String" itemvalue="jupyterlab_pygments" />
<item index="5" class="java.lang.String" itemvalue="jupyter_client" />
<item index="6" class="java.lang.String" itemvalue="typing_extensions" />
<item index="7" class="java.lang.String" itemvalue="jupyter_server_terminals" />
<item index="8" class="java.lang.String" itemvalue="prometheus_client" />
<item index="9" class="java.lang.String" itemvalue="jupyter_core" />
<item index="10" class="java.lang.String" itemvalue="jupyterlab_server" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyShadowingBuiltinsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredNames">
<list>
<option value="id" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="statsmodels.tsa.arima.model.*" />
</list>
</option>
</inspection_tool>
</profile>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.11" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/MonteCarlo.iml" filepath="$PROJECT_DIR$/.idea/MonteCarlo.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PySciProjectComponent">
<option name="PY_INTERACTIVE_PLOTS_SUGGESTED" value="true" />
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 MiB

+27
View File
@@ -1 +1,28 @@
# 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.
+58
View File
@@ -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%}")
+45
View File
@@ -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))
+57
View File
@@ -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%}")
BIN
View File
Binary file not shown.