<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
# YOUR CODE HERE! 
my_btc=1.2
my_eth=5.3
# Crypto API URLs
eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=CAD"
# Fetch current BTC price
# YOUR CODE HERE!
# Fetch current ETH price
# YOUR CODE HERE!
def get_crypto_price(ticker):
    url = f"https://api.alternative.me/v2/ticker/{ticker}/?convert=CAD"
    response=requests.get(url).content
    data=json.loads(response.decode('utf-8'))
    price=data['data'][next(iter(data['data']))]['quotes']['CAD']['price']
    return price
btc_price=get_crypto_price('Bitcoin')
eth_price=get_crypto_price('Ethereum')
print(btc_price,eth_price)


# Compute current value of my crpto
# YOUR CODE HERE!
my_btc_value=btc_price*my_btc
my_eth_value=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 $71952.73
The current value of your 5.3 ETH is $22595.68<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
# YOUR CODE HERE!
alpaca_api_key = os.getenv("ALPACA_API_KEY")
alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY")
# Create the Alpaca API object
# YOUR CODE HERE!
alpaca = tradeapi.REST(
    alpaca_api_key,
    alpaca_secret_key,
    api_version="v2")
# Format current date as ISO format
# YOUR CODE HERE!
today = pd.Timestamp("2022-03-25", tz="America/New_York").isoformat()
# Set the tickers
tickers = ["AGG", "SPY"]

# Set timeframe to "1Day" for Alpaca API
timeframe = "1Day"

# Get current closing prices for SPY and AGG
# YOUR CODE HERE!
# from alpaca_trade_api import TimeFrame
stock_price=alpaca.get_bars(tickers,timeframe,today,adjustment='raw').df
# Reorganize the DataFrame
# Separate ticker data
# YOUR CODE HERE!
SPY_price=stock_price.loc[stock_price['symbol']=='SPY']
AGG_price=stock_price.loc[stock_price['symbol']=='AGG']

# Concatenate the ticker DataFrames
# YOUR CODE HERE!
stock_price=pd.concat([SPY_price,AGG_price],axis=1,keys=['SPY','AGG'])
# Preview DataFrame
# YOUR CODE HERE!

