<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
import json

%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"

btc_url = btc_url + "?format=json"
eth_url = eth_url + "?format=json"
# Fetch current BTC price
current_btc_response = requests.get(btc_url).json()
current_btc_price = current_btc_response["data"]["1"]["quotes"]["USD"]["price"]
# Fetch current ETH price
current_eth_response = requests.get(eth_url).json()
current_eth_price = current_eth_response["data"]["1027"]["quotes"]["USD"]["price"]
# Compute current value of my crpto
my_btc_value = current_btc_price * my_btc
my_eth_value = current_eth_price * 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 $42769.20
The current value of your 5.3 ETH is $11953.62<jupyter_text>Collect Investments Data Using Alpaca: `SPY` (stocks) and `AGG` (bonds)<jupyter_code># Set 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 = tradeapi.REST(
    alpaca_api_key,
    alpaca_secret_key,
    api_version="v2")
# Format current date as ISO format
today = pd.Timestamp("2021-06-18", tz="Australia/Perth").isoformat()

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

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

# Get current closing prices for SPY and AGG
# (use a limit=1000 parameter to call the most recent 1000 days of data)
df_portfolio = alpaca.get_barset(
    tickers,
    timeframe,
    end = today,
    limit=1000
).df

print(f"Today time:{today}")
# Preview DataFrame
df_portfolio.head()

# Pick AGG and SPY close prices
# YOUR CODE HERE!
df_closing_prices = pd.DataFrame()
df_closing_prices["AGG"] = df_portfolio["AGG"]["close"]
df_closing_prices["SPY"] = df_portfolio["SPY"]["close"]

# Drop null value
df_closing_prices = df_closing_prices.dropna()
# Drop the time component of the date
df_closing_prices.index = df_closing_prices.index.date

# Print AGG and SPY close prices
agg_close_price = df_closing_prices["AGG"][-1]
spy_close_price = df_closing_prices["SPY"][-1]

print(f"Current AGG closing price: ${agg_close_price}")
print(f"Current SPY closing price: ${spy_close_price}")

# Compute the current value of shares
# YOUR CODE HERE!
my_agg_value = agg_close_price * my_agg
my_spy_value = spy_close_price * my_spy

# Print current value of shares
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 $22998.00
The current value of your 50 SPY shares is $21098.50<jupyter_text>Savings Health Analysis<jupyter_code># Set monthly household income
# YOUR CODE HERE!
monthly_income = 12000

# Consolidate financial assets data
total_crypto = my_btc_value + my_eth_value
total_share = my_agg_value + my_spy_value
 
data = [total_crypto, total_share]

# Create savings DataFrame
df_savings = pd.DataFrame(data, columns = ["amount"], index = ["crypto", "share"])

# Display savings DataFrame
display(df_savings)
# Plot savings pie chart
# YOUR CODE HERE!
df_savings.plot(kind="pie", subplots=True)
# Set ideal emergency fund
emergency_fund = monthly_income * 3

# Calculate total amount of savings
total_saving = total_crypto + total_share

# Validate saving health
if total_saving > emergency_fund:
    print("Congratulations! You have enough money in your emergency fund.")
elif total_saving == emergency_fund:
    print("Congratulations! You have reached this financial goal.")
