<jupyter_start><jupyter_text>Financial Planning with APIs and Simulations<jupyter_code># Import the required libraries and dependencies
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 the environment variables from the .env file by calling the load_dotenv function
load_dotenv()<jupyter_output><empty_output><jupyter_text>Create a Financial Planner for Emergencies<jupyter_code># The current number of coins for each cryptocurrency asset held in the portfolio.
btc_coins = 1.2
eth_coins = 5.3
# The monthly amount for the member's household income
monthly_income = 12000
# The Free Crypto API Call endpoint URLs for the held cryptocurrency assets
btc_url = "https://api.alternative.me/v2/ticker/Bitcoin/?convert=USD"
eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=USD"
# Using the Python requests library, make an API call to access the current price of BTC
btc_response = requests.get(btc_url).json()

# Use the json.dumps function to review the response data from the API call
# Use the indent and sort_keys parameters to make the response object readable
print(json.dumps(btc_response, indent=4, sort_keys=True))
# Using the Python requests library, make an API call to access the current price ETH
eth_response = requests.get(eth_url).json()

# Use the json.dumps function to review the response data from the API call
# Use the indent and sort_keys parameters to make the response object readable
print(json.dumps(eth_response, indent=4, sort_keys=True))

# Navigate the BTC response object to access the current price of BTC
btc_price = btc_response['data']['1']['quotes']['USD']['price']

# Print the current price of BTC
print(f'The current price of BitCoin to USD is ${btc_price:,.2f}.')
# Navigate the BTC response object to access the current price of ETH
eth_price = eth_response['data']['1027']['quotes']['USD']['price']

# Print the current price of ETH
print(f'The current price ofof Etherum to USD is ${eth_price:,.2f}.')

# Compute the current value of the BTC holding 
btc_value = btc_coins * btc_price

# Print current value of your holding in BTC
print(f'The current value of your BitCoin(BTC) is ${btc_value:,.2f}.')

# Compute the current value of the ETH holding 
eth_value = eth_coins * eth_price

# Print current value of your holding in ETH
print(f'The current value of your Etherum(ETH) is ${eth_value:,.2f}.')
# Compute the total value of the cryptocurrency wallet
# Add the value of the BTC holding to the value of the ETH holding
total_crypto_wallet = eth_value + btc_value

# Print current cryptocurrency wallet balance
print(f'The total value of your cryptocurrency wallet is ${total_crypto_wallet:,.2f}.')<jupyter_output>The total value of your cryptocurrency wallet is $95,403.10.<jupyter_text>Evaluate the Stock and Bond Holdings by Using the Alpaca SDK<jupyter_code># Current amount of shares held in both the stock (SPY) and bond (AGG) portion of the portfolio.
spy_shares = 110
agg_shares = 200

# Set the variables for the Alpaca API and secret keys
alpaca_api_key = os.getenv("ALPACA_API_KEY")
alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY")

# Create the Alpaca tradeapi.REST object
alpaca = tradeapi.REST(alpaca_api_key, alpaca_secret_key, api_version='v2')
# Set the tickers for both the bond and stock portion of the portfolio
tickers = ['AGG', 'SPY']

# Set timeframe to 1D 
timeframe = '1D'

# Create function to make sure to get last 7 days trading prices accounting for beginning of month/year and holidays
def sub_day(date,day):
    if date.day- day < 1:
        month = date.month -1 
        p_day = 30 + (date.day- day)
        if month <1:
            year = date.year -1
            month = 12
            date = f'{year}-{month}-{p_day}'
        else:
            date = f'{date.year}-{month}-{p_day}'
    else:
        p_day = date.day- day
        date=f'{date.year}-{date.month}-{p_day}'
        return date
    
# Format current date as ISO format
# Set both the start and end date at the date of your prior weekday 
# This will give you the closing price of the previous trading day
date = pd.Timestamp('today')        
start_date = pd.Timestamp(sub_day(date,7), tz='America/New_York').isoformat()
end_date = pd.Timestamp(date, tz='America/New_York').isoformat()

date = pd.Timestamp('today')
date
# Use the Alpaca get_barset function to get current closing prices the portfolio
# Be sure to set the `df` property after the function to format the response object as a DataFrame
port_ticker_df = alpaca.get_barset(tickers, timeframe, start=start_date, end=end_date).df

# Review the first 5 rows of the Alpaca DataFrame
port_ticker_df.head()
# Access the closing price for AGG from the Alpaca DataFrame
# Converting the value to a floating point number
agg_close_price = float(port_ticker_df['AGG']['close'][-1])

# Print the AGG closing price
print(f'The lastest AGG closing price is ${agg_close_price:,.2f}.')
# Access the closing price for SPY from the Alpaca DataFrame
# Converting the value to a floating point number
spy_close_price = float(port_ticker_df['SPY']['close'][-1])

