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

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

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

Comments

Loading...