else:
    print(f"You are ${emergency_fund - total_saving} away from reaching the financial 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-05-01', tz='Australia/Perth').isoformat()
end_date = pd.Timestamp('2021-06-18', tz='Australia/Perth').isoformat()
# Get 5 years' worth of historical data for SPY and AGG
# (use a limit=1000 parameter to call the most recent 1000 days of data)
stock_tickers = ["AGG", "SPY"]
df_stock_data = alpaca.get_barset(
    stock_tickers,
    timeframe,
    start=start_date,
    end=end_date,
    limit = 1000
).df
# Display sample data
df_stock_data.head()
# Configuring a Monte Carlo simulation to forecast 30 years cumulative returns

MC_thirtyyear = MCSimulation(
    portfolio_data = df_stock_data,
    weights = [.40,.60],
    num_simulation = 500,
    num_trading_days = 252*30
)

# Printing the simulation input data

MC_thirtyyear.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 30 years cumulative returns
MC_thirtyyear.calc_cumulative_return()
# Plot simulation outcomes

line_plot = MC_thirtyyear.plot_simulation()
line_plot.get_figure().savefig("MC_thirtyyear_sim_plot.png", bbox_inches="tight")
# Plot probability distribution and confidence intervals
dist_plot = MC_thirtyyear.plot_distribution()
dist_plot.get_figure().savefig("MC_probability_sim_plot.png", bbox_inches="tight")<jupyter_output><empty_output><jupyter_text>Retirement Analysis<jupyter_code># Fetch summary statistics from the Monte Carlo simulation results
tbl = MC_thirtyyear.summarize_cumulative_return()


# Print summary statistics
print(tbl)<jupyter_output>count           500.000000
mean             21.775489
std              16.405681
min               2.387748
25%              10.574968
50%              17.711738
75%              26.948578
max             111.724043
95% CI Lower      4.435807
95% CI Upper     64.955719
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(tbl[8]*initial_investment,2)
ci_upper = round(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 $88716.15 and $1299114.39<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 $30,000
ci_lower = round(tbl[8]*initial_investment,2)
ci_upper = round(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 $133074.22 and $1948671.58<jupyter_text>Optional Challenge - Early Retirement Five Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 5 years cumulative returns
MC_fiveyear = MCSimulation(
    portfolio_data = df_stock_data,
    weights = [.40,.60],
    num_simulation = 500,
    num_trading_days = 252*5
)
MC_fiveyear.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 5 years cumulative returns
MC_fiveyear.calc_cumulative_return()
# Plot simulation outcomes
line_plot_five = MC_fiveyear.plot_simulation()
line_plot_five.get_figure().savefig("MC_fiveyears_sim_plot.png", bbox_inches="tight")
# Plot probability distribution and confidence intervals
dist_plot_five = MC_fiveyear.plot_distribution()
dist_plot_five.get_figure().savefig("MC_fiveyears_probability_sim_plot.png", bbox_inches="tight")
# Fetch summary statistics from the Monte Carlo simulation results
tbl_five = MC_fiveyear.summarize_cumulative_return()


# Print summary statistics
print(tbl_five)
# Set initial investment
initial_investment = 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(tbl_five[8]*initial_investment,2)
ci_upper_five = round(tbl_five[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 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 $54494.49 and $167499.08<jupyter_text>Ten Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 10 years cumulative returns
MC_tenyear = MCSimulation(
    portfolio_data = df_stock_data,
    weights = [.40,.60],
    num_simulation = 500,
    num_trading_days = 252*10
)
MC_tenyear.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 10 years cumulative returns
MC_tenyear.calc_cumulative_return()
# Plot simulation outcomes
line_plot_ten = MC_tenyear.plot_simulation()
line_plot_ten.get_figure().savefig("MC_tenyears_sim_plot.png", bbox_inches="tight")
# Plot probability distribution and confidence intervals
dist_plot_ten = MC_tenyear.plot_distribution()
dist_plot_ten.get_figure().savefig("MC_tenyears_probability_sim_plot.png", bbox_inches="tight")
# Fetch summary statistics from the Monte Carlo simulation results
tbl_ten = MC_tenyear.summarize_cumulative_return()


# Print summary statistics
print(tbl_ten)
# Set initial investment
initial_investment = 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(tbl_ten[8]*initial_investment,2)
ci_upper_ten = round(tbl_ten[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 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 $67368.21 and $324481.27
{'fraction_non_alphanumeric': 0.08721843897328445, 'fraction_numerical': 0.03981141959140912, 'mean_word_length': 5.464446952595937, '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': '203603', 'license': 'ADSL', 'n_tokens_mistral': 4023, 'n_tokens_neox': 3650, 'n_words': 1160, 'path': 'Starter_Code/financial-planner.ipynb', 'repo_name': 'tiantran87/api-homework', 'size': '11454'}