# Print the SPY closing price
print(f'The lastest SPY closing price is ${spy_close_price:,.2f}.')

# Calculate the current value of the bond portion of the portfolio
agg_value = agg_close_price * agg_shares

# Print the current value of the bond portfolio
print(f'The current value of your AGG stocks is ${agg_value:,.2f}.')

# Calculate the current value of the stock portion of the portfolio
spy_value = spy_close_price * spy_shares

# Print the current value of the stock portfolio
print(f'The current value of your SPY stocks is ${spy_value:,.2f}.')

# Calculate the total value of the stock and bond portion of the portfolio
total_stocks_bonds = agg_value + spy_value

# Print the current balance of the stock and bond portion of the portfolio
print(f'The total value of your stock/bond porfolio is ${total_stocks_bonds:,.2f}.')

# Calculate the total value of the member's entire savings portfolio
# Add the value of the cryptocurrency walled to the value of the total stocks and bonds
total_portfolio = total_crypto_wallet + total_stocks_bonds

# Print current cryptocurrency wallet balance
print(f'The total portfolio value is ${total_portfolio:,.2f}.')<jupyter_output>The total portfolio value is $168,433.80.<jupyter_text>Evaluate Emergency Fund<jupyter_code># Consolidate financial assets data into a Python list
savings_data = [total_crypto_wallet, total_stocks_bonds]
# Review the Python list savings_data
print(savings_data)
    
# Create a Pandas DataFrame called savings_df 
savings_df = pd.DataFrame(savings_data , index=['crypto', 'stock/bond'], columns=['amount'])

# Display the savings_df DataFrame
savings_df.head()

# Plot the total value of the member's portfolio (crypto and stock/bond) in a pie chart
savings_df.plot.pie(y='amount', title='Total Value of Portfolio', figsize=(14,7), ylabel='Amount')

# Create a variable named emergency_fund_value
emergency_fund_value = 3* monthly_income

# Evaluate the possibility of creating an emergency fund with 3 conditions:
if total_portfolio > emergency_fund_value:
     print(f'Congratulations on exceeding your financial goal!')
elif total_portfolio == emergency_fund_value:
    print(f'Congratulations on reaching this important financial goal!')
else:
    print(f'You are still ${emergency_fund_value-total_portfolio:,.2f} away from your emergency_fund_value of ${emergency_fund_value:,.2f}.')<jupyter_output>Congratulations on exceeding your financial goal!<jupyter_text>Part 2: Create a Financial Planner for Retirement<jupyter_code># Set start and end dates of 3 years back from your current date 
start_date = pd.Timestamp(year=date.year-3, month=date.month, day=date.day, tz='America/New_York').isoformat()
end_date = pd.Timestamp(date, tz='America/New_York').isoformat()

# Set number of rows to 1000 to retrieve the maximum amount of rows
row_limit = 1000
# Use the Alpaca get_barset function to make the API call to get the 3 years worth of pricing data
# The tickers and timeframe parameters should have been set in Part 1 of this activity 
# The start and end dates should be updated with the information set above
# Remember to add the df property to the end of the call so the response is returned as a DataFrame
portfolio_df = alpaca.get_barset(tickers, timeframe, start=start_date, end=end_date, limit=row_limit).df


# Display both the first and last five rows of the DataFrame
display(portfolio_df.head())
display(portfolio_df.tail())


# Configure the Monte Carlo simulation to forecast 30 years cumulative returns
# The weights should be split 40% to AGG and 60% to SPY.
# Run 500 samples.
portf_mc_30y = MCSimulation(portfolio_data = portfolio_df, weights = [.40,.60], num_simulation = 500, num_trading_days = 252*30)

# Review the simulation input data
portf_mc_30y.portfolio_data.head()

# Run the Monte Carlo simulation to forecast 30 years cumulative returns
portf_mc_30y.calc_cumulative_return()
# Visualize the 30-year Monte Carlo simulation by creating an
# overlay line plot
portf_mc_30y.plot_simulation()
# Visualize the probability distribution of the 30-year Monte Carlo simulation 
# by plotting a histogram
portf_mc_30y.plot_distribution()

# Generate summary statistics from the 30-year Monte Carlo simulation results
# Save the results as a variable
portf_mc30y_summary = portf_mc_30y.summarize_cumulative_return()


