<jupyter_start><jupyter_text>Golden Years Retirement PlannerAmericans struggle to save enough money to live comfortably during retirement. Recent market data and analysis of surveys gauging retirement confidence have shown that Americans need to save more. In order to help Americans save more and make better financial decisions, our product aims to analyze the amount it takes to retire comfortably, make suggestions on where to invest, and forecast savings over time.<jupyter_code>#Import libraries and dependances
import csv
from pathlib import Path
import sys
import os
import requests
import json
import pandas as pd
import hvplot.pandas
import plotly.express as px
import alpaca_trade_api as tradeapi

from datetime import datetime
from dotenv import load_dotenv
from MCForecastTools import MCSimulation
%matplotlib inline

from data.retire import retirement_plan
from data.comfort import comfort_buffer
from data.americanstates import fifty_states<jupyter_output><empty_output><jupyter_text>Part 1: Analysis of Current Retirement Trends in the USA**Completed By: <NAME>**<jupyter_code>#Data was obtained from Retirement Confidence Survey by <NAME> and was used to create a dataframe
#The CSV file is us_retiree_basic_expenses_covered_confidence.csv file and index was set to confidence_rating

retiree_confidence_df = pd.read_csv(
    Path("./Resources/us_retiree_basic_expenses_covered_confidence.csv",
         index_col="confidence_rating"))
retiree_confidence_df.set_index("confidence_rating", inplace=True)
retiree_confidence_df["percentage"] = (retiree_confidence_df['outcome'] / 
                  retiree_confidence_df['outcome'].sum()) * 100
display(retiree_confidence_df)
#bar graph
retiree_confidence_df.hvplot.bar(figsize=(20,14), x='confidence_rating',
    y='outcome', title='Retirement Confidence Rating (USA)')<jupyter_output><empty_output><jupyter_text>AnalysisData gathered from a Retirement Confidence Survey by <NAME> indicates that Americans’ confidence in their ability to live comfortably in retirement remains high overall. This data shows that over 62% of Americans' are either **Very Confident** or **Somewhat Confident** that they will have enough money for a comfortable retirement. However, this still leaves over 37% of either **Not Too Confident** or **Not Confident At All** Americans' that feel they will not be able to have enough money to retire comfortably. While the majority of Americans' on the T. Rowe Price Retirement Confidence Survey feel they are on track for a comfortable retirement, Golden Years plans to put this to the test.  1.1: How Are Americans' Saving For Retirement?Loading Popular Retirement Accounts in the USA from popular_retirement_accounts_usa_survey.csv file, setting index to account_responses, and displaying DataFrame.<jupyter_code>#Converting CSV information into dataframe
popular_retirement_accounts_usa_survey_df = pd.read_csv(
    Path("./Resources/popular_retirement_accounts_usa_survey.csv",
    index_col="account_responses"))
popular_retirement_accounts_usa_survey_df.set_index("account_responses", inplace=True)
popular_retirement_accounts_usa_survey_df["percentage"] = (popular_retirement_accounts_usa_survey_df['amount'] / 
                  popular_retirement_accounts_usa_survey_df['amount'].sum()) * 100
display(popular_retirement_accounts_usa_survey_df)
#A pie chart showing popular retirement accounts in USA

explode = (0.06, 0, 0, 0, 0, 0, 0, 0)
popular_retirement_accounts_usa_survey_df.plot.pie(figsize=(20,16),
    y='percentage',
    autopct='%1.1f%%',
    explode=explode,
    #hoverinfo='account_response+amount',
    #legend = 'Accounts',
    title='Popular Retirement Accounts (USA)')<jupyter_output><empty_output><jupyter_text>1.2 Analysis of Comfortable Retirement in the USA using MAPBOX<jupyter_code>#Loading `.env` file to Read MapBox API Key and Printing type to confirm API access.
load_dotenv()

# Reading in the MAPBOX_API_KEY.
mapbox_api_access_token = os.getenv("MAPBOX_API_ACCESS_TOKEN")
# Confirming the availability of the Mapbox API access token by checking its type.
print(type(mapbox_api_access_token))

# Setting Mapbox API access token.
px.set_mapbox_access_token(mapbox_api_access_token)
#State Coordinates Data from coordinates.csv file 
#using .head() and .tail() functions to display First and Last Five rows of DataFrame. 
#Loading state coordinates data.
state_coordinates_df = pd.read_csv(Path("./Resources/coordinates.csv", index_col="States"))
state_coordinates_df.set_index('States', inplace=True)

