<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=USD"
eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=USD"
# Fetch current BTC price
btc_data_request = requests.get(btc_url).json()
btc_price = btc_data_request['data']['1']['quotes']['USD']['price']
btc_price
# Fetch current ETH price
eth_data_request = requests.get(eth_url).json()
eth_price = eth_data_request['data']['1027']['quotes']['USD']['price']
eth_price
# Compute current value of my crypto
my_btc_value = my_btc * btc_price
my_eth_value = my_eth * eth_price
# 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 $60586.80
The current value of your 5.3 ETH is $12124.44<jupyter_text>Collect Investments Data Using Alpaca: `SPY` (stocks) and `AGG` (bonds)<jupyter_code># Current amount of shares
my_agg = 200
my_spy = 50
# 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
alpaca_api = tradeapi.REST(
    alpaca_api_key,
    alpaca_secret_key,
    api_version="v3")
alpaca_api
# Format current date as ISO format
current_date = pd.Timestamp("2021-04-21", tz="America/New_York").isoformat()
current_date
# Set the tickers
tickers = ["AGG", "SPY"]

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

# Get current closing prices for SPY and AGG
data = alpaca_api.get_barset(
    tickers,
    timeframe,
    start = current_date,
    end = current_date
).df

# Preview DataFrame
data
# Pick AGG and SPY close prices
agg_close_price = data["AGG"]["close"][0]
spy_close_price = data["SPY"]["close"][0]

# 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 = agg_close_price * my_agg
my_spy_value = spy_close_price * my_spy

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

# Create savings DataFrame
df_savings = pd.DataFrame(
    [
        [my_btc_value + my_eth_value],
        [my_spy_value + my_agg_value]
    ],
    index = ["Crypto Value", "Stock Value"],
    columns = ["amount"]
)

# Display savings DataFrame
display(df_savings)
# Plot savings pie chart
df_savings.plot(kind = "pie", y = "amount", figsize = (10,10))
# Set ideal emergency fund
emergency_fund = monthly_income * 3

# Calculate total amount of savings
total_savings = df_savings["amount"]["Crypto Value"] + df_savings["amount"]["Stock Value"]

# Validate saving health
if total_savings > emergency_fund:
    print("Congratulations! You have enough money in this fund.")
elif total_savings == emergency_fund:
    print("Congratulations! You have reached your financial goal.")
else:
    print(f"You are ${(emergency_fund-total_savings):0.2f} away from reaching your financial goal.")<jupyter_output>Congratulations! You have enough money in this 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-04-21', tz='America/New_York').isoformat()
end_date = current_date
# Get 5 years' worth of historical data for SPY and AGG
df_stock_data = alpaca_api.get_barset(
    tickers,
    timeframe,
    start = start_date,
    end = end_date
).df

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

# Print summary statistics
print(summary_stats)<jupyter_output>count           5.000000e+02
mean            3.320782e+08
std             4.589605e+08
min             7.477927e+06
25%             8.748069e+07
50%             1.892350e+08
75%             3.722068e+08
max             4.394864e+09
95% CI Lower    2.305854e+07
95% CI Upper    1.696391e+09
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(summary_stats[8] * initial_investment, 2)
ci_upper = round(summary_stats[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 $461170771780.84 and $33927814613271.38<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_2 = 20000 * 1.5

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $30,000
ci_lower_2 = round(summary_stats[8] * initial_investment_2, 2)
ci_upper_2 = round(summary_stats[9] * initial_investment_2, 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_2} and ${ci_upper_2}")<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 $691756157671.26 and $50891721919907.06<jupyter_text>Optional Challenge - Early Retirement Five Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 5 years cumulative returns
monte_carlo_sim_5 = MCSimulation(
    portfolio_data = df_stock_data,
    num_simulation = 500,
    weights = [.40,.60],
    num_trading_days = 252*5
)
monte_carlo_sim_5.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 5 years cumulative returns
monte_carlo_sim_5.calc_cumulative_return()
# Plot simulation outcomes
monte_carlo_sim_5.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot_5 = monte_carlo_sim_5.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
summary_stats_5 = monte_carlo_sim_5.summarize_cumulative_return()

# Print summary statistics
print(summary_stats_5)
# Set initial investment
initial_investment_5 = 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(summary_stats_5[8]*60000,2)
ci_upper_five = round(summary_stats_5[9]*60000,2)

# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment_5} 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 $583875.41 and $3263761.22<jupyter_text>Ten Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 10 years cumulative returns
monte_carlo_sim_10 = MCSimulation(
    portfolio_data = df_stock_data,
    num_simulation = 500,
    weights = [.40,.60],
    num_trading_days = 252*10
)
monte_carlo_sim_10.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 10 years cumulative returns
monte_carlo_sim_10.calc_cumulative_return()
# Plot simulation outcomes
monte_carlo_sim_10.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot_10 = monte_carlo_sim_10.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
summary_stats_10 = monte_carlo_sim_10.summarize_cumulative_return()

# Print summary statistics
print(summary_stats_10)
# Set initial investment
initial_investment_10 = 60000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $60,000
ci_lower_ten = round(summary_stats_10[8]*60000,2)
ci_upper_ten = round(summary_stats_10[9]*60000,2)

# Print results
print(f"There is a 95% chance that an initial investment of ${initial_investment_10} in the portfolio"
      f" over the next 10 years will end within in the range of"
      f" ${ci_lower_ten} and ${ci_upper_ten}")<jupyter_output>There is a 95% chance that an initial investment of $60000 in the portfolio over the next 10 years will end within in the range of $8163984.57 and $107271640.38
{'fraction_non_alphanumeric': 0.08243451463790447, 'fraction_numerical': 0.052003081664098616, 'mean_word_length': 5.3054037644201575, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 34, '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': '588951', 'license': 'ADSL', 'n_tokens_mistral': 3714, 'n_tokens_neox': 3341, 'n_words': 1081, 'path': '.ipynb_checkpoints/financial-planner-checkpoint.ipynb', 'repo_name': 'JUnelus/Financial-Planning-APIs', 'size': '10384'}