stock_price.head()
# Pick AGG and SPY close prices
# YOUR CODE HERE!
# spy_close_price=list(stock_price['SPY']['close'])
spy_close_price=stock_price['SPY']['close'].iloc[0]
agg_close_price=stock_price['AGG']['close'].iloc[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
# YOUR CODE HERE!
my_spy_value=spy_close_price*my_spy
my_agg_value=agg_close_price*my_agg
# Print current value of shares
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 $22634.50
The current value of your 200 AGG shares is $21220.00<jupyter_text>Savings Health Analysis<jupyter_code># Set monthly household income
# YOUR CODE HERE!
monthly_income=12000
# Consolidate financial assets data
# YOUR CODE HERE!
# Create savings DataFrame
# YOUR CODE HERE!
df_savings=pd.DataFrame({
    'asset':  ['cypto','shares'],
    'amount': [my_btc_value+my_eth_value, my_spy_value+my_agg_value]
}).set_index('asset')

# Display savings DataFrame
display(df_savings)
# Plot savings pie chart
# YOUR CODE HERE!
df_savings.plot(kind='pie', y="amount")
# Set ideal emergency fund
emergency_fund = monthly_income * 3
# Calculate total amount of savings
# YOUR CODE HERE!
total_savings=my_spy_value+my_agg_value+my_btc_value+my_eth_value
# Validate saving health
# YOUR CODE HERE!
if total_savings > emergency_fund:
    print("Congratulations! You have enough money in your emergency fund.")
elif total_savings == emergency_fund:
    print("Congratulations! You are reaching your financial goal.")
elif total_savings < emergency_fund:
    print(f"You need to save addtional ${emergency_fund-total_savings:0.2f} to reach your 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='America/New_York').isoformat()
end_date = pd.Timestamp('2021-05-01', tz='America/New_York').isoformat()
# Get 5 years' worth of historical data for SPY and AGG
# YOUR CODE HERE!
df_stock_data=alpaca.get_bars(tickers,timeframe,start_date,end_date,adjustment='raw').df

# Reorganize the DataFrame
# Separate ticker data
# YOUR CODE HERE!
df_stock_data_spy=df_stock_data.loc[df_stock_data['symbol']=='SPY']
df_stock_data_spy.head()

df_stock_data_agg=df_stock_data.loc[df_stock_data['symbol']=='AGG']
df_stock_data_agg.head()

# Concatenate the ticker DataFrames
# YOUR CODE HERE!
df_stock_data=pd.concat([df_stock_data_spy,df_stock_data_agg],axis=1,keys=['SPY','AGG'])
# Display sample data
df_stock_data.head()
# Configuring a Monte Carlo simulation to forecast 30 years cumulative returns
# YOUR CODE HERE!

# from MCForecastTools import MCSimulation
MC_30year = MCSimulation(
    portfolio_data = df_stock_data,
    weights=[.60,.40],
    num_simulation=500,
    num_trading_days = 252*30
)
# Printing the simulation input data
# YOUR CODE HERE!
MC_30year.portfolio_data.head()
# Running a Monte Carlo simulation to forecast 30 years cumulative returns
# YOUR CODE HERE!
MC_30year.calc_cumulative_return()
# Plot simulation outcomes
# YOUR CODE HERE!
MC_30year.plot_simulation()
# Plot probability distribution and confidence intervals
# YOUR CODE HERE!
MC_30year.plot_distribution()<jupyter_output><empty_output><jupyter_text>Retirement Analysis<jupyter_code># Fetch summary statistics from the Monte Carlo simulation results
# YOUR CODE HERE!
MC_30year.summarize_cumulative_return()
# Print summary statistics
# YOUR CODE HERE!
print(MC_30year.summarize_cumulative_return())<jupyter_output>count           500.000000
mean             18.694662
std              13.077188
min               1.628830
25%               9.898250
50%              14.752955
75%              23.704385
max              88.231003
95% CI Lower      3.895188
95% CI Upper     51.278648
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
# YOUR CODE HERE!
ci_lower=initial_investment*MC_30year.summarize_cumulative_return()["95% CI Lower"]
ci_upper=initial_investment*MC_30year.summarize_cumulative_return()["95% CI Upper"]
# 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:.2f} and ${ci_upper:.2f}")<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 $77903.76 and $1025572.97<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
# YOUR CODE HERE!
ci_lower=initial_investment*MC_30year.summarize_cumulative_return()["95% CI Lower"]
ci_upper=initial_investment*MC_30year.summarize_cumulative_return()["95% CI Upper"]
# 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:.2f} and ${ci_upper:.2f}")<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 $116855.64 and $1538359.45<jupyter_text>Optional Challenge - Early Retirement Five Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 5 years cumulative returns
# YOUR CODE HERE!
MC_5year=MCSimulation(
    portfolio_data = df_stock_data,
    weights=[.80,.20],
    num_simulation=500,
    num_trading_days = 252*5
)
# Running a Monte Carlo simulation to forecast 5 years cumulative returns
# YOUR CODE HERE!
MC_5year.calc_cumulative_return()
# Plot simulation outcomes
# YOUR CODE HERE!
MC_5year.plot_simulation()
# Plot probability distribution and confidence intervals
# YOUR CODE HERE!
MC_5year.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
# YOUR CODE HERE!
print(MC_5year.summarize_cumulative_return())
# Print summary statistics
# YOUR CODE HERE!
# Set initial investment
# YOUR CODE HERE!
initial_investment = 20000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $30,000
# YOUR CODE HERE!
ci_lower_5=initial_investment*MC_5year.summarize_cumulative_return()["95% CI Lower"]
ci_upper_5=initial_investment*MC_5year.summarize_cumulative_return()["95% CI Upper"]

# 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_5} and ${ci_upper_5}")<jupyter_output>There is a 95% chance that an initial investment of $20000 in the portfolio over the next 5 years will end within in the range of $18590.776930441323 and $67547.76078500896<jupyter_text>Ten Years Retirement Option<jupyter_code># Configuring a Monte Carlo simulation to forecast 10 years cumulative returns
# YOUR CODE HERE!
MC_10year = MCSimulation(
    portfolio_data = df_stock_data,
    weights=[.80,.20],
    num_simulation=500,
    num_trading_days = 252*10
)
# Running a Monte Carlo simulation to forecast 10 years cumulative returns
# YOUR CODE HERE!
MC_10year.calc_cumulative_return()
# Plot simulation outcomes
# YOUR CODE HERE!
MC_10year.plot_simulation()
# Plot probability distribution and confidence intervals
# YOUR CODE HERE!
MC_10year.plot_distribution()
# Fetch summary statistics from the Monte Carlo simulation results
# YOUR CODE HERE!
MC_10year.summarize_cumulative_return()
# Print summary statistics
print(MC_10year.summarize_cumulative_return())
# YOUR CODE HERE!
# Set initial investment
# YOUR CODE HERE!

initial_investment = 20000

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $30,000
# YOUR CODE HERE!
ci_lower_10=initial_investment*MC_10year.summarize_cumulative_return()["95% CI Lower"]
ci_upper_10=initial_investment*MC_10year.summarize_cumulative_return()["95% CI Upper"]

# 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_10} and ${ci_upper_10}")<jupyter_output>There is a 95% chance that an initial investment of $20000 in the portfolio over the next 10 years will end within in the range of $23236.855139878717 and $170269.06511171832
{'fraction_non_alphanumeric': 0.09071923815888397, 'fraction_numerical': 0.044106590928076186, 'mean_word_length': 5.737197523916714, 'pattern_counts': {'":': 0, '<': 34, '<?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': '207696', 'license': 'ADSL', 'n_tokens_mistral': 4345, 'n_tokens_neox': 3837, 'n_words': 1212, 'path': 'financial-planner.ipynb', 'repo_name': 'Fayee0103/financial-planning-tool', 'size': '11971'}