<jupyter_start><jupyter_text>Unit 5 - Financial Planning<jupyter_code># Initial imports
import os
import requests
import pandas as pd
from dotenv import load_dotenv
import alpaca_trade_api as tradeapi
from MCForecastTools import MCSimulation


%matplotlib inline
# Load .env enviroment variables
load_dotenv()<jupyter_output><empty_output><jupyter_text>Part 1 - Personal Finance Planner  Collect Crypto Prices Using the requests Library<jupyter_code># Set current amount of crypto assets
my_btc = 1.2
my_eth = 5.3
 # Crypto API URLs
btc_url = "https://api.alternative.me/v2/ticker/Bitcoin/?convert=CAD"
eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=CAD"
# Fetch current BTC price
btc_response_data = requests.get(btc_url)
btc_response_content = btc_response_data.content
btc_data = btc_response_data.json()
import json
print(json.dumps(btc_data, indent=4))
# Fetch current ETH price
eth_response_data = requests.get(eth_url)
eth_response_content = eth_response_data.content
eth_data = eth_response_data.json()
print(json.dumps(eth_data, indent=4))
# Compute current value of my crypto
btc_value = btc_data["data"]["1"]["quotes"]["USD"]["price"]
my_btc_value = btc_value * my_btc
eth_value = eth_data["data"]["1027"]["quotes"]["USD"]["price"]
my_eth_value = eth_value * my_eth

# Print current crypto wallet balance
print(f"The current value of your {my_btc} BTC is ${my_btc_value:0.2f}")
print(f"The current value of your {my_eth} ETH is ${my_eth_value:0.2f}")<jupyter_output>The current value of your 1.2 BTC is $69374.40
The current value of your 5.3 ETH is $9543.66<jupyter_text>Collect Investments Data Using Alpaca: SPY (stocks) and AGG (bonds)<jupyter_code># Current amount of shares
my_SPY = 50
my_AGG = 200

 # Set Alpaca API key and secret
alpaca_api_key = os.getenv("ALPACA_API_KEY")
alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY")

# Create the Alpaca API object
api = tradeapi.REST( alpaca_api_key, alpaca_secret_key, api_version="v2")
# Format current date as ISO format
today = pd.Timestamp("2021-03-19", tz="America/New_York").isoformat()

# Set the tickers
tickers = ["AGG", "SPY"]

# Set timeframe to '1D' for Alpaca API
timeframe = "1D"

# Get current closing prices for SPY and AGG
portfolio_df = api.get_barset(tickers,timeframe,start=today,end=today,).df

# Preview DataFrame
portfolio_df.head()
 # Pick AGG and SPY close prices
agg_close_price = float(portfolio_df["AGG"]["close"])
spy_close_price = float(portfolio_df["SPY"]["close"])


# Print AGG and SPY close prices
print(f"Current AGG closing price: ${agg_close_price}")
print(f"Current SPY closing price: ${spy_close_price}")
# Compute the current value of shares

my_agg_value = my_AGG * agg_close_price 
my_spy_value = my_SPY * spy_close_price 

# Print current value of share
print(f"The current value of your {my_SPY} SPY shares is ${my_spy_value:0.2f}")
print(f"The current value of your {my_AGG} AGG shares is ${my_agg_value:0.2f}")<jupyter_output>The current value of your 50 SPY shares is $19475.00
The current value of your 200 AGG shares is $22700.00<jupyter_text>Savings Health Analysis<jupyter_code># Set monthly household income
monthly_income = 12000

# Create savings DataFrame
crypto_portfolio = my_btc_value + my_eth_value
stock_portfolio = my_spy_value + my_agg_value
data = {'amount': [crypto_portfolio,stock_portfolio]}
df_savings = pd.DataFrame(data, index=['crypto', 'shares'])
# Display savings DataFrame
display(df_savings)
df_savings.plot.pie(y='amount',title='composition of personal savings')
# Set ideal emergency fund
emergency_fund = monthly_income * 3

# Calculate total amount of savings
total_savings = crypto_portfolio + stock_portfolio

# Validate saving health

if emergency_fund < total_savings:
        print("Congratulations! You have enough money in your emergency fund.")
elif emergency_fund == total_savings:
        print("You are doing fine, still need more improvements through")
else:
        print(f"You are {emergency_fund - total_savings} dollars away from reaching the goal")<jupyter_output>Congratulations! You have enough money in your emergency fund.<jupyter_text>Part 2 - Retirement Planning  Monte Carlo Simulation<jupyter_code># Set start and end dates of five years back from today.
# Sample results may vary from the solution based on the time frame chosen
start_date = pd.Timestamp('2016-03-19', tz='America/New_York').isoformat()
end_date = pd.Timestamp('2021-03-19', tz='America/New_York').isoformat()
# Get 5 years' worth of historical data for SPY and AGG
tickers = ["SPY","AGG"]
stock_data = api.get_barset(tickers, timeframe, start=start_date, end=end_date).df

