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

newMonteCarlo.py 4.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  1. import numpy as np
  2. import yfinance as yf
  3. import matplotlib.pyplot as plt
  4. start_date = input("Enter the start date (YYYY-MM-DD): ")
  5. end_date = input("Enter the end date (YYYY-MM-DD): ")
  6. stock_symbol = input("Enter stock ticker symbol (e.g., GOOGL): ")
  7. prev_days = int(input("Enter the number of previous days you want to predict with in each simulation: "))
  8. num_simulations = 30
  9. data = yf.download(stock_symbol, start=start_date, end=end_date)
  10. days = len(data)
  11. dt = 1 / days
  12. np.random.seed(42)
  13. actual_price = data['Close'].iloc[-1]
  14. def monte_carlo(start_price, days, mu, sigma):
  15. price = np.zeros(days) # Initializes price with zeros
  16. price[0] = start_price
  17. for x in range(1, days):
  18. total_shock = 0
  19. for day in range(prev_days):
  20. total_shock += np.random.normal(loc=mu, scale=sigma) # Accumulate shocks from previous days
  21. shock = total_shock / prev_days # Average shock from previous days
  22. drift = mu * dt # Expected change in price based on the average daily return
  23. # computed by applying the drift and shock components to the previous day’s price and stores that in the price array
  24. price[x] = price[x - 1] + (price[x - 1] * (drift + shock))
  25. return price # compare all these prices curve and get accuracies for all of these prices
  26. # accuracies to be plotted
  27. def accuracies(start_price, days, mu, sigma, prev_days):
  28. price = np.zeros(days) # initializes prices with 0
  29. price[0] = start_price
  30. accuracies = []
  31. for x in range(1, days):
  32. total_shock = 0
  33. for day in range(prev_days):
  34. total_shock += np.random.normal(loc=mu, scale=sigma) # Accumulate shocks from previous days
  35. shock = total_shock / prev_days # Average shock from previous days
  36. drift = mu * dt
  37. # computed by applying the drift and shock components to the previous day’s price and stores that in the price array
  38. price[x] = price[x - 1] + (price[x - 1] * (drift + shock))
  39. # Calculate accuracy for the current day and store it
  40. predicted_price = price[x]
  41. actual_price = data['Close'].iloc[x] # Actual price for the current day
  42. accuracy = (1 - abs(actual_price - predicted_price) / actual_price) * 100
  43. accuracies.append(accuracy)
  44. return accuracies
  45. # Perform Monte Carlo simulations for the specified stock for 30 days
  46. sim = np.zeros((num_simulations, days))
  47. for i in range(num_simulations):
  48. start_price = data['Adj Close'].iloc[0] # retrieves the adjusted closing prices of all the stocks in your dataset
  49. # and indexes into the 'Adj Close' column to select the specific stock symbol
  50. mu = data['Adj Close'].pct_change().mean() # mean of daily percentage values entire year
  51. sigma = data['Adj Close'].pct_change().std() # standard deviation of daily percentage values
  52. result = monte_carlo(start_price, days, mu, sigma)
  53. sim[i] = result # store the simulation results
  54. # Plotting Monte Carlo simulations for each day
  55. plt.figure(figsize=(15, 8))
  56. for i in range(num_simulations):
  57. plt.plot(sim[i])
  58. # Print predicted prices and accuracies
  59. for i in range(num_simulations):
  60. predicted_price = sim[i][-1]
  61. accuracy = (1 - abs(actual_price - predicted_price) / actual_price) * 100
  62. print(f"Predicted price for day {i}: ${predicted_price:.2f} | Accuracy: {accuracy:.2f}%")
  63. # Perform Monte Carlo simulation to get accuracies for each day
  64. accuracies_per_day = accuracies(data['Close'].iloc[0], days, data['Close'].pct_change().mean(),
  65. data['Close'].pct_change().std(), prev_days)
  66. plt.figure(figsize=(12, 6))
  67. plt.plot(range(1, days), accuracies_per_day, color='b', linewidth=1)
  68. plt.xlabel('Day')
  69. plt.ylabel('Accuracy (Decimal)')
  70. plt.title(f'Accuracy of {stock_symbol} Predictions from {start_date} to {end_date}')
  71. plt.tight_layout()
  72. for i in range(num_simulations):
  73. plt.figure(figsize=(10, 7))
  74. plt.hist(sim[:, i], bins=100)
  75. plt.figtext(0.6, 0.7, f"Mean: {sim[:, i].mean():.2f}\nStd: {sim[:, i].std():.2f}\nStart Price: {start_price:.2f}")
  76. plt.title(f'Histogram for Monte Carlo Simulations of {stock_symbol} on Day {i}')
  77. plt.xlabel('Price')
  78. plt.ylabel('Frequency')
  79. plt.savefig(f'histogram_day_{i}.png') # Save the histogram to a file
  80. plt.close()
  81. # Show plots
  82. plt.show()
Tip!

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

Comments

Loading...