# Reviewing the DataFrame.
display(state_coordinates_df.head())
display(state_coordinates_df.tail())
#Loading US Retirement Data from us_retirement_data.csv file 
#using .head() and .tail() functions to display First and Last Five rows of DataFrame. 
#Using the read_csv function, Path module, and creating a DataFrame 
# by importing the us_retirement_data.csv file from the Resources folder.
us_retirement_data_df = pd.read_csv(Path("./Resources/us_retirement_data.csv"))

# Reviewing the first and last five rows of the DataFrame.
display(us_retirement_data_df.head())
display(us_retirement_data_df.tail())
#Grouping data.
retirement_by_state = us_retirement_data_df.groupby(["States"])[["cost_of_living","comfort_buffer","comfortable_retirement"]].mean()


# Reviewing the DataFrame.
retirement_by_state.head()
# Using the Pandas `concat` function to join the 
# state_coordinates_df and retirement_by_state DataFrames
# The axis of the concatenation is "columns".
# The concat function will automatially combine columns with
# identical information, while keeping the additional columns.
all_states_retirement_df = pd.concat(
    [state_coordinates_df, retirement_by_state], 
    axis="columns",
    sort=False
)

# Reviewing the resulting DataFrame.
display(all_states_retirement_df.head())
display(all_states_retirement_df.tail())
# Creating a scatter mapbox to analyze retirement info of all states.
mapbox = px.scatter_mapbox(
    all_states_retirement_df,
    lat="Lat",
    lon="Lon",
    size="cost_of_living",
    color="comfortable_retirement",
    size_max=15,
    zoom=1.65
)
mapbox<jupyter_output><empty_output><jupyter_text>Part 2: User Input***Completed by <NAME>***User inputs information regarding the state they want to live in and their investment choices. Please run this portion from user_input.py.   Part 3: Financial Forecast and Simulations***Completed by <NAME>***Analysis of stocks and crypto currency based on the amount the user can save.<jupyter_code># Load the environment variables from the .env file
#by calling the load_dotenv function
load_dotenv()<jupyter_output><empty_output><jupyter_text>Cryptocurrency Analysis Review the endpoint URLs for the API calls to Free Crypto API in order to get the current pricing information for both BTC and ETH.<jupyter_code># 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"<jupyter_output><empty_output><jupyter_text>Use the Requests library to get the current price (in US dollars) of Bitcoin (BTC) and Ethereum (ETH) by using the API endpoints that the starter code supplied.<jupyter_code># 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))<jupyter_output>{
    "data": {
        "1027": {
            "circulating_supply": 117208141,
            "id": 1027,
            "last_updated": 1629626371,
            "max_supply": 0,
            "name": "Ethereum",
            "quotes": {
                "USD": {
                    "market_cap": 382835869228,
                    "percent_change_1h": 0.477871248339957,
                    "percent_change_24h": -0.37915803634404,
                    "percent_change_7d": 0.0144878491381817,
                    "percentage_change_1h": 0.477871248339957,
                    "percentage_change_24h": -0.37915803634404,
                    "percentage_change_7d": 0.0144878491381817,
                    "price": 3269.02,
                    "volume_24h": 17665084256
                }
            },
            "rank": 2,
            "symbol": "ETH",
            "total_supply": 117208141,
            "website_slug": "ethereum"
        }
    },
    "metadata": {
        "error": null,
        "num_cryptocu[...]<jupyter_text>Navigate the JSON response object to access the current price of each coin, and store each in a variable.<jupyter_code>#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 price for Bitcoin 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 price for Ethereum is ${eth_price:,.2f}")<jupyter_output>The price for Ethereum is $3,269.02<jupyter_text>Calculate the amount of coins the retiree can afford to purchase.   Take amount able to invest divide by 2, equals "half the amount". Take "half the amount" divide by BTC price equals the amount of BTC to purchase. Take "half the amount" divide by ETH price equals the amount of ETH to purchase.<jupyter_code>#user input savings amount and press enter
savings_amount= int(input("Enter savings account information:"))
#buying both bitcoin and etherum
half_savings = savings_amount / 2
btc_coins = half_savings / btc_price
eth_coins = half_savings / eth_price
# Print current holding in BTC
#since savings is low, threshold 1000
print(f"You now are holding {btc_coins} Bitcoin")
# Print current holding in ETH
#based on savings 
print(f"The now are holding {eth_coins} Ethereum")
# Read in the CSV file called "Bitcoin Historical Data.csv" using the Path module. 
# The CSV file is located in the Resources folder.
# Set the index to the column "Date"
# Set the parse_dates and infer_datetime_format parameters
btc_df = pd.read_csv(
    Path('./Resources/Bitcoin Historical Data.csv'), 
    index_col="Date", parse_dates=True, infer_datetime_format=True)