# Display sample data
stock_data.head()
# Configuring a Monte Carlo simulation to forecast 30 years cumulative returns
MC_even_dist = MCSimulation(stock_data, weights = [.60,.40], num_simulation = 500, num_trading_days = 252*30 )
# Printing the simulation input data
MC_even_dist.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 30 years cumulative returns
MC_even_dist.calc_cumulative_return()
# Plot simulation outcomes
line_plot = MC_even_dist.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot = MC_even_dist.plot_distribution()<jupyter_output><empty_output><jupyter_text>Retirement Analysis<jupyter_code># Fetch summary statistics from the Monte Carlo simulation results
even_tbl = MC_even_dist.summarize_cumulative_return()

# Print summary statistics
print(even_tbl)<jupyter_output>count           500.000000
mean             15.623185
std               6.052524
min               5.529973
25%              11.328437
50%              14.622053
75%              18.554302
max              42.137135
95% CI Lower      7.214141
95% CI Upper     31.775032
Name: 7560, dtype: float64<jupyter_text>Calculate the expected portfolio return at the 95% lower and upper confidence intervals based on a $20,000 initial investment.<jupyter_code># Set initial investment
initial_investment = 20000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $20,000
ci_lower = round(even_tbl[8]*(initial_investment),2)
ci_upper = round(even_tbl[9]*(initial_investment),2)

# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment} in the portfolio"
      f" over the next 30 years will end within in the range of"
      f" ${ci_lower} and ${ci_upper}")<jupyter_output>There is a 95% chance that an initial investment of $20000 in the portfolio over the next 30 years will end within in the range of $144282.83 and $635500.64<jupyter_text>Calculate the expected portfolio return at the 95% lower and upper confidence intervals based on a 50% increase in the initial investment.<jupyter_code># Set initial investment
initial_investment = 20000 * 1.5

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $20,000
ci_lower = round(even_tbl[8]*(initial_investment),2)
ci_upper = round(even_tbl[9]*(initial_investment),2)

# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment} in the portfolio"
      f" over the next 30 years will end within in the range of"
      f" ${ci_lower} and ${ci_upper}")<jupyter_output>There is a 95% chance that an initial investment of $30000.0 in the portfolio over the next 30 years will end within in the range of $216424.24 and $953250.96<jupyter_text>Optional Challenge - Early Retirement   Five Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 5 years cumulative returns
MC_even_dist_5Y = MCSimulation(stock_data, weights = [.60,.40], num_simulation = 500, num_trading_days = 252*5)
MC_even_dist_5Y.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 5 years cumulative returns
MC_even_dist_5Y.calc_cumulative_return()
# Plot simulation outcomes
line_plot_5Y = MC_even_dist_5Y.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot_5Y = MC_even_dist_5Y.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
even_tbl_5Y = MC_even_dist_5Y.summarize_cumulative_return()
# Print summary statistics
print(even_tbl_5Y)
# Set initial investment
initial_investment_5Y = 60000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $60,000
ci_lower_five = round(even_tbl_5Y[8]*(initial_investment_5Y),2)
ci_upper_five = round(even_tbl_5Y[9]*(initial_investment_5Y),2)
# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment_5Y} in the portfolio"
      f" over the next 5 years will end within in the range of"
      f" ${ci_lower_five} and ${ci_upper_five}")<jupyter_output>There is a 95% chance that an initial investment of $60000 in the portfolio over the next 5 years will end within in the range of $70367.68 and $124629.76<jupyter_text>Ten Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 10 years cumulative returns
MC_even_dist_10Y = MCSimulation(stock_data, weights = [.60,.40], num_simulation = 500, num_trading_days = 252*10)
MC_even_dist_10Y.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 10 years cumulative returns
MC_even_dist_10Y.calc_cumulative_return()
# Plot simulation outcomes
line_plot_10Y = MC_even_dist_10Y.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot_10Y = MC_even_dist_10Y.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
even_tbl_10Y = MC_even_dist_10Y.summarize_cumulative_return()
# Print summary statistics
print(even_tbl_10Y)
# Set initial investment
initial_investment_10Y = 60000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $60,000
ci_lower_five = round(even_tbl_5Y[8]*(initial_investment_10Y),2)
ci_upper_five = round(even_tbl_5Y[9]*(initial_investment_10Y),2)
# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment_10Y} in the portfolio"
      f" over the next 5 years will end within in the range of"
      f" ${ci_lower_five} and ${ci_upper_five}")<jupyter_output>There is a 95% chance that an initial investment of $60000 in the portfolio over the next 5 years will end within in the range of $70367.68 and $124629.76
{'fraction_non_alphanumeric': 0.08336538461538462, 'fraction_numerical': 0.045384615384615384, 'mean_word_length': 5.740764744005185, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 33, 'https://': 2, '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': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '351662', 'license': 'ADSL', 'n_tokens_mistral': 3651, 'n_tokens_neox': 3313, 'n_words': 1069, 'path': 'financial-planner_output_code.ipynb', 'repo_name': 'desmondphan951/Financial-Planning', 'size': '10400'}