<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
from alpaca_trade_api.rest import REST, TimeFrame
from IPython.display import display
%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_price = requests.get(btc_url).json()
btc_price = btc_price['data']['1']['quotes']['USD']['price']

# Fetch current ETH price
eth_price = requests.get(eth_url).json()
eth_price = eth_price['data']['1027']['quotes']['USD']['price']

# Compute current value of my crpto
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 $49642.80
The current value of your 5.3 ETH is $15471.71<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("APCA_API_KEY_ID")
alpaca_secret_key = os.getenv("APCA_API_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('2022-03-21', tz='America/New_York').isoformat()

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




# Get current closing prices for SPY and AGG
# (use a limit=1000 parameter to call the most recent 1000 days of data)
df_ticker = api.get_bars(tickers, 
TimeFrame.Day, 
start= today, end=today, limit=1000).df
df_ticker.index = df_ticker.index.date
# Preview DataFrame
df_ticker
#turn table into pivot table 
closes = df_ticker.pivot_table(values="close", index="timestamp", columns="symbol")
closes.head()
# Pick AGG and SPY close prices
agg_close_price = df_ticker.iloc[0,3]
spy_close_price = df_ticker.iloc[1,3]
# 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_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 $22219.50
The current value of your 200 AGG shares is $21408.00<jupyter_text>Savings Health Analysis<jupyter_code># Set monthly household income
monthly_income = 12000 

# Consolidate financial assets data
crypto_sum = my_btc_value + my_eth_value 
shares_sum = my_spy_value + my_agg_value


# Create savings DataFrame
df_savings = pd.DataFrame([crypto_sum, shares_sum], 
columns=['amount'], 
index=['crypto','shares'])

# Display savings DataFrame
display(df_savings)
# Plot savings pie chart
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 = df_savings['amount'].sum()

# Validate saving health
if total_savings > emergency_fund:
    print('Congratulations! You have enough money in your emergency fund.')
elif total_savings == emergency_fund:
    print('Congratulations! You have reached your financial goal.')
else:
    print('Sorry! You have not reached your 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 AGG
# (use a limit=1000 parameter to call the most recent 1000 days of data)
tickers = ["AGG"]
df_agg_data = api.get_bars(tickers,
TimeFrame.Day,
start=start_date,
end=end_date, limit=1000).df
df_agg_data.index = df_agg_data.index.date
df_agg_data = df_agg_data.reset_index()
# Display sample data
#turn table into pivot table 
df_agg_data = df_agg_data.pivot_table(values="close", index='index', columns="symbol")
df_agg_data.head()
# Get 5 years' worth of historical data for SPY 
# (use a limit=1000 parameter to call the most recent 1000 days of data)
tickers = ["SPY"]
df_spy_data = api.get_bars(tickers,
TimeFrame.Day,
start=start_date,
end=end_date, limit=1000).df
df_spy_data.index = df_spy_data.index.date
df_spy_data = df_spy_data.reset_index()
# Display sample data
df_spy_data = df_spy_data.pivot_table(values="close", index='index', columns="symbol")
df_spy_data.head()
tradeapi = REST()
def get_company(ticker, start, end, tradeapi):
    return tradeapi.get_bars(
        ticker,
        TimeFrame.Day,
        start,
        end
    ).df
my_df = {
    "AGG":get_company("AGG", "2017-03-17", "2022-03-18", api),
    "SPY":get_company("SPY", "2017-03-17", "2022-03-18", api)
}
#Concat the two data sets
combined_stocks = pd.concat(my_df.values(), keys= my_df.keys(), axis='columns' )
combined_stocks
# Configuring a Monte Carlo simulation to forecast 30 years cumulative returns
thirty_years = MCSimulation(portfolio_data= combined_stocks,
weights=[.50, .50],
num_simulation= 1000,
num_trading_days= 252*30
)
# Printing the simulation input data
thirty_years
# Running a Monte Carlo simulation to forecast 30 years cumulative returns
thirty_years.calc_cumulative_return()
# Plot simulation outcomes
line_plot = thirty_years.plot_simulation()
# Plot probability distribution and confidence intervals
dist_plot = thirty_years.plot_distribution()<jupyter_output><empty_output><jupyter_text>Retirement Analysis<jupyter_code># Fetch summary statistics from the Monte Carlo simulation results
summary_stats = thirty_years.summarize_cumulative_return()

# Print summary statistics
print(summary_stats)<jupyter_output>count           1000.000000
mean               8.748873
std                4.644179
min                1.799858
25%                5.541962
50%                7.688277
75%               11.007671
max               32.753957
95% CI Lower       2.828521
95% CI Upper      21.397630
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]*20000*2)
ci_upper = round(summary_stats[9]*20000*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 $113141 and $855905<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(summary_stats[8]*30000*2)
ci_upper = round(summary_stats[9]*30000*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 $169711 and $1283858
{'fraction_non_alphanumeric': 0.0959016393442623, 'fraction_numerical': 0.04625292740046839, 'mean_word_length': 5.234306569343065, 'pattern_counts': {'":': 2, '<': 27, '<?xml version=': 0, '>': 28, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '138310', 'license': 'ADSL', 'n_tokens_mistral': 3104, 'n_tokens_neox': 2788, 'n_words': 881, 'path': '05-APIs/Instructions/Starter_Code/financial-planner.ipynb', 'repo_name': 'kxh3/api-homework05', 'size': '8540'}