<jupyter_start><jupyter_text>Portfolio PlannerIn this activity, you will use the iedfinance api to grab historical data for a 60/40 portfolio using `SPY` to represent the stock portion and `AGG` to represent the bonds.<jupyter_code>from iexfinance.stocks import get_historical_data
import iexfinance as iex<jupyter_output><empty_output><jupyter_text>Data CollectionIn this step, you will need to use the IEX api to fetch closing prices for the `SPY` and `AGG` tickers. Save the results as a pandas DataFrame<jupyter_code>tickers = ["SPY", "AGG"]
end_date = datetime.now()
start_date = end_date + timedelta(-1260)
df = get_historical_data(tickers, start_date, end_date,  output_format='pandas')
df.head

df.drop(columns = ['open', 'high', 'low', 'volume'], level=1, inplace=True)
df.head()<jupyter_output><empty_output><jupyter_text>Monte Carlo SimulationIn this step, you will run Monte Carlo Simulations for your portfolio to model portfolio performance at different retirement ages. Complete the following steps:1. Calculate the daily returns for the SPY and AGG closing prices.2. Calculate volatility for both the SPY and AGG closing prices.3. Find the last day's closing price for both stocks and save those as variables.4. Run a Monte Carlo Simulation of at least 100 iterations and generate at least 20 years of closing prices HINTS:There are 252 trading days per year, so the number of records to generate for each Monte Carlo run will be 252 days * 20 years<jupyter_code># Calculate the daily roi for the stocks
daily_returns = df.pct_change()
daily_returns.head()

avg_daily_return_spy = daily_returns.mean()['SPY']['close']
avg_daily_return_agg = daily_returns.mean()['AGG']['close']

print(avg_daily_return_agg)
print(avg_daily_return_spy)
# Calculate volatility
std_daily_return_spy = daily_returns.std()['SPY']['close']
std_daily_return_agg = daily_returns.std()['AGG']['close']

print(std_daily_return_agg)
print(std_daily_return_spy)
# Save the last day's closing price
spy_last_price = df['SPY']['close'][-1]
agg_last_price = df['AGG']['close'][-1]
# Setup the Monte Carlo Parameters
num_simulations = 500
num_trading_days = 252 * 30
monte_carlo = pd.DataFrame()
portfolio_cumulative_returns = pd.DataFrame()
num_simulations = 500
num_trading_days = 252 * 30

spy_last_price = df['SPY']['close'][-1]
agg_last_price = df['AGG']['close'][-1]


monte_carlo = pd.DataFrame()
portfolio_cumulative_returns = pd.DataFrame()

for n in range(num_simulations):
    simulated_spy_prices = [spy_last_price]
    simulated_agg_prices = [agg_last_price]
    
    for i in range(num_trading_days):
        simulated_spy_price = simulated_spy_prices[-1] * (1 + np.random.normal(avg_daily_return_spy, std_daily_return_spy))
        simulated_agg_price = simulated_agg_prices[-1] * (1 + np.random.normal(avg_daily_return_agg, std_daily_return_agg))
        
        simulated_spy_prices.append(simulated_spy_price)
        simulated_agg_prices.append(simulated_agg_price)
        
        
    monte_carlo['SPY Prices'] = pd.Series(simulated_spy_prices)
    monte_carlo['AGG Prices'] = pd.Series(simulated_agg_prices)
    
    
    simulated_daily_return = monte_carlo.pct_change()
    
    
    weights = [0.60, 0.40]
    
    portfolio_daily_return = simulated_daily_return.dot(weights)
    portfolio_cumulative_returns[n] = (1+ portfolio_daily_return.fillna(0)).cumprod()


portfolio_cumulative_returns.head()
# Visualize the Simulation
portfolio_cumulative_returns.plot(legend=None)
plt.show()
# Select the last row for the cumulative returns (cumulative returns at 30 years)
ending_cumulative_returns_30 = portfolio_cumulative_returns.iloc[-1, :]
ending_cumulative_returns_30.head()
# Select the last row for the cumulative returns (cumulative returns at 20 years)
ending_cumulative_returns_20 = portfolio_cumulative_returns.iloc[-2521, :]
ending_cumulative_returns_20.head()
# Display the 90% confidence interval for the ending returns
confidence_interval_30 = ending_cumulative_returns_30.quantile(q=[0.05, 0.95])
confidence_interval_20 = ending_cumulative_returns_20.quantile(q=[0.05, 0.95])