btc_df.loc[:,"Price"]=btc_df.loc[:,"Price"].str.replace(",","")
btc_df.loc[:,"Price"]=btc_df.loc[:,"Price"].astype("float")

btc_df.loc[:,"Open"]=btc_df.loc[:,"Open"].str.replace(",","")
btc_df.loc[:,"Open"]=btc_df.loc[:,"Open"].astype("float")

btc_df.loc[:,"High"]=btc_df.loc[:,"High"].str.replace(",","")
btc_df.loc[:,"High"]=btc_df.loc[:,"High"].astype("float")

btc_df.loc[:,"Low"]=btc_df.loc[:,"Low"].str.replace(",","")
btc_df.loc[:,"Low"]=btc_df.loc[:,"Low"].astype("float")

btc_df = btc_df.drop(columns=["Change %"])
# This function converts the string values into a floating point number
def clean_currency(price_string):
    price = price_string
    if type(price_string) == str:
        price_string = price_string.replace('$', '')
        price_string = price_string.replace('-', '0')
        if price_string[-1] == 'K':
            thousand = 1000
            price_string = price_string.replace('K', '')
            price = float(price_string)
            price = price * thousand
        elif price_string[-1] == 'M':
            million = 1000000
            price_string = price_string.replace('M', '')
            price = float(price_string)
            price = price * million
        else:
            billion = 1000000000
            price_string = price_string.replace('B', '')
            price = float(price_string)
            price = price * billion
    return price
btc_df['Vol.'] = btc_df['Vol.'].apply(clean_currency)
list(btc_df.columns)
btc_df2 = btc_df[['Open', 'High', 'Low', 'Price', 'Vol.']]
columns = ["open", "high"," low", "close", "volume"]
btc_df2.columns = columns
btc_df2.keys()
# Read in the CSV file called "Bitcoin Historical Data.csv" using the Path module. 
# The CSV file is located in the Resources folder.
# Set the index to the column "Date"
# Set the parse_dates and infer_datetime_format parameters
eth_df = pd.read_csv(
    Path('./Resources/Ethereum Historical Data.csv'), 
    index_col="Date", parse_dates=True, infer_datetime_format=True)
eth_df = eth_df.drop(columns=["Change %"])

eth_df['Vol.'] = eth_df['Vol.'].apply(clean_currency)

eth_df.loc[:,"Price"]=eth_df.loc[:,"Price"].str.replace(",","")
eth_df.loc[:,"Price"]=eth_df.loc[:,"Price"].astype("float")

eth_df.loc[:,"Open"]=eth_df.loc[:,"Open"].str.replace(",","")
eth_df.loc[:,"Open"]=eth_df.loc[:,"Open"].astype("float")

eth_df.loc[:,"High"]=eth_df.loc[:,"High"].str.replace(",","")
eth_df.loc[:,"High"]=eth_df.loc[:,"High"].astype("float")

eth_df.loc[:,"Low"]=eth_df.loc[:,"Low"].str.replace(",","")
eth_df.loc[:,"Low"]=eth_df.loc[:,"Low"].astype("float")
eth_df2 = eth_df[['Open', 'High', 'Low', 'Price', 'Vol.']]
columns = ["open", "high"," low", "close", "volume"]
eth_df2.columns = columns
eth_df2.head()
# Create a dictionary of the two dataframes
to_merge_dict = {'BTC': btc_df2 , 'ETH': eth_df2}
# Use concat to create a merged dataframe from the dictionary
merged_df = pd.concat(to_merge_dict.values(), axis=1, keys=to_merge_dict.keys())
merged_df.head()
# Configure the Monte Carlo simulation to forecast 5 years cumulative returns
# Run 500 samples.
MC_crypto = MCSimulation(
  portfolio_data = merged_df,
  weights = [.5, .5],
  num_simulation = 500,
  num_trading_days = 252*5
)

# Review the simulation input data
display(MC_crypto.portfolio_data.head())
#Run the Monte Carlo simulation to forecast 5 years cumulative returns
MC_crypto.calc_cumulative_return()

# Visualize the probability distribution of the 5-year Monte Carlo simulation 
# by plotting a histogram
MC_sim_dist_plot = MC_crypto.plot_distribution()



# Generate summary statistics from the 5-year Monte Carlo simulation results
# Save the results as a variable
MC_summary_statistics = MC_crypto.summarize_cumulative_return()


# Review the 5-year Monte Carlo summary statistics
print(MC_summary_statistics)
# Print the current balance of the stock and bond portion of the members portfolio
print(f"The current balance of cryptocurrency is ${savings_amount:,.2f}")
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio
ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount
ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount

