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

original_monte_working.py 7.8 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
  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. start_date = input("Enter the start date (YYYY-MM-DD): ")
  16. end_date = input("Enter the end date (YYYY-MM-DD): ")
  17. stock_symbol = input("Enter stock ticker symbol (e.g., GOOGL): ")
  18. prev_days = int(input("Enter the number of previous days you want to predict with in each simulation: "))
  19. num_simulations = int(input("Enter the number of simulations you want in Monte simulation: "))
  20. # Retrieve historical data for the specified stock and user-defined dates
  21. data = yf.download(stock_symbol, start=start_date, end=end_date)
  22. days = len(data) # Number of days in the data
  23. dt = 1 / days # Time interval
  24. # Random seed for reproducibility
  25. np.random.seed(42)
  26. actual_price = data['Close'].iloc[-1]
  27. def monte_carlo(start_price, days, mu, sigma):
  28. price = np.zeros(days) # Initializes price with zeros
  29. price[0] = start_price
  30. for x in range(1, days):
  31. total_shock = 0
  32. for day in range(prev_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. for i in range(num_simulations):
  88. start_price = data['Adj Close'].iloc[0] #retrieves the adjusted closing prices of all the stocks in your datase
  89. # and indexes into the 'Adj Close' column to select the specific stock symbole
  90. mu = data['Adj Close'].pct_change().mean() #mean of daily percentage values entire year
  91. sigma = data['Adj Close'].pct_change().std() #standard deviation of daily percentage values
  92. result = monte_carlo(start_price, days, mu, sigma)
  93. sim[i] = result[days-1] # final price is stored
  94. plt.plot(result)
  95. #prints out predicted price for next day and accuracy of that value compared to actual data
  96. predicted_price = np.median(np.sort(sim))
  97. print("Predicted price for the next day after " + end_date + f" is ${predicted_price:.2f}")
  98. accuracy = (1- abs(actual_price - predicted_price) / actual_price) * 100
  99. print("Accuracy: {:.2f}%".format(accuracy))
  100. # sets axes and title for Graph #1
  101. plt.xlabel('Days')
  102. plt.ylabel('Price')
  103. plt.title(f'Monte Carlo Simulation for {stock_symbol}')
  104. # Perform Monte Carlo simulation to get accuracies for each day
  105. accuracies_per_day = accuracies(data['Close'].iloc[0], days, data['Close'].pct_change().mean(),
  106. data['Close'].pct_change().std(), prev_days)
  107. # Plotting accuracies for each day
  108. plt.figure(figsize=(12, 6))
  109. plt.plot(data.index[1:], accuracies_per_day, color='b', linewidth=1)
  110. plt.xlabel('Date')
  111. plt.ylabel('Accuracy (Decimal)')
  112. plt.title(f'Accuracy of {stock_symbol} Predictions from {start_date} to {end_date}')
  113. plt.xticks(rotation=45)
  114. plt.tight_layout()
  115. # Plot histogram
  116. plt.figure(figsize=(10, 7)) #generates a histogram plot using the data from the sim array.
  117. # the sim array contains the simulated final prices of each of the stocks
  118. plt.hist(sim, bins=100)
  119. plt.figtext(0.6, 0.7, "Mean: {:.2f}\nStd: {:.2f}\nStart Price: {:.2f}".format(sim.mean(), sim.std(), start_price))
  120. # adds text annotations to the figure at specific coordinates. It displays the mean, standard deviation, and start price of the simulated prices
  121. plt.title(f'Histogram for Monte Carlo Simulations of {stock_symbol}')
  122. plt.xlabel('Price')
  123. plt.ylabel('Frequency')
  124. #write next graph here
  125. # Initialize lists to store accuracies and predicted prices
  126. accuracies_list = []
  127. predicted_prices_list = []
  128. arr = []
  129. # Iterate through the range from -30 to 30 days
  130. # Think about price your predicting, if oprice goes up as well, otherwise consider a failure.
  131. # where the error builds o
  132. # if you make current predicition to next day
  133. # quantize our final score
  134. # need an alogiirhtm to combine all the tests
  135. # if it is anegative prediction, you do minus
  136. # quantizing --> if predicting score is more (that way you factor + (predicited)/(actual)
  137. # if you get a 60% movement accuracy better than S&P 500
  138. for prev_days in range(-30, 30): #-30, 30 Predict whether it goes up or down
  139. shifted_start_date = pd.to_datetime(start_date) + pd.DateOffset(days=prev_days)
  140. shifted_end_date = pd.to_datetime(end_date) + pd.DateOffset(days=prev_days)
  141. days = len(data)
  142. dt = 1 / days
  143. start_price = data['Close'].iloc[0]
  144. mu = data['Close'].pct_change().mean()
  145. sigma = data['Close'].pct_change().std()
  146. accuracy_values = accuracies(start_price, days, mu, sigma, prev_days)
  147. arr.extend(accuracy_values)
  148. mean_accuracy = np.mean(arr)
  149. accuracies_list.append(mean_accuracy)
  150. predicted_prices_list.append(prev_days)
  151. plt.figure(figsize=(10, 6))
  152. plt.plot(predicted_prices_list, accuracies_list, marker='o', linestyle='-', color='b')
  153. plt.xlabel('Days Shifted')
  154. plt.ylabel('Accuracy (%)')
  155. plt.title('Accuracy of Predictions vs. Days Shifted')
  156. plt.grid(True)
  157. plt.show()
  158. def main():
  159. # Your main code goes here
  160. print("This is the main method.")
  161. # Check if the script is being run as the main program
  162. if __name__ == "__main__":
  163. # Call the main method
  164. main()
Tip!

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

Comments

Loading...