print(confidence_interval_30)
print(confidence_interval_20)
# Visualize the distribution of the ending returns
ending_cumulative_returns_30.plot(kind='hist', density=True, bins=20)
ending_cumulative_returns_30.value_counts(bins=10) / len(ending_cumulative_returns_30)
plt.axvline(confidence_interval_30.iloc[0], color='r')
plt.axvline(confidence_interval_30.iloc[1], color='r')<jupyter_output><empty_output><jupyter_text>---  Retirement AnalysisIn this section, you will use the monte carlo model to answer the following retirement planning questions:1. What are the expected cumulative returns at 30 years for the 10th, 50th, and 90th percentiles?2. Given an initial investment of `$20,000`, what is the expected portfolio return in dollars at the 10th, 50th, and 90th percentiles?3. Given the current projected annual income from the Plaid analysis, will a 4% withdraw rate from the retirement portfolio meet or exceed that value at the 10th percentile?4. How would a 50% increase in the initial investment amount affect the 4% retirement withdrawal?  What are the expected cumulative returns at 30 years for the 10th, 50th, and 90th percentiles?<jupyter_code>initial_investment = 20000
confidence_interval_10 = ending_cumulative_returns_30.quantile(q=[0.95, 0.05])
confidence_interval_50 = ending_cumulative_returns_30.quantile(q=[0.5, 0.5])

investment_pnl_lower_bound_90 = (initial_investment * confidence_interval_30.iloc[0])
investment_pnl_upper_bound_90 = (initial_investment * confidence_interval_30.iloc[1])
       
investment_pnl_lower_bound_50 = (initial_investment * confidence_interval_50.iloc[0])
investment_pnl_upper_bound_50 = (initial_investment * confidence_interval_50.iloc[1])

investment_pnl_lower_bound_10 = (initial_investment * confidence_interval_10.iloc[0])
investment_pnl_upper_bound_10 = (initial_investment * confidence_interval_10.iloc[1])

ending_cumulative_returns_30.value_counts(bins=10) / len(ending_cumulative_returns_30)<jupyter_output><empty_output><jupyter_text>Given an initial investment of `$20,000`, what is the expected portfolio return in dollars at the 10th, 50th, and 90th percentiles?<jupyter_code>print(f"There is a 90% chance that an initial investment of $20,000 in the portfolio"
      f" over the next 7560 trading days will end within in the range of"
      f" ${investment_pnl_lower_bound_90} and ${investment_pnl_upper_bound_90}")
print()
print()

print(f"There is a 50% chance that an initial investment of $20,000 in the portfolio"
      f" over the next 7560 trading days will end within in the range of"
      f" ${investment_pnl_lower_bound_50} and ${investment_pnl_upper_bound_50}")
print()
print()
print(f"There is a 10% chance that an initial investment of $20,000 in the portfolio"
      f" over the next 7560 trading days will end within in the range of"
      f" ${investment_pnl_lower_bound_10} and ${investment_pnl_upper_bound_10}")<jupyter_output>There is a 90% chance that an initial investment of $20,000 in the portfolio over the next 7560 trading days will end within in the range of $66354.83353359034 and $264764.45699693996


There is a 50% chance that an initial investment of $20,000 in the portfolio over the next 7560 trading days will end within in the range of $142715.9358974036 and $142715.9358974036


There is a 10% chance that an initial investment of $20,000 in the portfolio over the next 7560 trading days will end within in the range of $264764.45699693996 and $66354.83353359034<jupyter_text>Given the current projected annual income from the Plaid analysis, will a 4% withdraw rate from the retirement portfolio meet or exceed that value at the 10th percentile?Note: This is effectively saying that 90% of the expected returns will be greater than the return at the 10th percentile, so this can help measure the uncertainty about having enough funds at retirement<jupyter_code>withraw = 0.04 * (initial_investment * ending_cumulative_returns_30.sum())
withraw

exceeding value at the 10th percentile<jupyter_output><empty_output><jupyter_text>How would a 50% increase in the initial investment amount affect the 4% retirement withdrawal?<jupyter_code>also amount of retirement withdrawl will increased by 50% percent.<jupyter_output><empty_output><jupyter_text>Optional ChallengeIn this section, you will calculate and plot the cumulative returns for the median and 90% confidence intervals. This plot shows the expected cumulative returns for any given day between the first day and the last day of investment.<jupyter_code># YOUR CODE HERE<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07848568790397045, 'fraction_numerical': 0.048591874422899355, 'mean_word_length': 6.137561779242175, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '482022', 'license': 'ADSL', 'n_tokens_mistral': 3038, 'n_tokens_neox': 2666, 'n_words': 847, 'path': 'portfolio_planner_hw.ipynb', 'repo_name': 'jrmatos92/API_HW', 'size': '8664'}