# Review the 30-year Monte Carlo summary statistics
print(portf_mc30y_summary)<jupyter_output>count           500.000000
mean             56.740676
std              48.037484
min               5.829181
25%              25.872525
50%              44.015857
75%              71.269509
max             326.389560
95% CI Lower     10.268232
95% CI Upper    178.603346
Name: 7560, dtype: float64<jupyter_text>Analyze the Retirement Portfolio ForecastsUsing the current value of only the stock and bond portion of the member's portfolio and the summary statistics that you generated from the Monte Carlo simulation, answer the following question:-  What are the lower and upper bounds for the expected value of the portfolio with a 95% confidence interval?<jupyter_code># Print the current balance of the stock and bond portion of the members portfolio
def print_currbal_sb(total_stocks_bonds, agg_value, spy_value):
    print(f'Current Balance of Stock and Bond Portion: ${total_stocks_bonds:,.2f}. The value of AGG ${agg_value:,.2f} and the value of SPY ${spy_value:,.2f}.')

print_currbal_sb(total_stocks_bonds,agg_value,spy_value)
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio
ci_lower_thirty_cumulative_return = portf_mc30y_summary[8] * total_stocks_bonds
ci_upper_thirty_cumulative_return = portf_mc30y_summary[9] * total_stocks_bonds


# Print the result of your calculations
def print_ci_interval(ci_lower_cumulative_return, ci_upper_cumulative_return):
    print(f'The lower 95% confidence interval is ${ci_lower_cumulative_return:,.2f} and the upper 95% confidence interval is ${ci_upper_cumulative_return:,.2f}.')
print_ci_interval(ci_lower_thirty_cumulative_return, ci_upper_thirty_cumulative_return)<jupyter_output>The lower 95% confidence interval is $749,896.20 and the upper 95% confidence interval is $13,043,527.38.<jupyter_text>Forecast Cumulative Returns in 10 Years- Based on the new Monte Carlo simulation, answer the following questions:    - Using the current value of only the stock and bond portion of the member's portfolio and the summary statistics that you generated from the new Monte Carlo simulation, what are the lower and upper bounds for the expected value of the portfolio (with the new weights) with a 95% confidence interval?    - Will weighting the portfolio more heavily toward stocks allow the credit union members to retire after only 10 years?<jupyter_code># Configure a Monte Carlo simulation to forecast 10 years cumulative returns
# The weights should be split 20% to AGG and 80% to SPY.
# Run 500 samples.
portf_mc_10y = MCSimulation(portfolio_data = portfolio_df, weights = [.20,.80], num_simulation=500, num_trading_days = 252*10)

# Review the simulation input data
portf_mc_10y.portfolio_data.head()

# Run the Monte Carlo simulation to forecast 10 years cumulative returns
portf_mc_10y.calc_cumulative_return()

# Visualize the 10-year Monte Carlo simulation by creating an overlay line plot
portf_mc_10y.plot_simulation()
# Visualize the probability distribution of the 10-year Monte Carlo simulation by plotting a histogram
portf_mc_10y.plot_distribution()
# Generate summary statistics from the 10-year Monte Carlo simulation results
# Save the results as a variable
portf_mc10y_summary = portf_mc_10y.summarize_cumulative_return()


# Review the 10-year Monte Carlo summary statistics
print(portf_mc10y_summary)<jupyter_output>count           500.000000
mean              5.622375
std               3.793096
min               0.844054
25%               3.047923
50%               4.497523
75%               6.937020
max              29.417940
95% CI Lower      1.635658
95% CI Upper     15.979578
Name: 2520, dtype: float64<jupyter_text>Answer the following questions:  Question: Using the current value of only the stock and bond portion of the member's portfolio and the summary statistics that you generated from the new Monte Carlo simulation, what are the lower and upper bounds for the expected value of the portfolio (with the new weights) with a 95% confidence interval?<jupyter_code># Print the current balance of the stock and bond portion of the members portfolio
print_currbal_sb(total_stocks_bonds,agg_value,spy_value)

# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio
ci_lower_ten_cumulative_return = portf_mc10y_summary[8] * total_stocks_bonds
ci_upper_ten_cumulative_return = portf_mc10y_summary[9] * total_stocks_bonds

# Print the result of your calculations
print_ci_interval(ci_lower_ten_cumulative_return, ci_upper_ten_cumulative_return)<jupyter_output>The lower 95% confidence interval is $119,453.24 and the upper 95% confidence interval is $1,166,999.73.<jupyter_text>Question: Will weighting the portfolio more heavily to stocks allow the credit union members to retire after only 10 years?<jupyter_code>**Answer** The lower 95% confidence interval shows a 60% gain and the upper 95% confidence interval shows a 1356% gain. Depending on how much they are trying to retire with, how heavily they invest, and how they weigh their portfolio it is possible for them to be able to retire in 10 years time.<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0691586262735308, 'fraction_numerical': 0.031037042034950408, 'mean_word_length': 4.921693967239313, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 31, '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': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '579651', 'license': 'MIT', 'n_tokens_mistral': 4738, 'n_tokens_neox': 4297, 'n_words': 1715, 'path': 'financial_planning_tools.ipynb', 'repo_name': 'Deep4Patel9/fintech_budget_retirement_plans', 'size': '14821'}