# Print the result of your calculations
print(f"There is a 95% chance that your investment over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.")<jupyter_output>There is a 95% chance that your investment over the next 5 years will end within in the range of $7.35 and $1,317.53.<jupyter_text>Part 4: Analysis of FAANG Stocks***Completed by <NAME>***  Set the variables for the Alpaca API and secret keys. Using the Alpaca SDK, create the Alpaca `tradeapi.REST` object. In this object, include the parameters for the Alpaca API key, the secret key, and the version number.<jupyter_code># 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")<jupyter_output><empty_output><jupyter_text>Set the following parameters for the Alpaca API call:- `tickers`: Use the tickers for the member’s stock and bond holdings.- `timeframe`: Use a time frame of one day.- `start_date` and `end_date`: using 7/30/2018 - 7/30/2021<jupyter_code># Set the tickers for the stock portion of the portfolio
tickers = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"]

# Set timeframe to 1D 
timeframe = "1D"

# 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
# Alternatively you can use a start and end date of 2020-08-07
start_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat()
end_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat()
# 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
df_portfolio = alpaca.get_barset(
    tickers,
    timeframe,
    start = start_date,
    end = end_date
).df

# Review the first 5 rows of the Alpaca DataFrame
df_portfolio.head()
# Access the closing price for FB from the Alpaca DataFrame
# Converting the value to a floating point number
fb_close_price = df_portfolio["FB"]["close"]
fb_close_price = float(fb_close_price)
# Print the FB closing price
print(f"The closing price of Facebook is ${fb_close_price:,.2f}")
# Access the closing price for AMZN from the Alpaca DataFrame
# Converting the value to a floating point number
amzn_close_price = df_portfolio["AMZN"]["close"]
amzn_close_price = float(amzn_close_price)
# Print the AMZN closing price
print(f"The closing price of Amazon is ${amzn_close_price:,.2f}")
# Access the closing price for FB from the Alpaca DataFrame
# Converting the value to a floating point number
aapl_close_price = df_portfolio["AAPL"]["close"]
aapl_close_price = float(aapl_close_price)
# Print the AAPL closing price
print(f"The closing price of Apple is ${aapl_close_price:,.2f}")
# Access the closing price for FB from the Alpaca DataFrame
# Converting the value to a floating point number
nflx_close_price = df_portfolio["NFLX"]["close"]
nflx_close_price = float(nflx_close_price)
# Print the NFLX closing price
print(f"The closing price of Netflix is ${nflx_close_price:,.2f}")
# Access the closing price for GOOG from the Alpaca DataFrame
# Converting the value to a floating point number
goog_close_price = df_portfolio["GOOG"]["close"]
goog_close_price = float(goog_close_price)
# Print the GOOG closing price
print(f"The closing price of Google is ${goog_close_price:,.2f}")<jupyter_output>The closing price of Google is $2,704.66<jupyter_text>4.1 Create a Financial Planner for Retirement Create the Monte Carlo SimulationIn this section, you’ll use the MCForecastTools library to create a Monte Carlo simulation for the member’s savings portfolio. To do this, complete the following steps:1. Make an API call via the Alpaca SDK to get 3 years of historical closing prices for an even 5-way split between FAANG stocks.2. Run a Monte Carlo simulation of 500 samples and (ANSWER FROM QUESTIONAIRE) for the FAANG portfolio, and then plot the results.The following image shows the overlay line plot resulting from a simulation with these characteristics.3. Plot the probability distribution of the Monte Carlo simulation. Plot the probability distribution of the Monte Carlo simulation. The following image shows the histogram plot resulting from a simulation with these characteristics.4. Generate the summary statistics for the Monte Carlo simulation.  Make an API call via the Alpaca SDK to get 3 years of historical closing prices for FAANG<jupyter_code># Set start and end dates of 3 years back from your current date
# Alternatively, you can use an end date of 2020-08-07 and work 3 years back from that date 
start_date = pd.Timestamp("2018-07-30", tz="America/New_York").isoformat()
end_date = pd.Timestamp("2021-07-30", tz="America/New_York").isoformat()

# Set number of rows to 1000 to retrieve the maximum amount of rows
limit_rows = 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
prices_df = alpaca.get_barset(
  tickers,
  timeframe,
  start=start_date,
  end=end_date,
  limit=limit_rows
).df


# Display both the first and last five rows of the DataFrame
display(prices_df.head())
display(prices_df.tail())
# Configure the Monte Carlo simulation to forecast 5 years cumulative returns
# Run 500 samples.
MC_faang = MCSimulation(
  portfolio_data = prices_df,
  weights = [.2, .2, .2, .2, .2],
  num_simulation = 500,
  num_trading_days = 252*5
)

