<jupyter_start><jupyter_text>Unit 5 - Financial Planning<jupyter_code># Initial imports
import os
import requests
import json
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
btc_amount = 1.2
eth_amount = 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).json()
print(json.dumps(btc_response_data, indent=4))

# Fetch current ETH price
eth_response_data = requests.get(eth_url).json()
print(json.dumps(eth_response_data, indent=4))

# Compute current value of my crpto
btc_price = btc_response_data['data']['1']['quotes']['USD']['price']
btc_value = btc_amount * btc_price

eth_price = eth_response_data['data']['1027']['quotes']['USD']['price']
eth_value = eth_amount * eth_price

# Print current crypto wallet balance
print(f"The current value of your {btc_amount} BTC is ${btc_value:0.2f}")
print(f"The current value of your {eth_amount} ETH is ${eth_value:0.2f}")<jupyter_output>{
    "data": {
        "1": {
            "id": 1,
            "name": "Bitcoin",
            "symbol": "BTC",
            "website_slug": "bitcoin",
            "rank": 1,
            "circulating_supply": 18741143,
            "total_supply": 18741143,
            "max_supply": 21000000,
            "quotes": {
                "USD": {
                    "price": 33934.0,
                    "volume_24h": 60337557466,
                    "market_cap": 636584615009,
                    "percentage_change_1h": -1.06484300240482,
                    "percentage_change_24h": 7.80820269120387,
                    "percentage_change_7d": -15.9586660919359,
                    "percent_change_1h": -1.06484300240482,
                    "percent_change_24h": 7.80820269120387,
                    "percent_change_7d": -15.9586660919359
                },
                "CAD": {
                    "price": 41667.5586,
                    "volume_24h": 74088486812.5014,
                    "[...]<jupyter_text>Collect Investments Data Using Alpaca: `SPY` (stocks) and `AGG` (bonds)<jupyter_code># Current amount of shares
agg_shares = 200
spy_shares = 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
api = tradeapi.REST(
    alpaca_api_key,
    alpaca_secret_key,
    api_version = "v2"
)
# Format current date as ISO format
current_date = pd.Timestamp("2021-6-17", 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
prices = api.get_barset(
    tickers, 
    timeframe, 
    start=current_date, 
    end=current_date
).df

# Preview DataFrame
prices.head()
# Pick AGG and SPY close prices
agg_price = float(prices["AGG"]["close"])
spy_price = float(prices["SPY"]["close"])

# Print AGG and SPY close prices
print(f"Current AGG closing price: ${agg_price}")
print(f"Current SPY closing price: ${spy_price}")
# Compute the current value of shares
agg_value = agg_shares * agg_price 
spy_value = spy_shares * spy_price 

# Print the current value of the stocks portfolio
print(f"The current value of your {agg_shares} AGG shares is ${agg_value:0.2f}")
print(f"The current value of your {spy_shares} SPY shares is ${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
monthly_income = 12000

# Set total investments value
total_crypto = round(btc_value + eth_value, 2)
total_stocks = round(agg_value + spy_value, 2)
investment_data = {'value': [total_crypto, total_stocks]}

# Create savings DataFrame
savings_df = pd.DataFrame(investment_data, index = ['crypto', 'shares'])

# Display savings DataFrame
display(savings_df)
# Plot savings pie chart
savings_df.plot.pie(y='value', title='Composition of Personal Savings')
# Set ideal emergency fund
emergency_fund = monthly_income * 3

# Calculate total amount of savings
total_savings = total_crypto + total_stocks
emergency_fund_difference = emergency_fund - total_savings

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

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

# Print summary statistics
print(summary_statistics)<jupyter_output>count           500.000000
mean             46.855548
std              20.684165
min              12.199538
25%              32.150397
50%              43.906238
75%              57.990781
max             127.993903
95% CI Lower     17.004865
95% CI Upper     95.407295
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_statistics[8]*20000, 2)
ci_upper= round(summary_statistics[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 $340097.29 and $1908145.89.<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_statistics[8]*30000, 2)
ci_upper= round(summary_statistics[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 $510145.94 and $2862218.84.
{'fraction_non_alphanumeric': 0.09425149700598802, 'fraction_numerical': 0.06047904191616767, 'mean_word_length': 4.079683698296837, 'pattern_counts': {'":': 24, '<': 28, '<?xml version=': 0, '>': 27, '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': '68858', 'license': 'ADSL', 'n_tokens_mistral': 3022, 'n_tokens_neox': 2637, 'n_words': 807, 'path': 'financial-planner.ipynb', 'repo_name': 'nmd55/api_homework', 'size': '8350'}