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

monteCarlo7Day.py 9.1 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
  1. import numpy as np
  2. import pandas as pd
  3. import yfinance as yf
  4. import matplotlib.pyplot as plt
  5. #Mote Carlo for 7 days
  6. #start_price (initial stock price),
  7. # days (number of simulation days),
  8. # mu (average daily return of the stock),
  9. # sigma (standard deviation of the stock’s daily returns)
  10. #TO-DO for the next year: compare from previous year to next year
  11. #change the value from one day to one month
  12. #take data for all S&P 500
  13. # uses yfinance library to get the stocks for analysis based on user inputs
  14. start_date = input("Enter the start date (YYYY-MM-DD): ")
  15. end_date = input("Enter the end date (YYYY-MM-DD): ")
  16. stock_symbol = input("Enter stock ticker symbol (e.g., GOOGL): ")
  17. prev_days = int(input("Enter the number of previous days you want to predict with in each simulation: "))
  18. num_simulations = int(input("Enter the number of simulations you want in Monte simulation: "))
  19. # Retrieve historical data for the specified stock and user-defined dates
  20. data = yf.download(stock_symbol, start=start_date, end=end_date)
  21. days = len(data) # Number of days in the data
  22. dt = 1 / days # Time interval
  23. # Random seed for reproducibility
  24. np.random.seed(42)
  25. actual_price = data['Close'].iloc[-1]
  26. def monte_carlo(start_price, days, mu, sigma):
  27. price = np.zeros(days + 7) # Initializes price with zeros
  28. print(len(price))
  29. price[0] = start_price
  30. for x in range(1, days + 9):
  31. total_shock = 0
  32. for i in range(prev_days): #was initally for days
  33. total_shock += np.random.normal(loc=mu, scale=sigma) # Accumulate shocks from previous days
  34. shock = total_shock / prev_days # Average shock from previous days
  35. drift = mu * dt # Expected change in price based on the average daily return
  36. # computed by applying the drift and shock components to the previous day’s price and stores that in the price array
  37. price[x] = price[x - 1] + (price[x - 1] * (drift + shock))
  38. return price #compare all these prices curve and get accuracies for all of these prices
  39. #new accuracy method
  40. def accur(start_date, end_date, days, mu, sigma, start_price, prev_days):
  41. price = np.zeros(days) # initializes prices with 0
  42. price[0] = start_price
  43. accuracies = []
  44. print('hello')
  45. def accuracies(start_price, days, mu, sigma, prev_days):
  46. dt = 1 / days
  47. price = np.zeros(days)
  48. price[0] = start_price
  49. accuracies = []
  50. for x in range(1, days):
  51. total_shock = 0
  52. for day in range(days):
  53. total_shock += np.random.normal(loc=mu, scale=sigma)
  54. shock = total_shock / days
  55. drift = mu * dt
  56. price[x] = price[x - 1] + (price[x - 1] * (drift + shock))
  57. predicted_price = price[x]
  58. accuracy = (1 - abs(actual_price - predicted_price) / actual_price) * 100
  59. accuracies.append(accuracy)
  60. return accuracies
  61. #accuracies to be plotted
  62. # def accuracies(start_price, days, mu, sigma, prev_days):
  63. # price = np.zeros(days) # initializes prices with 0
  64. # price[0] = start_price
  65. # accuracies = []
  66. #
  67. # for x in range(1, days):
  68. # total_shock = 0
  69. # for day in range(prev_days):
  70. # total_shock += np.random.normal(loc=mu, scale=sigma) # Accumulate shocks from previous days
  71. # shock = total_shock / prev_days # Average shock from previous days
  72. # drift = mu * dt # Expected change in price based on the average daily return
  73. #
  74. # # computed by applying the drift and shock components to the previous day’s price and stores that in the price array
  75. # price[x] = price[x - 1] + (price[x - 1] * (drift + shock))
  76. #
  77. # # Calculate accuracy for the current day and store it
  78. # predicted_price = price[x]
  79. # actual_price = data['Close'].iloc[x] # Actual price for the current day
  80. # accuracy = (1 - abs(actual_price - predicted_price) / actual_price) * 100
  81. # accuracies.append(accuracy)
  82. #
  83. # return accuracies
  84. # Perform x amount of Monte Carlo simulations for the specified stock
  85. sim = np.zeros(num_simulations)
  86. plt.figure(figsize=(15, 8))
  87. # need 7 different arrays, one for each of the days within the week for predicting the price for X stock
  88. sim1 = np.zeros(num_simulations)
  89. sim2 = np.zeros(num_simulations)
  90. sim3 = np.zeros(num_simulations)
  91. sim4 = np.zeros(num_simulations)
  92. sim5 = np.zeros(num_simulations)
  93. sim6 = np.zeros(num_simulations)
  94. sim7 = np.zeros(num_simulations)
  95. for i in range(num_simulations):
  96. start_price = data['Adj Close'].iloc[0] #retrieves the adjusted closing prices of all the stocks in your datase
  97. # and indexes into the 'Adj Close' column to select the specific stock symbole
  98. mu = data['Adj Close'].pct_change().mean() #mean of daily percentage values entire year
  99. sigma = data['Adj Close'].pct_change().std() #standard deviation of daily percentage values
  100. result = monte_carlo(start_price, days, mu, sigma)
  101. sim[i] = result[days-1] # final price is stored #TODO instead need to store final 7 day price here
  102. sim1[i] = result[(days + 1) - 1]
  103. sim2[i] = result[(days + 2) - 1]
  104. sim3[i] = result[(days + 3) - 1]
  105. sim4[i] = result[(days + 4) - 1]
  106. sim5[i] = result[(days + 5) - 1]
  107. sim6[i] = result[(days + 6) - 1]
  108. sim7[i] = result[(days + 7) - 1]
  109. plt.plot(result)
  110. # for i in range (days, days + 8):
  111. # result = monte_
  112. day_1_predicted_price = np.median(np.sort(sim1))
  113. day_2_predicted_price = np.median(np.sort(sim2))
  114. day_3_predicted_price = np.median(np.sort(sim3))
  115. day_4_predicted_price = np.median(np.sort(sim4))
  116. day_5_predicted_price = np.median(np.sort(sim5))
  117. day_6_predicted_price = np.median(np.sort(sim6))
  118. day_7_predicted_price = np.median(np.sort(sim7))
  119. plt.xlabel('Days')
  120. plt.ylabel('Price')
  121. plt.title(f'7 Day Price Prediction of GOOGL')
  122. predicted_prices = [day_1_predicted_price, day_2_predicted_price, day_3_predicted_price,
  123. day_4_predicted_price, day_5_predicted_price, day_6_predicted_price, day_7_predicted_price]
  124. plt.plot(range(1, 8), predicted_prices, marker='o', label='Predicted Prices')
  125. # Adding legend
  126. plt.legend()
  127. # Show the plot
  128. plt.show()
  129. #---------------------------------------------------------------------------------------------------------------------
  130. #prints out predicted price for next day and accuracy of that value compared to actual data
  131. predicted_price = np.median(np.sort(sim))
  132. print("Predicted price for the next day after " + end_date + f" is ${predicted_price:.2f}")
  133. accuracy = (1- abs(actual_price - predicted_price) / actual_price) * 100
  134. print("Accuracy: {:.2f}%".format(accuracy))
  135. # sets axes and title for Graph #1
  136. plt.xlabel('Days')
  137. plt.ylabel('Price')
  138. plt.title(f'Monte Carlo Simulation for {stock_symbol}')
  139. # Perform Monte Carlo simulation to get accuracies for each day
  140. accuracies_per_day = accuracies(data['Close'].iloc[0], days, data['Close'].pct_change().mean(),
  141. data['Close'].pct_change().std(), prev_days)
  142. # Plotting accuracies for each day
  143. plt.figure(figsize=(12, 6))
  144. plt.plot(data.index[1:], accuracies_per_day, color='b', linewidth=1)
  145. plt.xlabel('Date')
  146. plt.ylabel('Accuracy (Decimal)')
  147. plt.title(f'Accuracy of {stock_symbol} Predictions from {start_date} to {end_date}')
  148. plt.xticks(rotation=45)
  149. plt.tight_layout()
  150. # Plot histogram
  151. plt.figure(figsize=(10, 7)) #generates a histogram plot using the data from the sim array.
  152. # the sim array contains the simulated final prices of each of the stocks
  153. plt.hist(sim, bins=100)
  154. plt.figtext(0.6, 0.7, "Mean: {:.2f}\nStd: {:.2f}\nStart Price: {:.2f}".format(sim.mean(), sim.std(), start_price))
  155. # adds text annotations to the figure at specific coordinates. It displays the mean, standard deviation, and start price of the simulated prices
  156. plt.title(f'Histogram for Monte Carlo Simulations of {stock_symbol}')
  157. plt.xlabel('Price')
  158. plt.ylabel('Frequency')
  159. #write next graph here
  160. # Initialize lists to store accuracies and predicted prices
  161. accuracies_list = []
  162. predicted_prices_list = []
  163. arr = []
  164. # Iterate through the range from -30 to 30 days
  165. # Think about price your predicting, if oprice goes up as well, otherwise consider a failure.
  166. # where the error builds o
  167. # if you make current predicition to next day
  168. # quantize our final score
  169. # need an alogiirhtm to combine all the tests
  170. # if it is anegative prediction, you do minus
  171. # quantizing --> if predicting score is more (that way you factor + (predicited)/(actual)
  172. # if you get a 60% movement accuracy better than S&P 500
  173. for prev_days in range(-30, 30): #-30, 30 Predict whether it goes up or down
  174. shifted_start_date = pd.to_datetime(start_date) + pd.DateOffset(days=prev_days)
  175. shifted_end_date = pd.to_datetime(end_date) + pd.DateOffset(days=prev_days)
  176. days = len(data)
  177. dt = 1 / days
  178. start_price = data['Close'].iloc[0]
  179. mu = data['Close'].pct_change().mean()
  180. sigma = data['Close'].pct_change().std()
  181. accuracy_values = accuracies(start_price, days, mu, sigma, prev_days)
  182. arr.extend(accuracy_values)
  183. mean_accuracy = np.mean(arr)
  184. accuracies_list.append(mean_accuracy)
  185. predicted_prices_list.append(prev_days)
  186. plt.figure(figsize=(10, 6))
  187. plt.plot(predicted_prices_list, accuracies_list, marker='o', linestyle='-', color='b')
  188. plt.xlabel('Days Shifted')
  189. plt.ylabel('Accuracy (%)')
  190. plt.title('Accuracy of Predictions vs. Days Shifted')
  191. plt.grid(True)
  192. plt.show()
Tip!

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

Comments

Loading...