# Review the simulation input data
MC_faang.portfolio_data.head()
# Run the Monte Carlo simulation to forecast 5 years cumulative returns
MC_faang.calc_cumulative_return()
# Visualize the 5-year Monte Carlo simulation by creating an
# overlay line plot
MC_sim_line_plot = MC_faang.plot_simulation()<jupyter_output><empty_output><jupyter_text>Generate the summary statistics for the Monte Carlo simulation.<jupyter_code># Generate summary statistics from the 5-year Monte Carlo simulation results
# Save the results as a variable
MC_summary_statistics = MC_faang.summarize_cumulative_return()


# Review the 5-year Monte Carlo summary statistics
print(MC_summary_statistics)<jupyter_output>count           500.000000
mean              3.678908
std               1.516097
min               1.191165
25%               2.600935
50%               3.493042
75%               4.537284
max              12.354789
95% CI Lower      1.486905
95% CI Upper      7.179377
Name: 1260, 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 in your Jupyter notebook:-  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
print(f"The current balance of your investing in FAANG stocks is ${savings_amount:,.2f}")
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current stock/bond portfolio
ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount
ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount

# Print the result of your calculations
print(f"There is a 95% chance that the portfolio over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.")<jupyter_output>There is a 95% chance that the portfolio over the next 5 years will end within in the range of $1,486.90 and $7,179.38.<jupyter_text>4.2 Coding for top 4 popular mutual fundshttps://www.marketwatch.com/tools/mutual-fund/top25largest<jupyter_code>tickers = ["SPY", "IVV", "VTI", "VOO"]
prices_df = alpaca.get_barset(
  tickers,
  timeframe,
  start=start_date,
  end=end_date,
  limit=limit_rows
).df

display(prices_df.head())
display(prices_df.tail())
# Configure the Monte Carlo simulation to forecast 5 years cumulative returns
# Run 500 samples.
MC_mutual_funds = MCSimulation(
  portfolio_data = prices_df,
  weights = [.25, .25, .25, .25],
  num_simulation = 500,
  num_trading_days = 252*5
)

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

# Run the Monte Carlo simulation to forecast 5 years cumulative returns
MC_mutual_funds.calc_cumulative_return()

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

# Review the 5-year Monte Carlo summary statistics
print(MC_summary_statistics)
# Print the current balance of the mutual funds of the members portfolio
print(f"The current balance of your investing in mutual funds is ${savings_amount:,.2f}")
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes for the current mutual fund portfolio
ci_lower_cumulative_return = MC_summary_statistics[8]*savings_amount
ci_upper_cumulative_return = MC_summary_statistics[9]*savings_amount

# Print the result of your calculations
print(f"There is a 95% chance that the portfolio over the next 5 years will end within in the range of ${ci_lower_cumulative_return:,.2f} and ${ci_upper_cumulative_return:,.2f}.")<jupyter_output>There is a 95% chance that the portfolio over the next 5 years will end within in the range of $1,429.92 and $3,915.83.<jupyter_text>Comparing investing in a "safe" bank account (i.e. high yield savings account, CD)Compound Interest Formula FV = P (1 + r / n)^Yn, where P is the starting principal, r is the annual interest rate, Y is the number of years invested, and n is the number of compounding periods per year. FV is the future value, meaning the amount the principal grows to after Y years.<jupyter_code>P = int(input("Enter starting principle please. "))
n = int(input("Enter number of compounding periods per year. "))
r = float(input("Enter annual interest rate. e.g. 15 for 15% "))
y = int(input("Enter the amount of years. "))

FV = P * (((1 + ((r/100.0)/n)) ** (n*y)))

print(f"The final amount after", y, f"years is ${FV:,.2f}.")
# another way to write code for compounding interest.  can tinker with it to make into function that takes in variables from questionaire?

years = range(1,31)
rate = 0.07
rates = pd.Series(index = years, data = rate)

x = 1000*((rates + 1).cumprod())
final_amount = x.tail(1).item()
print(f"${final_amount:,.2f}.")<jupyter_output>$7,612.26.
{'fraction_non_alphanumeric': 0.0931974599794669, 'fraction_numerical': 0.024031331989809498, 'mean_word_length': 4.91942381273914, 'pattern_counts': {'":': 24, '<': 63, '<?xml version=': 0, '>': 63, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '646445', 'license': 'MIT', 'n_tokens_mistral': 8446, 'n_tokens_neox': 7864, 'n_words': 2758, 'path': 'golden_years_final.ipynb', 'repo_name': 'kevin-mau/Golden-Years', 'size': '26332'}