Open main menu
Home
Random
Donate
Recent changes
Special pages
Community portal
Preferences
About Stockhub
Disclaimers
Search
User menu
Talk
Contributions
Create account
Log in
Editing
Safran SA
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Monte Carlo Simulations for Stock Price Predictions - Python Code === <syntaxhighlight lang="python"> """ Created on Thu Jul 27 18:31:35 2023 @author: Jérémy Archier """ import csv import matplotlib.pyplot as plt import numpy as np from datetime import datetime, timedelta from scipy.stats import norm # Step 1: Load data from the CSV file csv_file_path = "SAF.PA.csv" dates = [] opens = [] with open(csv_file_path, newline="") as csvfile: csv_reader = csv.DictReader(csvfile) for row in csv_reader: # Check if the 'Open' value is 'null' or empty or 0 if row['Open'].strip() == '' or row['Open'].lower() == 'null' or float(row['Open']) == 0: # Skip the data point if there is no valid 'Open' value continue # Convert the 'Open' value to a float open_value = float(row['Open']) # Convert the 'Date' value to a datetime object date_value = datetime.strptime(row['Date'], '%Y-%m-%d') # Append the 'Date' and 'Open' values to their respective lists dates.append(date_value) opens.append(open_value) # Step 2: Compute the logarithmic returns of the stock log_returns = np.log(np.array(opens[1:]) / np.array(opens[:-1])) # Plot the previous prices plt.figure(figsize=(10, 5)) plt.plot(dates, opens, linestyle='-', color='b') plt.xlabel('Date') plt.ylabel('Open Value') plt.title('Open Value as a Function of Dates') plt.xticks(rotation=45) plt.grid(True) plt.tight_layout() plt.show() # Plot the log returns plt.figure(figsize=(6, 5)) plt.hist(log_returns, bins=30, edgecolor='k') plt.xlabel("Logarithmic Returns") plt.ylabel("Frequency") plt.title("Distribution of Logarithmic Returns") plt.grid(True) plt.tight_layout() plt.show() # Step 3: Compute the Drift u = log_returns.mean() var = log_returns.var() drift = u - (0.5 * var) # Step 4: Compute the Variance and Daily Returns stdev = log_returns.std() days = 50 trials = 1000000 # Reduce the number of trials to 100 for faster computation Z = norm.ppf(np.random.rand(days, trials)) # days, trials daily_returns = np.exp(drift + stdev * Z) # Step 5: Calculating the stock price for every trial price_paths = np.zeros_like(daily_returns) price_paths[0] = opens[-1] for t in range(1, days): price_paths[t] = price_paths[t - 1] * daily_returns[t] # Step 6: Calculate the probability of reaching the target price target_price = 150.0 # Replace this with the desired target price # Count how many times the stock price reaches or exceeds the target price in each trial success_count = np.sum(price_paths[-1, :] >= target_price) # Calculate the probability as the ratio of successful trials to total trials probability = success_count / trials # Print the probability print(f"The probability of the stock reaching or exceeding {target_price} is: {probability:.2%}") # Step 7: Plot the histogram of final stock prices final_prices = price_paths[-1, :] plt.figure(figsize=(10, 6)) plt.hist(final_prices, bins=30, edgecolor='k', density=True) plt.axvline(x=target_price, color='r', linestyle='dashed', linewidth=2, label=f'Target Price ({target_price})') plt.xlabel('Stock Price') plt.ylabel('Probability Density') plt.title('Probability Distribution of Final Stock Prices') plt.legend() plt.grid(True) plt.tight_layout() plt.show() # Step 8: Plot the price paths for each trial plt.figure(figsize=(10, 6)) for trial in range(trials): trial_dates = [dates[-1] + timedelta(days=i) for i in range(days)] plt.plot(trial_dates, price_paths[:, trial], linewidth=0.5) plt.xlabel('Date') plt.ylabel('Stock Price') plt.title('Monte Carlo Simulation of Stock Price') plt.tight_layout() plt.grid(True) plt.show() </syntaxhighlight>
Summary:
Please note that all contributions to Stockhub may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Stockhub:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)