Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

monteCarloS&P500.py 2.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. import yfinance as yf
  2. import numpy as np
  3. import pandas as pd
  4. from monteCarlo import monte_carlo
  5. from monteCarlo import stockAnalysis
  6. import matplotlib.pyplot as plt
  7. # Get user inputs
  8. start_date = input("Enter the start date (YYYY-MM-DD): ")
  9. end_date = input("Enter the end date (YYYY-MM-DD): ")
  10. prev_days = int(input("Enter the number of previous days you want to predict with in each simulation: "))
  11. num_simulations = int(input("Enter the number of simulations you want in Monte simulation: "))
  12. # Get the list of S&P 500 tickers
  13. sp500 = pd.read_excel("SP_500_Companies.xlsx")
  14. sp500_tickers = sp500['Symbol'].tolist()
  15. # sp500_tickers = yf.Tickers('^GSPC').tickers # Fetch S&P 500 companies
  16. # Initialize a list to store the final predictions
  17. predictions_data = []
  18. # monte carlo simulation for all 500 companies
  19. for ticker in sp500_tickers:
  20. data = yf.download(ticker, start=start_date, end=end_date)
  21. if len(data) == 0:
  22. print(f"Warning: No data available for {ticker}. Skipping.")
  23. continue
  24. days = len(data)
  25. dt = 1 / days
  26. sim = np.zeros(num_simulations)
  27. for i in range(num_simulations):
  28. start_price = data['Close'].iloc[0]
  29. mu = data['Close'].pct_change().mean()
  30. sigma = data['Close'].pct_change().std()
  31. result = monte_carlo(start_price, days, mu, sigma, prev_days, dt)
  32. sim[i] = result[days - 1]
  33. predicted_price = np.median(np.sort(sim))
  34. predictions_data.append({'Symbol': ticker, 'Predicted Price': predicted_price})
  35. # plt.figure(figsize=(15, 8))
  36. # for i in range(num_simulations):
  37. # plt.plot(result)
  38. #Following code to write each of the data into a .txt file
  39. with open('predictions_data.txt', 'w') as file:
  40. file.write("Start Date: " + start_date)
  41. file.write("\nEnd Date: " + end_date)
  42. file.write("\nSimulations for each Monte Carlo " + str(num_simulations))
  43. file.write("\n\n")
  44. for prediction in predictions_data:
  45. file.write(f"Symbol: {prediction['Symbol']}, Predicted Price: {prediction['Predicted Price']}\n")
  46. #uses pandas to create the dataframe in.xlsx file
  47. # predictions_df = pd.DataFrame(predictions_data)
  48. #
  49. # predictions_df.to_excel('predictions.xlsx', index=False)
  50. #TODO: need to store in a .txt file | also make sure to include accuracy rate
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...