In this activity, Harold's manager wants Harold to take a look at one year's worth of TSLA stock prices and plot a potential stock trajectory for where TSLA stock prices could go in the next 3 years. In addition, he would like to know how a $10,000 investment would perform given the simulated results.
Help Harold by creating a Monte Carlo simulation that simulates the next 252 * 3 trading days using three years worth of TSLA stock data. Plot the simulated results of TSLA daily returns over the next 3 years as well as the corresponding simulated outcomes.
# Import libraries and dependenciesimportosimportnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltimportalpaca_trade_apiastradeapifromMCForecastToolsimportMCSimulation%matplotlibinline
# Load .env enviroment variablesfromdotenvimportload_dotenvload_dotenv()
# Set Alpaca API key and secretalpaca_api_key=os.getenv("ALPACA_API_KEY")
alpaca_secret_key=os.getenv("ALPACA_SECRET_KEY")
api=tradeapi.REST(
alpaca_api_key,
alpaca_secret_key,
api_version="v2"
)
Get 3 Years Worth of Data via API Call and Read in as DataFrame
# Set the tickerticker="TSLA"# Set timeframe to '1D'timeframe="1D"# Set start and end datetimes of 3 years from Todaystart_date=pd.Timestamp("2017-05-04", tz="America/New_York").isoformat()
end_date=pd.Timestamp("2020-05-04", tz="America/New_York").isoformat()
# Get 3 years worth of historical data for TSLAticker_data=api.get_barset(
ticker,
timeframe,
start=start_date,
end=end_date,
limit=1000,
).dfticker_data.head()
# Set number of simulationsnum_sims=1000# Configure a Monte Carlo simulation to forecast three years daily returnsMC_TSLA=MCSimulation(
portfolio_data=ticker_data,
num_simulation=num_sims,
num_trading_days=252*3
)
# Run Monte Carlo simulations to forecast three years daily returnsMC_TSLA.calc_cumulative_return()
Running Monte Carlo simulation number 0.
Running Monte Carlo simulation number 10.
Running Monte Carlo simulation number 20.
Running Monte Carlo simulation number 30.
Running Monte Carlo simulation number 40.
Running Monte Carlo simulation number 50.
Running Monte Carlo simulation number 60.
Running Monte Carlo simulation number 70.
Running Monte Carlo simulation number 80.
Running Monte Carlo simulation number 90.
Running Monte Carlo simulation number 100.
Running Monte Carlo simulation number 110.
Running Monte Carlo simulation number 120.
Running Monte Carlo simulation number 130.
Running Monte Carlo simulation number 140.
Running Monte Carlo simulation number 150.
Running Monte Carlo simulation number 160.
Running Monte Carlo simulation number 170.
Running Monte Carlo simulation number 180.
Running Monte Carlo simulation number 190.
Running Monte Carlo simulation number 200.
Running Monte Carlo simulation number 210.
Running Monte Carlo simulation number 220.
Running Monte Carlo simulation number 230.
Running Monte Carlo simulation number 240.
Running Monte Carlo simulation number 250.
Running Monte Carlo simulation number 260.
Running Monte Carlo simulation number 270.
Running Monte Carlo simulation number 280.
Running Monte Carlo simulation number 290.
Running Monte Carlo simulation number 300.
Running Monte Carlo simulation number 310.
Running Monte Carlo simulation number 320.
Running Monte Carlo simulation number 330.
Running Monte Carlo simulation number 340.
Running Monte Carlo simulation number 350.
Running Monte Carlo simulation number 360.
Running Monte Carlo simulation number 370.
Running Monte Carlo simulation number 380.
Running Monte Carlo simulation number 390.
Running Monte Carlo simulation number 400.
Running Monte Carlo simulation number 410.
Running Monte Carlo simulation number 420.
Running Monte Carlo simulation number 430.
Running Monte Carlo simulation number 440.
Running Monte Carlo simulation number 450.
Running Monte Carlo simulation number 460.
Running Monte Carlo simulation number 470.
Running Monte Carlo simulation number 480.
Running Monte Carlo simulation number 490.
Running Monte Carlo simulation number 500.
Running Monte Carlo simulation number 510.
Running Monte Carlo simulation number 520.
Running Monte Carlo simulation number 530.
Running Monte Carlo simulation number 540.
Running Monte Carlo simulation number 550.
Running Monte Carlo simulation number 560.
Running Monte Carlo simulation number 570.
Running Monte Carlo simulation number 580.
Running Monte Carlo simulation number 590.
Running Monte Carlo simulation number 600.
Running Monte Carlo simulation number 610.
Running Monte Carlo simulation number 620.
Running Monte Carlo simulation number 630.
Running Monte Carlo simulation number 640.
Running Monte Carlo simulation number 650.
Running Monte Carlo simulation number 660.
Running Monte Carlo simulation number 670.
Running Monte Carlo simulation number 680.
Running Monte Carlo simulation number 690.
Running Monte Carlo simulation number 700.
Running Monte Carlo simulation number 710.
Running Monte Carlo simulation number 720.
Running Monte Carlo simulation number 730.
Running Monte Carlo simulation number 740.
Running Monte Carlo simulation number 750.
Running Monte Carlo simulation number 760.
Running Monte Carlo simulation number 770.
Running Monte Carlo simulation number 780.
Running Monte Carlo simulation number 790.
Running Monte Carlo simulation number 800.
Running Monte Carlo simulation number 810.
Running Monte Carlo simulation number 820.
Running Monte Carlo simulation number 830.
Running Monte Carlo simulation number 840.
Running Monte Carlo simulation number 850.
Running Monte Carlo simulation number 860.
Running Monte Carlo simulation number 870.
Running Monte Carlo simulation number 880.
Running Monte Carlo simulation number 890.
Running Monte Carlo simulation number 900.
Running Monte Carlo simulation number 910.
Running Monte Carlo simulation number 920.
Running Monte Carlo simulation number 930.
Running Monte Carlo simulation number 940.
Running Monte Carlo simulation number 950.
Running Monte Carlo simulation number 960.
Running Monte Carlo simulation number 970.
Running Monte Carlo simulation number 980.
Running Monte Carlo simulation number 990.
# Use the `plot` function to visually analyze the trajectory of TSLA stock daily returns on the next three years of trading days simulationdf_simulated_returns.plot(title="Simulated Daily Returns Behavior of TSLA Stock Over the Next Year")
<matplotlib.axes._subplots.AxesSubplot at 0x7faaf8c88610>
Calculate the Simulated Profits/Losses of $10,000 Investment in TSLA Over the Next Three Years
# Set initial investmentinitial_investment=10000# Multiply an initial investment by the daily returns of simulative stock prices to return the progression of daily returns in terms of moneycumulative_pnl=initial_investment*df_simulated_returns# Display sample datacumulative_pnl.head()
Plot the Simulated Profits/Losses of $10,000 Investment in TSLA Over the Next 252 Trading Days
# Use the 'plot' function to create a chart of the simulated profits/lossescumulative_pnl.plot(title="Simulated Outcomes Behavior of TSLA Stock Over the Next Year")
<matplotlib.axes._subplots.AxesSubplot at 0x7faaf2e62190>
Calculate the range of the possible outcomes of our $10,000 investments in TSLA stocks
# Fetch summary statistics from the Monte Carlo simulation resultstbl=MC_TSLA.summarize_cumulative_return()
# Print summary statisticsprint(tbl)
count 1000.000000
mean 4.906131
std 6.899562
min 0.126797
25% 1.232316
50% 2.655507
75% 6.011975
max 85.991793
95% CI Lower 0.371666
95% CI Upper 23.772773
Name: 756, dtype: float64
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $10,000 investments in TSLA stocksci_lower=round(tbl[8]*10000,2)
ci_upper=round(tbl[9]*10000,2)
# Print resultsprint(f"There is a 95% chance that an initial investment of $10,000 in the portfolio"f" over the next year will end within in the range of"f" ${ci_lower} and ${ci_upper}.")
There is a 95% chance that an initial investment of $10,000 in the portfolio over the next year will end within in the range of $3716.66 and $237727.73.