-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_multi_stock.py
More file actions
82 lines (62 loc) · 2.47 KB
/
Copy pathmain_multi_stock.py
File metadata and controls
82 lines (62 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import sys
import os
import subprocess
# Auto-install dependencies
REQUIRED_PACKAGES = ["numpy", "pandas", "matplotlib", "yfinance"]
def install_packages():
for package in REQUIRED_PACKAGES:
try:
__import__(package)
except ImportError:
print(f"Installing {package}...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
install_packages()
import pandas as pd
from simulator.data import fetch_stock_data, calculate_returns
from simulator.multi_stock_animation import MultiStockAnimation
import matplotlib.pyplot as plt
def main():
print("Monte Carlo Multi-Stock Simulator - Animated Version")
# Get multiple tickers
tickers_input = input("Enter stock tickers separated by commas or spaces (e.g. AAPL,MSFT,GOOGL or AAPL MSFT GOOGL): ").strip().upper()
# Handle both comma and space separation
if ',' in tickers_input:
tickers = [t.strip() for t in tickers_input.split(',') if t.strip()]
else:
tickers = [t.strip() for t in tickers_input.split() if t.strip()]
days = int(input("Enter time horizon (days): "))
num_simulations = int(input("Enter number of simulations per stock: "))
# Fetch data for all stocks
stock_data = {}
for ticker in tickers:
print(f"\nFetching data for {ticker}...")
df = fetch_stock_data(ticker)
if df is None:
print(f"Failed to fetch data for {ticker}. Skipping.")
continue
# Handle both single and multi-index DataFrames
if isinstance(df.columns, pd.MultiIndex):
close_series = df['Close'][ticker]
else:
close_series = df['Close']
last_price = float(close_series.iloc[-1])
# Calculate returns using the close series
returns = close_series.pct_change()
mu = float(returns.mean())
sigma = float(returns.std())
stock_data[ticker] = {
'last_price': last_price,
'mu': mu,
'sigma': sigma
}
if not stock_data:
print("No valid stock data. Exiting.")
return
print(f"\nStarting animated simulation for {len(stock_data)} stocks...")
print("Close the animation window when done.")
# Run multi-stock animated simulation
animator = MultiStockAnimation(stock_data, days, num_simulations)
animator.run()
print("\nSimulation complete!")
if __name__ == "__main__":
main()