#Igor Droś (130010), Leonardo Molestina (137487), Carles Lorenzo (137476) L1 #Basic parameters of the market ( Load required packages library(quantmod) library(xts) library(zoo) library(dplyr)

start_date <- as.Date(“2023-05-01”) end_date <- as.Date(“2023-09-30”) table_data <- data.frame( Category = character(), Beginning_of_Term = character(), End_of_Term = character(), Value_Beg = character(), Value_End = character(), stringsAsFactors = FALSE

)

add_row <- function(category, value_beg, value_end = ““) { # Check if value_beg is non-empty and not NA if (!is.null(value_beg) && !is.na(value_beg) && value_beg !=”“) { # Format value_beg and value_end to avoid scientific notation value_beg_formatted <- format(value_beg, scientific = FALSE, trim = TRUE) value_end_formatted <- format(value_end, scientific = FALSE, trim = TRUE)

    new_row <- data.frame(
        Category = category,
        Beginning_of_Term = format(start_date, "%d %B %Y"),
        End_of_Term = format(end_date, "%d %B %Y"),
        Value_Beg = value_beg_formatted,
        Value_End = value_end_formatted,
        stringsAsFactors = FALSE
    )
    table_data <<- rbind(table_data, new_row)  # Update the global table_data
} else {
    cat("Warning: Data for", category, "is missing or incomplete.\n")
}

}

Function to fetch data with error handling

get_symbol_data <- function(symbol, src, from, to) { tryCatch({ data <- getSymbols(symbol, src = src, from = from, to = to, auto.assign = FALSE, warnings = FALSE) if (is.null(data) || nrow(data) == 0) { warning(paste(“No data returned for symbol:”, symbol)) return(NULL) } return(data) }, error = function(e) { warning(paste(“Error fetching data for symbol:”, symbol, “-”, e$message)) return(NULL) }) }

Function to update data and add rows

update_data <- function() { # Fetch S&P 500 and Nasdaq data sp500_data <- get_symbol_data(“^GSPC”, “yahoo”, start_date, end_date) nasdaq_data <- get_symbol_data(“^IXIC”, “yahoo”, start_date, end_date)

if (!is.null(sp500_data)) {
    # Extract beginning and ending prices for S&P 500
    sp500_open <- round(as.numeric(first(Op(sp500_data))), 2)
    sp500_close <- round(as.numeric(last(Cl(sp500_data))), 2)
    # Add row for S&P 500
    add_row("S&P 500 Index Level", sp500_open, sp500_close)
}

if (!is.null(nasdaq_data)) {
    # Extract beginning and ending prices for Nasdaq
    nasdaq_open <- round(as.numeric(first(Op(nasdaq_data))), 2)
    nasdaq_close <- round(as.numeric(last(Cl(nasdaq_data))), 2)
    # Add row for Nasdaq Composite
    add_row("Nasdaq Composite Index Level", nasdaq_open, nasdaq_close)
}

# Fetch interest rate data from FRED
prime_rate <- get_symbol_data("DPRIME", "FRED", start_date, end_date)
fed_funds_rate <- get_symbol_data("FEDFUNDS", "FRED", start_date, end_date)
commercial_paper_rate <- get_symbol_data("DCPN3M", "FRED", start_date, end_date)  # 3-Month Nonfinancial Commercial Paper Rate
cd_rate <- get_symbol_data("TB3MS", "FRED", start_date, end_date)  # 3-Month Treasury Bill Secondary Market Rate
tbill_13wk <- get_symbol_data("DTB3", "FRED", start_date, end_date)
tbill_26wk <- get_symbol_data("DTB6", "FRED", start_date, end_date)

# Extract and add interest rate data
if (!is.null(prime_rate)) {
    add_row("Prime Rate", round(as.numeric(first(prime_rate)), 2), round(as.numeric(last(prime_rate)), 2))
}
if (!is.null(fed_funds_rate)) {
    add_row("Federal Funds Rate", round(as.numeric(first(fed_funds_rate)), 2), round(as.numeric(last(fed_funds_rate)), 2))
}
if (!is.null(commercial_paper_rate)) {
    add_row("Commercial Paper Rate (90 days)", round(as.numeric(first(commercial_paper_rate)), 2), round(as.numeric(last(commercial_paper_rate)), 2))
}
if (!is.null(cd_rate)) {
    add_row("Certificate of Deposit Rate (3-month)", round(as.numeric(first(cd_rate)), 2), round(as.numeric(last(cd_rate)), 2))
}
if (!is.null(tbill_13wk)) {
    add_row("Treasury Bill Rate (13 weeks)", round(as.numeric(first(tbill_13wk)), 2), round(as.numeric(last(tbill_13wk)), 2))
}
if (!is.null(tbill_26wk)) {
    add_row("Treasury Bill Rate (26 weeks)", round(as.numeric(first(tbill_26wk)), 2), round(as.numeric(last(tbill_26wk)), 2))
}

# Fetch bond yield data from FRED
treasury_long_term_yield <- get_symbol_data("GS10", "FRED", start_date, end_date)
corporate_bond_yield <- get_symbol_data("BAA", "FRED", start_date, end_date)
high_yield_bond_yield <- get_symbol_data("BAMLH0A0HYM2EY", "FRED", start_date, end_date)

# Extract and add bond yield data
if (!is.null(treasury_long_term_yield)) {
    add_row("Treasury Long-term Bond Yield", round(as.numeric(first(treasury_long_term_yield)), 2), round(as.numeric(last(treasury_long_term_yield)), 2))
}
if (!is.null(corporate_bond_yield)) {
    add_row("Corporate (Master) Bond Yield", round(as.numeric(first(corporate_bond_yield)), 2), round(as.numeric(last(corporate_bond_yield)), 2))
}
if (!is.null(high_yield_bond_yield)) {
    add_row("High-yield Corporate Bond Yield", round(as.numeric(first(high_yield_bond_yield)), 2), round(as.numeric(last(high_yield_bond_yield)), 2))
}

# Fetch exchange rates
gbp_usd <- get_symbol_data("GBPUSD=X", "yahoo", start_date, end_date)
jpy_usd <- get_symbol_data("JPYUSD=X", "yahoo", start_date, end_date)
mxn_usd <- get_symbol_data("MXNUSD=X", "yahoo", start_date, end_date)

# Extract and add exchange rate data
if (!is.null(gbp_usd)) {
    gbp_beg <- round(as.numeric(first(Cl(gbp_usd))), 4)
    gbp_end <- round(as.numeric(last(Cl(gbp_usd))), 4)
    add_row("Exchange Rate of the British Pound (in $)", gbp_beg, gbp_end)
}
if (!is.null(jpy_usd)) {
    jpy_beg <- round(as.numeric(first(Cl(jpy_usd))), 6)
    jpy_end <- round(as.numeric(last(Cl(jpy_usd))), 6)
    add_row("Exchange Rate of the Japanese Yen (in $)", jpy_beg, jpy_end)
}
if (!is.null(mxn_usd)) {
    mxn_beg <- round(as.numeric(first(Cl(mxn_usd))), 6)
    mxn_end <- round(as.numeric(last(Cl(mxn_usd))), 6)
    add_row("Exchange Rate of the Mexican Peso (in $)", mxn_beg, mxn_end)
}

# Fetch futures prices
# Treasury Bond Futures (Symbol: ZB=F)
treasury_futures <- get_symbol_data("ZB=F", "yahoo", start_date, end_date)
if (!is.null(treasury_futures)) {
    treasury_beg <- round(as.numeric(first(Cl(treasury_futures))), 2)
    treasury_end <- round(as.numeric(last(Cl(treasury_futures))), 2)
    add_row("Treasury Bond Futures", treasury_beg, treasury_end)
}

# S&P 500 Index Futures (Symbol: ES=F)
sp500_futures <- get_symbol_data("ES=F", "yahoo", start_date, end_date)
if (!is.null(sp500_futures)) {
    sp500_fut_beg <- round(as.numeric(first(Cl(sp500_futures))), 2)
    sp500_fut_end <- round(as.numeric(last(Cl(sp500_futures))), 2)
    add_row("S&P 500 Index Futures", sp500_fut_beg, sp500_fut_end)
}

# British Pound Futures (Symbol: 6B=F)
bp_futures <- get_symbol_data("6B=F", "yahoo", start_date, end_date)
if (!is.null(bp_futures)) {
    bp_fut_beg <- round(as.numeric(first(Cl(bp_futures))), 4)
    bp_fut_end <- round(as.numeric(last(Cl(bp_futures))), 4)
    add_row("British Pound Futures", bp_fut_beg, bp_fut_end)
}

# Options Data
# Since programmatic access to options data is limited, we'll manually input the data.

# Call Option on a Firm (e.g., Apple Inc. - AAPL)
call_option_firm <- "AAPL"
call_option_expiration <- "2024-12-20"
call_option_strike <- 150  # Example strike price
call_option_premium <- 10   # Example premium

# Get current stock price
firm_data <- get_symbol_data(call_option_firm, "yahoo", Sys.Date() - 10, Sys.Date() - 1)
if (!is.null(firm_data)) {
    current_price <- round(as.numeric(last(Cl(firm_data))), 2)
} else {
    current_price <- "N/A"
}

# Add rows
add_row(paste("Call Option on", call_option_firm, "- Stock Price"), current_price)
add_row(paste("Call Option on", call_option_firm, "- Option Premium"), call_option_premium)
add_row(paste("Call Option on", call_option_firm, "- Strike Price"), call_option_strike)
add_row(paste("Call Option on", call_option_firm, "- Expiration"), call_option_expiration)

# Put Option on a Firm (e.g., Intel Corporation - INTC)
put_option_firm <- "INTC"
put_option_expiration <- "2024-12-20"
put_option_strike <- 50  # Example strike price
put_option_premium <- 0.0005   # Example premium adjusted to avoid scientific notation

# Get current stock price
firm_data <- get_symbol_data(put_option_firm, "yahoo", Sys.Date() - 10, Sys.Date() - 1)
if (!is.null(firm_data)) {
    current_price <- round(as.numeric(last(Cl(firm_data))), 2)
} else {
    current_price <- "N/A"
}

# Add rows
add_row(paste("Put Option on", put_option_firm, "- Stock Price"), current_price)
add_row(paste("Put Option on", put_option_firm, "- Option Premium"), put_option_premium)
add_row(paste("Put Option on", put_option_firm, "- Strike Price"), put_option_strike)
add_row(paste("Put Option on", put_option_firm, "- Expiration"), put_option_expiration)

# Currency Options Data
# Call Option on a Foreign Currency (Euro)
currency_call = "Euro (EURUSD)"
currency_call_expiration = "2024-12-20"
currency_call_strike = 1.20
currency_call_premium = 0.05

# Get current exchange rate for EURUSD
eurusd_data <- get_symbol_data("EURUSD=X", "yahoo", Sys.Date() - 10, Sys.Date() - 1)
if (!is.null(eurusd_data)) {
    eurusd_price <- round(as.numeric(last(Cl(eurusd_data))), 4)
} else {
    eurusd_price <- "N/A"
}

# Add rows
add_row(paste("Call Option on", currency_call, "- Currency Value"), eurusd_price)
add_row(paste("Call Option on", currency_call, "- Option Premium"), currency_call_premium)
add_row(paste("Call Option on", currency_call, "- Strike Price"), currency_call_strike)
add_row(paste("Call Option on", currency_call, "- Expiration"), currency_call_expiration)

# Put Option on a Foreign Currency (Japanese Yen)
currency_put = "Japanese Yen (JPYUSD)"
currency_put_expiration = "2024-12-20"
currency_put_strike = 0.0090
currency_put_premium = 0.0005

# Get current exchange rate for JPYUSD
jpyusd_data <- get_symbol_data("JPYUSD=X", "yahoo", Sys.Date() - 10, Sys.Date() - 1)
if (!is.null(jpyusd_data)) {
    jpyusd_price <- round(as.numeric(last(Cl(jpyusd_data))), 6)
} else {
    jpyusd_price <- "N/A"
}

# Add rows
add_row(paste("Put Option on", currency_put, "- Currency Value"), jpyusd_price)
add_row(paste("Put Option on", currency_put, "- Option Premium"), currency_put_premium)
add_row(paste("Put Option on", currency_put, "- Strike Price"), currency_put_strike)
add_row(paste("Put Option on", currency_put, "- Expiration"), currency_put_expiration)

}

Run the function to update data and print the table

update_data()

Display the data frame with proper formatting

print(table_data, right = FALSE)

L2 Financial markets microstructure → download basic statistic of NASDAQ and London Stock Exchange and compare them https://rpubs.com/staszkiewicz/FM05_Financials

https://rpubs.com/staszkiewicz/FM_02_Market_Comparision

Load the library

if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)

Define the date range

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Download data for FTSE and NASDAQ

ftse_data <- getSymbols(“^FTSE”, src = “yahoo”, from = start_date, to = end_date, auto.assign = FALSE) nasdaq_data <- getSymbols(“^IXIC”, src = “yahoo”, from = start_date, to = end_date, auto.assign = FALSE)

Data preprocessing

ftse_close <- na.omit(Cl(ftse_data)) # Adjusted closing prices for FTSE nasdaq_close <- na.omit(Cl(nasdaq_data)) # Adjusted closing prices for NASDAQ

Basic statistics for FTSE

lond_stats <- data.frame( Mean = mean(ftse_close), Median = median(ftse_close), Std_Dev = sd(ftse_close), Min = min(ftse_close), Max = max(ftse_close) )

Basic statistics for NASDAQ

nasdaq_stats <- data.frame( Mean = mean(nasdaq_close), Median = median(nasdaq_close), Std_Dev = sd(nasdaq_close), Min = min(nasdaq_close), Max = max(nasdaq_close) )

Compare statistics

stats_comparison <- rbind( “FTSE 100” = lond_stats, “NASDAQ Composite” = nasdaq_stats )

Display statistics comparison

print(“Comparison of FTSE 100 and NASDAQ Composite statistics:”) print(round(stats_comparison, 2))

Plot both indices

plot(ftse_close, main = “FTSE 100 (May 2024 - Sep 2024)”, col = “blue”, lwd = 2, xlab = “Date”, ylab = “Price”) lines(nasdaq_close, col = “red”, lwd = 2) legend(“topright”, legend = c(“FTSE 100”, “NASDAQ Composite”), col = c(“blue”, “red”), lwd = 2)

The FTSE 100 and NASDAQ Composite are two stock market indices, but they behave very differently: FTSE 100:

Stable and predictable. Average level: 8,254, with small changes between its lowest (8,008) and highest (8,445). Suitable for people who prefer safety and low risk. NASDAQ Composite:

Higher growth potential but more volatile. Average level: 17,357, with bigger changes between its lowest (15,605) and highest (18,647). Better for people willing to take risks for potentially bigger returns. In short: FTSE 100 is safer but steady, while NASDAQ Composite is riskier but offers higher rewards.

Load necessary library

if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)

Define the date range

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Fetch data for FTSE 100 (^FTSE) and NASDAQ Composite (^IXIC)

ftse_data <- getSymbols(“^FTSE”, src = “yahoo”, from = start_date, to = end_date, auto.assign = FALSE) nasdaq_data <- getSymbols(“^IXIC”, src = “yahoo”, from = start_date, to = end_date, auto.assign = FALSE)

Extract adjusted close prices

ftse_close <- na.omit(Cl(ftse_data)) # Remove missing values from FTSE nasdaq_close <- na.omit(Cl(nasdaq_data)) # Remove missing values from NASDAQ

Align the two time series by their dates

aligned_data <- merge(ftse_close, nasdaq_close, all = FALSE) colnames(aligned_data) <- c(“FTSE”, “NASDAQ”)

Calculate the correlation

correlation <- cor(aligned_data\(FTSE, aligned_data\)NASDAQ)

Optionally, print the correlation directly if needed

print(round(correlation, 2))

A correlation of -0.14 between the FTSE 100 and the NASDAQ Composite means their relationship is very weak and slightly negative.This suggests the two markets don’t influence each other much, likely because they are in different regions and focus on different types of companies (FTSE on established UK firms and NASDAQ on U.S. tech companies).Since the indices aren’t strongly linked, investing in both could help diversify a portfolio. When one is unstable, the other might not be affected much, reducing overall risk.

L3 Instrument’s overview and valuation → DONE L3.1 Compare the 13-week Treasury bill rate (which is a proxy for short-term interest rates) at the end of the school term to the rate that existed at the beginning of the school term. (note: 3-Month Treasury Bill Secondary Market Rate, Discount Basis (TB3MS)) https://fred.stlouisfed.org/series/TclB3MShttps://fred.stlouisfed.org/series/DTB3 As i’was supposed to work with the academic calendar, I’ve used the following dates: Beginning of the school term: assume May 1, 2024 End of the school term: assume September 30, 2024 # Load the necessary library if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)

Define the start and end dates for the period

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Download data from FRED for the TB3MS indicator

getSymbols(“TB3MS”, src = “FRED”, auto.assign = TRUE)

Check that the data has been downloaded correctly

if (!exists(“TB3MS”) || is.null(TB3MS) || nrow(TB3MS) == 0) { print(“No data available for TB3MS. Check the date range or internet connection.”) } else { # Display the range of available data print(paste(“Range of available data:”, range(index(TB3MS))))

# Try to get the rates for the exact dates
start_rate <- TB3MS[start_date]
end_rate <- TB3MS[end_date]

# Handle cases where there is no data for the exact dates
if (is.null(start_rate) || length(start_rate) == 0 || is.na(start_rate)) {
    closest_start <- which(index(TB3MS) >= start_date)
    start_rate <- if (length(closest_start) > 0) TB3MS[closest_start[1]] else NA
}

if (is.null(end_rate) || length(end_rate) == 0 || is.na(end_rate)) {
    closest_end <- which(index(TB3MS) <= end_date)
    end_rate <- if (length(closest_end) > 0) TB3MS[closest_end[length(closest_end)]] else NA
}

# Print the start and end rates
print(paste("Start Rate (closest to 1-May-2024):", 
            ifelse(!is.na(start_rate), as.numeric(start_rate), "No Data")))
print(paste("End Rate (closest to 30-Sep-2024):", 
            ifelse(!is.na(end_rate), as.numeric(end_rate), "No Data")))

# Calculate the difference if both rates are available
if (!is.na(start_rate) && !is.na(end_rate)) {
    rate_difference <- as.numeric(end_rate) - as.numeric(start_rate)
    print(paste("Rate difference from start to end of term:", rate_difference))
} else {
    print("Insufficient data to compute the rate difference.")
}

}

The 3-month Treasury Bill rate decreased slightly from 5.25% on May 1, 2024, to 4.72% on September 30, 2024. The difference is -0.53%. This shows a small decline in short-term interest rates The decrease might indicate lower inflation expectations or a slowing economy. It could also reflect expectations of future policy changes by the Federal Reserve (or the relevant central bank). A small drop in short-term rates could suggest the market expects a more dovish (growth-supporting) stance from the Federal Reserve, possibly due to economic factors or inflationary pressures easing. In the short term, it’s not significant L3.2 Why interest rates change over time?

Interest rates are the cost of borrowing money. If you borrow money, you pay interest. If you save money, the bank pays you interest. So, why do interest rates change? There are some parts who influence the interests, such as: 1. Central Banks: Central banks control interest rates to manage the economy. They raise rates to slow down inflation (when prices rise too fast) and lower rates to help the economy grow during tough times. 2. Inflation: High inflation causes interest rates to rise because lenders need to protect their money’s value. Low inflation leads to lower interest rates. 3. Supply and Demand: If many people want loans, interest rates go up. If fewer people want loans, rates go down. 4. Government Borrowing: If the government borrows a lot, it can increase interest rates by making more people want to lend money. 5. Global Events: Interest rates can change based on what happens in other countries and financial markets. 6. Risk: When there’s more risk in the economy (e.g., during a crisis), interest rates can go lower, as people look for safer investments. Why It Matters - For Borrowers: Higher rates mean more expensive loans. - For Savers: Higher rates mean better returns on savings. - For Businesses: Rates affect how much it costs to invest or grow. Interest rates change mainly because central banks adjust them to control inflation and manage economic growth. They also depend on the supply and demand for money: if more people want loans or there’s less money available, rates can increase. Global factors, like decisions in major economies or changes in currency values, also influence interest rates. Lastly, expectations of inflation and risk play a role, as lenders may raise rates to protect themselves from losing money or purchasing power in the future. L4 Efficiency of market and information → DONE Check if on 26 October 2017 coca cola shares were hit by the advarse information realized on the market. (assume 26 is the information realese date) → TRADES EVOLUTION # Install and load required libraries library(quantmod)

Step 1: Fetch Coca-Cola (KO) stock data for October 2017

getSymbols(“KO”, from = “2017-10-01”, to = “2017-11-01”)

View the downloaded data

head(KO)

Step 2: Convert to a data frame for easier manipulation

ko_data <- data.frame(Date = index(KO), coredata(KO)) head(ko_data)

Step 3: Filter data around October 26, 2017

library(dplyr) ko_data_filtered <- ko_data %>% filter(Date >= as.Date(“2017-10-25”) & Date <= as.Date(“2017-10-27”))

Display filtered data

print(“Filtered Data for October 25-27, 2017:”) print(ko_data_filtered)

Calculate percentage change in adjusted closing price

ko_data_filtered <- ko_data_filtered %>% mutate(Change = 100 * (KO.Adjusted - lag(KO.Adjusted)) / lag(KO.Adjusted))

print(“Filtered Data with Percentage Change:”) print(ko_data_filtered)

library(ggplot2)

ggplot(ko_data, aes(x = Date, y = KO.Adjusted)) + geom_line(color = “blue”) + geom_vline(xintercept = as.Date(“2017-10-26”), linetype = “dashed”, color = “red”) + labs(title = “Coca-Cola Stock Price Around October 26, 2017”, x = “Date”, y = “Adjusted Close Price”) + theme_minimal()

ggplot(ko_data, aes(x = Date, y = KO.Volume)) + geom_line(color = “darkgreen”) + geom_vline(xintercept = as.Date(“2017-10-26”), linetype = “dashed”, color = “red”) + labs(title = “Coca-Cola Trading Volume Around October 26, 2017”, x = “Date”, y = “Volume”) + theme_minimal()

→ STOCK PRICE EVOLUTION # Install and load the required libraries library(quantmod) library(ggplot2)

Fetch Coca-Cola (KO) stock data for October 2017

getSymbols(“KO”, from = “2017-10-01”, to = “2017-11-01”)

Convert the data to a data frame for easier manipulation

ko_data <- data.frame(Date = index(KO), coredata(KO))

Plot the evolution of the adjusted stock price

ggplot(ko_data, aes(x = Date, y = KO.Adjusted)) + geom_line(color = “blue”) + # Line showing the adjusted price geom_vline(xintercept = as.Date(“2017-10-26”), linetype = “dashed”, color = “red”) + # Vertical line to highlight October 26 labs(title = “Evolution of Coca-Cola Stock Price in October 2017”, x = “Date”, y = “Adjusted Close Price”) + theme_minimal()

As we can see, Coca-Cola shares were hit by the adverse information realized on the market on 26 October 2017. This can be observed through the increase in trading volume from 23th October, around that date, which indicates that investors reacted to the negative news with an immediate adjustment in their positions. Although the stock price did not show a drastic drop on the same day, the increase in trading volume suggests that there was a reaction to the event. Additionally, the subsequent decrease in trading volume after 26 October indicates that the market started to absorb the information and the interest in trading decreased, which is common after a significant informational event. In summary, although there wasn’t a major movement in the stock price, the trading volume indicates that the market reacted negatively to the disclosed information, suggesting that the shares were affected by the adverse news on that date. L5 Financial statements and fundamental analysis # Load necessary libraries library(readxl) library(edgar) library(dplyr) library(tidyr) library(finreportr)

We need to give out mail to edgar in order to use it’s data in rpubs studio

options(HTTPUserAgent = “”)

In order to download Microsoft annual report, you need to manually download the file from EDGAR sec. Microsofts ticker is MSFT and CIK number is 0000789019. Then you put it into Rpubs.

Load the financial report for Microsoft (Excel file with data)

Financial_Report_Microsoft <- read_excel(“Financial_Report.xlsx”)

Load the financial report data

Financial_Report <- read_excel(“Financial_Report.xlsx”)

View the financial report data in the Viewer

View(Financial_Report)

Download annual report for Bank of America (CIK: 0000070858) - example

BankofAmerica <- GetBalanceSheet(‘BAC’, 2018)

L5.1: Text description about Bank of America’s funding structure

cat(“L5.1”) cat(“This Bank has the most of its funds because of firstly: interest bearing deposits, then non-interest bearing deposits,”) cat(“then interest bearing deposits (foreign), and lastly non-interest bearing deposits (foreign)”)

L5.2: Text description about Bank of America’s investments

cat(“L5.2”) cat(“Bank mainly invests in federal funds and securities. From Consolidated balance sheet from edgar sec (261,131 million of $ worth of sold securities)”)

L5.3: Bank’s stance on securities market

cat(“L5.3”) cat(“I believe that the bank already sells securities as we can see in ‘Notes to financial statements’ under ‘securities’ they offer various securities.”) cat(“And there are securities for sale so Bank of America does not want to enter the securities market, because it is already in it.”)

L5.4: Text description about insurances offered by Bank of America

cat(“L5.4”) cat(“Bank of America offers various types of insurances. You can find them in the Financial statement as well.”)

L5.5: Bank’s assets in loans and leases

cat(“L5.5”) cat(“Bank of America has a significant part of its assets in loans and leases which very often have variable rates.”) cat(“Bank earns on any interest rate rise. On the other side, bank has interest bearing deposits but they mostly have fixed rates.”) cat(“Therefore, I believe that Bank of America has a positive gap between rate-sensitive assets and liabilities.”)

L5.6: Total Assets, Total Interest Income, and Interest Income Percentage

total_assets <- 2354507000000 # 2,354,507 million USD total_interest_income <- 66769000000 # 66,769 million USD interest_income_percentage <- (total_interest_income / total_assets) * 100 cat(“L5.6”) cat(“Total Assets from ‘Consolidated Balance sheet’ are equal to 2,354,507 million USD”) cat(“Total interest income from ‘Consolidated Statement of Income’ is equal to 66,769 million USD”) cat(“Percentage = (66,769,000,000 / 2,354,507,000,000) * 100% =”, interest_income_percentage, “%”)

L5.7: Total Interest Expense and Interest Expense Percentage

total_interest_expense <- 19337000000 # 19,337 million USD interest_expense_percentage <- (total_interest_expense / total_assets) * 100 cat(“L5.7”) cat(“Total interest expense from ‘Consolidated Statement of Income’ is equal to 19,337 million USD”) cat(“Percentage = (19,337,000,000 / 2,354,507,000,000) * 100% =”, interest_expense_percentage, “%”)

L5.8: Net Interest Income and Net Interest Margin

net_interest_income <- 47432000000 # 47,432 million USD average_earning_assets <- (2354507000000 + 2281234000000) / 2 # Average of Total Assets for 2017 and 2018 net_interest_margin <- (net_interest_income / average_earning_assets) * 100 cat(“L5.8”) cat(“Net interest income from ‘Consolidated Statement of Income’ is equal to 47,432 million USD”) cat(“Average earning assets = (2,354,507,000,000 + 2,281,234,000,000) / 2 = 2,317,870,500,000”) cat(“Net interest margin = (47,432,000,000 / 2,317,870,500,000) * 100% =”, net_interest_margin, “%”)

L5.9: Non-interest Income and Expense Percentages

total_non_interest_income <- 43815000000 # 43,815 million USD non_interest_income_percentage <- (total_non_interest_income / total_assets) * 100 total_non_interest_expense <- 53381000000 # 53,381 million USD non_interest_expense_percentage <- (total_non_interest_expense / total_assets) * 100 cat(“L5.9”) cat(“Total non-interest income from ‘Consolidated Statement of Income’ = 43,815 million USD”) cat(“Total non-interest expense from ‘Consolidated Statement of Income’ = 53,381 million USD”) cat(“Percentage of income = (43,815,000,000 / 2,354,507,000,000) * 100% =”, non_interest_income_percentage, “%”) cat(“Percentage of expense = (53,381,000,000 / 2,354,507,000,000) * 100% =”, non_interest_expense_percentage, “%”)

L5.10: Provision for Credit Losses

cat(“L5.10”) cat(“Provision for credit losses = 3,282 million USD”) cat(“Total Assets = 2,354,507 million USD”) cat(“Percentage = (3,282,000,000 / 2,354,507,000,000) * 100% = 0.14%”)

L5.11: Net income calculation

cat(“L5.11”) cat(“Net income from ‘Consolidated Statement of Income’ = 28,147 million USD”) cat(“Total Assets from ‘Consolidated Balance Sheet’ = 2,354,507 million USD”) cat(“Percentage = (28,147,000,000 / 2,354,507,000,000) * 100% = 1.2%”)

L5.12: Net income as a percentage of shareholder’s equity

cat(“L5.12”) cat(“Net income = 28,147 million USD”) cat(“Total shareholder’s equity = 265,325 million USD”) cat(“Percentage = (28,147,000,000 / 265,325,000,000) * 100% = 10.61%”)

L5.13: Interest income impact

cat(“L5.13”) cat(“Interest income – positive impact, because bank would earn more on loans and investments”)

L5.14: Provision for credit losses impact

cat(“L5.14”) cat(“Provision for credit losses – as the market condition worsens, bank’s risk on loans and credit losses increases, so the bank needs to increase its provision for losses on the loans which would decrease the demand for those services.”)

L5.15: S&P 500 mutual fund risk level

cat(“L5.15”) cat(“The S&P 500 mutual fund is a moderate risk investment due to its diversification across 500 large companies.”)

L5.16: S&P 500 return calculation for 2023

cat(“L5.16”) cat(“Return for year 2023 = 26.29%”) cat(“Average return from the last 3 years = (26.29 - 18.11 + 28.71) / 3 = 12.3%”)

L5.17: S&P 500 dependence on economic conditions

cat(“L5.17”) cat(“S&P 500 is heavily influenced by fluctuations of stocks of companies included in S&P 500. It is highly dependent on stock market conditions.”)

L5.18: Vanguard mutual fund fee structure

cat(“L5.18”) cat(“Vanguard charges $25 for each brokerage account and 0.25% to 1% of transaction value depending on the amount.”)

L5.19: Expense ratio calculation for Vanguard 500 index fund

cat(“L5.19”) cat(“The expense ratio is 0.04 = 4%. You can see this on the Vanguard website.”)

L5.20: Securities firm services

cat(“L5.20”) cat(“Securities firms offer a wide range of financial services including trading, investment banking, asset management, wealth management, etc.”) cat(“These companies serve individuals and companies by being an intermediary between buyer and seller on the financial market.”)

L5.21: JP Morgan’s Risk Factors

cat(“L5.21”) cat(“In their Financial statement in Part 1, Item 1A, Risk Factors, JP Morgan stated:”) cat(“Regulatory risks, including the impact that applicable laws, rules, and regulations in the highly-regulated and supervised financial services industry, as well as changes to or in the application, interpretation or enforcement of those laws, rules and regulations, can have on JPMorgan Chase’s business and operations.”)

L5.22: JP Morgan’s Performance in 2024

cat(“L5.22”) cat(“JP Morgan’s performance in 2024 has been extremely successful due to many factors such as: rising interest rates which increase their margin on loans; high activity in financial markets; good revenues from branches like wealth management or investment banking and strong economic growth.”)

L6 Equity I’ve asked the professor what do we have to do → 1 equity - portfolio by Msrkovitz

S&P500

Load required library

library(quantmod)

Download S&P 500 data from Yahoo Finance

getSymbols(“^GSPC”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)

Plot S&P 500 Adjusted Closing Prices

plot(GSPC$GSPC.Adjusted, main = “S&P 500 (May 2024 - September 2024)”, ylab = “S&P 500 Adjusted Close”, xlab = “Date”, col = “red”, lwd = 2) grid()

Additional summary of the data

summary(GSPC$GSPC.Adjusted)

Optional: Display the first few rows of the data

head(GSPC)

TESLA

Load required library

library(quantmod)

Download Tesla stock data from Yahoo Finance

getSymbols(“TSLA”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)

Plot Tesla Adjusted Closing Prices

plot(TSLA$TSLA.Adjusted, main = “Tesla (TSLA) Adjusted Close (May 2024 - September 2024)”, ylab = “Adjusted Close Price (USD)”, xlab = “Date”, col = “blue”, lwd = 2) grid()

Additional summary of the data

summary(TSLA$TSLA.Adjusted)

Optional: Display the first few rows of the data

head(TSLA)

MICROSOFT

Load required library

library(quantmod)

Download Microsoft stock data from Yahoo Finance

getSymbols(“MSFT”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)

Plot Microsoft Adjusted Closing Prices

plot(MSFT$MSFT.Adjusted, main = “Microsoft (MSFT) Adjusted Close (May 2024 - September 2024)”, ylab = “Adjusted Close Price (USD)”, xlab = “Date”, col = “orange”, lwd = 2) grid()

Additional summary of the data

summary(MSFT$MSFT.Adjusted)

Optional: Display the first few rows of the data

head(MSFT)

IBM

Load required library

library(quantmod)

Download IBM stock data from Yahoo Finance

getSymbols(“IBM”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)

Plot IBM Adjusted Closing Prices

plot(IBM$IBM.Adjusted, main = “IBM (IBM) Adjusted Close (May 2024 - September 2024)”, ylab = “Adjusted Close Price (USD)”, xlab = “Date”, col = “purple”, lwd = 2) grid()

Additional summary of the data

summary(IBM$IBM.Adjusted)

Optional: Display the first few rows of the data

head(IBM)

NVIDIA

Load required library

library(quantmod)

Download NVIDIA stock data from Yahoo Finance

getSymbols(“NVDA”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)

Plot NVIDIA Adjusted Closing Prices

plot(NVDA$NVDA.Adjusted, main = “NVIDIA (NVDA) Adjusted Close (May 2024 - September 2024)”, ylab = “Adjusted Close Price (USD)”, xlab = “Date”, col = “green”, lwd = 2) grid()

Additional summary of the data

summary(NVDA$NVDA.Adjusted)

Optional: Display the first few rows of the data

head(NVDA)

L7 Fixed income Comparing yields among securities L7.1 What is the difference between the yield on corporate high-quality bonds and the yield on Treasury bonds at the end of the school term? Explain why the difference exists? The corporate Bond Yield has a 6.16% and the long-term bond yield is 6.16%, the difference between the yield is 1.78%. The difference exists because corporate bonds are riskier than treasury bonds. Treasury bonds are considered risk free since they are backed by the US government. While corporate bonds have a risk of default. L7.2 What is the difference between the yield on long-term Treasury bonds and the yield on long-term municipal bonds at the end of the school term? Explain why the difference exists? The long-term treasury bonds typically differ from long-term bonds because of tax advantages and credit risk differences that are associated with municipal bonds. Interes incomes from municipal bond are often exempt from federal income taxes, sometime¡mes state and local as well. Municipal bond are considered safe, but they are still riskier than treasury bonds, because treasury bonds have been backed by the federal government. Demand from tax-exempt income can lower municipal bond yields. Assessing the forecasting ability of the yield curve L7.3 What was the difference between the 26-week T-bill yield and the 13-week T-bill yield at the beginning of the school term? The 26 week T-bill yield is 4.91% while the 13-week T-bill yield is 5.1%. Making the difference between them 0.19%. L7.4 Does this imply that the yield curve had an upward or downward slope at that time? It had a downward slope at the beginning of the term, because the 13-week Treasurie bill was higher than the 26-week treasury bill. This is because the market is expecting declining future interest rates, assuming economic slowdowns in the future, or future monetary policy easing by the central bank. L7.5 Assuming that this slope can be primarily attributed to expectations theory, did the direction of the slope indicate that the market expected higher or lower interest rates in the future? Taking into account the expectation theory, the market expects lower interest rates. In the scenario, the higher yield reflects the market’s belief that interest rates will decline over the next 26 weeks. L7.6 Did interest rates move in that direction over the school term? While both treasury bills matched by the end of the term, the direction did not aling with the initial expectation of falling interest rates. This means that the market expectations at the start of the term did not fully materialize

Explaining shifts in the yield curve over time L7.7 What was the difference between the long-term Treasury bond yield and the 13-week T-bill yield at the beginning of the school term? At the beginning of the term the 13-week treasury bill rate was 5.1 and the treasury long term bond yield 3.57. The difference is -1.5. The T-bill is higher than the long term treasury bond yield at the start of the term. L7.8 What is the difference between the long-term Treasury bond yield and the 13-week T-bill yield at the end of the school term? The difference at the end is 13-week T-bill 5.32 and the treasury llong term bond yield 438 the difference being -0.94 13 week T bill will be higher than the long term treasury bond. L7.9 Given your answers to the two previous questions, describe how the yield curve changed over the school term. Explain the changes in expectations about future interest rates that are implied by the shift in the yield curve over the school term. The yield curve is an inverted yield curve, which reflects market expectations of declining future interest rates and the yield curve remains inverted, but less pronounced inversion indicates a shift in market expectations. The Fed’s influence on interest rates L7.10 Did the Fed change the federal funds rate over the school term?

Load necessary libraries

library(quantmod)

Get the federal funds rate data from FRED

getSymbols(“FEDFUNDS”, src = “FRED”)

Subset data to the desired date range

fed_subset <- window(FEDFUNDS, start = as.Date(“2024-05-01”), end = as.Date(“2024-09-30”))

Plot the federal funds rate over the specified time period

plot(fed_subset, main = “Federal Funds Rate (May 2024 - September 2024)”, ylab = “Federal Funds Rate (%)”, xlab = “Date”, col = “blue”, lwd = 2)

Add grid lines for better readability

grid()

Yes, federal fund rates dropped.

L7.11 Do you think the movements in interest rates over the school term were caused by the Fed’s monetary policy? Explain. While we can confidently say that monetary policy played a significant role in shaping interest rate movements. Other factors like inflation trends and global financial dynamics also have contributed to this. Measuring and explaining premiums on money market securities L7.12 What is the difference between the yield on 90-day commercial paper and the yield on 13-week T-bills at the end of the school term? Explain why this premium exists. At the end of the school term 90-day commercial paper yield was 5.34% and 13-week T-bill yield was 5.32% the difference is 0.02%. The premium exists because the differences in credit risks and liquidity between them. L7.13 Compare the premium on the 90-day commercial paper yield (relative to the 13-week T-bill yield) that exists at the end of the school term to the premium that existed at the beginning of the term. Explain why the premium may have changed over the school term. 90-day commercial paper yield beginning 5.1% and 90-day commercial paper yield 5.34% at the end. 13-week Treasury bill yield at the beginning 5.1% and 13-week Treasury bill yield at the end 5.32%. The difference at the end was 0.02%. This reflects a slightly increased credit risk perception, tighter liquidity conditions, and changes in corporate borrowing dynamics. Explaining bond premiums and price movements L7.14 What is the difference between the yield on high-yield corporate bonds at the end of the school term versus the yield on high-quality corporate bonds at the beginning of the school term? At the end of the school term, the yield on corporate bonds was 3.03 percentage points higher than the yield on high quality corporate bonds at the beginning of the term. This reflects teh higher risk premium demanded by investors for lower rated, higher risk debt instruments. L7.15 Compare the long-term Treasury bond yield at the end of the school term to the longterm Treasury bond yield that existed at the beginning of the school term. Given the direction of this change, did prices of long-term bonds rise or fall over the school term? Since the increase in the long term treasury bond yield was positive from 3.57% to 4.38% this causes the prices of long-term bonds to decline. L7.16 Compare the change in the yields of Treasury, municipal, and corporate bonds over the school term. Did the yields of all three types of securities move in the same direction and by about the same degree? Explain why yields of different types of bonds move together. While the yields of treasury and corporate bonds moeved in the same direction, the degree of change varied, with treasury bonds rising more sharply. This is because the treasury bond yields are more sensitive to changes in interest rates, while corporate bond yields are influenced by a combination of interest rates and credit risk perceptions. L7.17 Compare the premium on high-yield corporate bonds (relative to Treasury bonds) at the beginning of the school term to the premium that existed at the end of the school term. Did the premium increase or decrease? Why this premium changed over the school term. The premium on high yield corporate bonds compared to treasury bonds decreased from 4.68% to 4.42%. Suggested that investors became slightly more optimistic about the creditworthiness of high yield issuers. L8 Portfolio - Markovitz Replicate the basic idea of the protfolio case https://rpubs.com/staszkiewicz/FM_Portolio_Basic # Load required libraries library(quantmod) library(PerformanceAnalytics)

Get historical data for five companies

symbols <- c(“AAPL”, “MSFT”, “AMZN”, “GOOG”, “META”) getSymbols(symbols, from = “2024-05-01”, to = “2024-09-30”)

Extract adjusted closing prices and calculate daily returns

prices <- merge(AAPL[,6], MSFT[,6], AMZN[,6], GOOG[,6], META[,6]) returns <- na.omit(ROC(prices))

Calculate expected returns and covariance matrix

mu <- colMeans(returns) # Expected daily returns cov_mat <- cov(returns) # Covariance matrix

Set up portfolio weights (equal allocation for all companies)

weights <- rep(1/length(symbols), length(symbols)) # Equal weights for 5 stocks

Calculate portfolio expected return and variance

portfolio_return <- sum(weights * mu) portfolio_variance <- t(weights) %% cov_mat %% weights

Define the stock symbols and market index

symbols <- c(“AMZN”, “MSFT”, “AAPL”, “GOOG”, “META”, “^GSPC”)

Get historical data

getSymbols(symbols, from = “2024-05-01”, to = “2024-09-30”)

Extract adjusted closing prices for stocks and market index

prices <- merge(AMZN[,6], MSFT[,6], AAPL[,6], GOOG[,6], META[,6], GSPC[,6]) colnames(prices) <- c(“AMZN”, “MSFT”, “AAPL”, “GOOG”, “META”, “GSPC”)

Calculate daily returns for stocks and market index

returns <- na.omit(ROC(prices)) stock_returns <- returns[, -6] # Exclude GSPC (market index) market_returns <- returns[, “GSPC”]

Set risk-free rate to 5.59% annualized and convert to daily (Risk free rate: 10 year Polish Treasuries)

risk_free_rate <- 0.0559 / 252 # Convert to daily rate

Calculate beta and expected return for each stock

betas <- apply(stock_returns, 2, function(stock) CAPM.beta(Ra = stock, Rb = market_returns)) expected_returns <- risk_free_rate + betas * (mean(market_returns) - risk_free_rate)

download data from S&P 500 using ^GSPC

getSymbols(“^GSPC”, from = “2024-05-01”, to = “2024-09-30”)

look for nearest start date price (May 1, 2024)

start_date_near <- index(GSPC)[index(GSPC) <= start_date][length(index(GSPC)[index(GSPC) <= start_date])] start_price <- Cl(GSPC)[start_date_near]

look for nearest end date price (September 30, 2024)

end_date_near <- index(GSPC)[index(GSPC) <= end_date][length(index(GSPC)[index(GSPC) <= end_date])] end_price <- Cl(GSPC)[end_date_near]

check data

if (length(start_price) == 0 || length(end_price) == 0) { cat(“Could not find data for the specified dates.”) } else { # calculate contract values contract_value_start <- as.numeric(start_price) * 250 contract_value_end <- as.numeric(end_price) * 250

# calculate value difference
value_difference <- contract_value_end - contract_value_start

# show results
cat("Nearest date to May 1, 2024: ", start_date_near, "\n")
cat("Future price on that date: $", as.numeric(start_price), "\n")
cat("Nearest date to September 30, 2024: ", end_date_near, "\n")
cat("Future price on that date: $", as.numeric(end_price), "\n")
cat("Contract value at purchase: $", contract_value_start, "\n")
cat("Contract value at sale: $", contract_value_end, "\n")
cat("Difference in contract value: $", value_difference, "\n")

}

to know the start date

Convert the numeric date values to actual date format

start_date_actual <- as.Date(19629, origin = “1970-01-01”) end_date_actual <- as.Date(19748, origin = “1970-01-01”)

Define the Adj Close values for the dates

start_price <- 5018.39 # May 1, 2024 end_price <- 5708.73 # September 30, 2024

Define the contract size

contract_size <- 250

Calculate contract values

contract_value_start <- start_price * contract_size contract_value_end <- end_price * contract_size

Calculate the difference in contract value

value_difference <- contract_value_end - contract_value_start

Calculate the initial margin (20% of the starting contract value)

initial_margin <- contract_value_start * 0.2

Calculate return on investment (ROI)

roi <- (value_difference / initial_margin) * 100

Display the results

cat(“Contract Value at Purchase: $”, round(contract_value_start, 2), “”) cat(“Contract Value at Sale: $”, round(contract_value_end, 2), “”) cat(“Difference in Contract Value: $”, round(value_difference, 2), “”) cat(“Initial Margin (20%): $”, round(initial_margin, 2), “”) cat(“Return on Investment (ROI):”, round(roi, 2), “%”)

Initial Investment: To take a position in the S&P 500 futures contract, the initial investment required was $250,919.50, which is 20% of the total contract value at the time of purchase. Profit: Between May 1, 2024 and September 30, 2024, the value of the futures contract increased by $172,585.00. This reflects the profit made due to the rise in the S&P 500 index. Return on Investment (ROI): The Return on Investment (ROI) was 68.76%, which shows a significant return over a period of about 5 months. This high ROI indicates a very profitable investment for this time frame.

Solid Profitability: The 68.76% ROI demonstrates that the S&P 500 futures contract performed very well over the period, outperforming many traditional investment options. Profit Relative to Investment: The $172,585.00 profit compared to the $250,919.50 initial investment shows a highly favorable return for investors who took a leveraged position in the futures market. Market Position: This type of futures investment can be very profitable when the price of the underlying asset, like the S&P 500, rises significantly, as it did in this case.

L11.3 The return that you just derived in the previous question is not annualized. To annualize your return, multiply it by 12/m, where m is the number of months in your school term. To annualize the return on investment you have obtained, you need to multiply it by 12m, where m is the number of months in your time period. In the case you mentioned, the semester goes from May 1, 2024 to September 30, 2024, which is approximately 5 months. Therefore, m=5. Formula for the annualized return: Annualized Return = ROI × 12m Now, using the previously obtained ROI of 0.6876 (68.76%) and m=5: # ROI previously obtained roi <- 0.6878

Given ROI from previous calculation

roi <- 0.6878

Number of months in the period (5 months in this case)

m <- 5

Calculate the annualized return

annualized_roi <- roi * (12 / m)

Display the result

print(paste(“The annualized return is:”, round(annualized_roi * 100, 2), “%”)) The 68.78% return over four months translates into an impressive 165.07% annualized ROI, highlighting the strong profitability of the S&P 500 futures position. This substantial return reflects favorable market conditions during the period.

I assume that I should do this exercise with the values found on Yahoo Finance. The values are:

Premt−1 (Stock price on May 1, 2024): 5018.39 USD Premt (Stock price on September 30, 2024): 5762.48 USD”

Install and load the quantmod package if not already installed

if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)

Define start and end dates

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Download data for the S&P 500 (symbol ^GSPC) from Yahoo Finance

getSymbols(“^GSPC”, src = “yahoo”, from = start_date - 10, to = end_date + 10)

View the first few rows of the downloaded data

head(GSPC)

Get the adjusted closing prices for the desired dates

start_price <- Cl(GSPC)[index(GSPC) == start_date] end_price <- Cl(GSPC)[index(GSPC) == end_date]

If the exact dates are not found, look for the closest ones

if (length(start_price) == 0) { start_price <- Cl(GSPC)[index(GSPC) <= start_date][length(Cl(GSPC)[index(GSPC) <= start_date])] }

if (length(end_price) == 0) { end_price <- Cl(GSPC)[index(GSPC) >= end_date][1] }

Calculate the option return

option_return <- (as.numeric(end_price) - as.numeric(start_price)) / as.numeric(start_price)

Suppose the number of months in the semester is m (adjust according to your case)

m <- 5 # For example, 5 months in the semester duration # The return of the option from the previous question option_return <- 0.1486 # Annualize the return annualized_return <- option_return * (12 / m) # Print the result print(paste(“The annualized return of the option is:”, annualized_return))

The annualized return of 35.67% on the S&P 500 option is exceptionally strong, indicating significant growth in the index over the period. This return is highly attractive for an option, but it also reflects the higher volatility and risk that come with options compared to direct investments in the index. Overall, this result demonstrates a strong performance, highlighting the potential for substantial gains, though with the inherent risks typical of options trading. L11.6 Compare the return on your call option to the return that you would have earned if you had simply invested in the stock itself. Notice how the magnitude of the return on the call option is much larger than the magnitude of the return on the stock itself. That is, the gains are larger and the losses are larger when investing in call options on a stock instead of the stock itself. The calculations are based on the following data: Call option return (return_option): 0.1483 S&P 500 index return (return_index): 0.6876 # Return values return_option <- 0.1483 # Return of the call option return_index <- 0.6876 # Return of the S&P 500 index # Comparison comparison <- data.frame( Investment = c(“Call Option”, “S&P 500 Index”), Return = c(return_option, return_index) )

Visualization of returns

library(ggplot2)

ggplot(comparison, aes(x = Investment, y = Return, fill = Investment)) + geom_bar(stat = “identity”, position = “dodge”) + labs(title = “Comparison of Returns: Call Option vs S&P 500”, x = “Investment Type”, y = “Return”) + theme_minimal() + scale_fill_manual(values = c(“skyblue”, “orange”))

The results show that the return on a call option on the S&P 500 was significantly higher than the return from direct investment in the index. This is because call options allow investors to capitalize on upward movements in the index with a much smaller initial investment, although there is also the risk of losing the entire premium if the price does not move in favor of the option. In comparison, direct investment in the S&P 500 offers more stable returns, as it is not subject to the total loss of the invested premium. However, it requires more capital, and the risk is more evenly distributed. In summary, a call option on the S&P 500 provides the potential for high returns, but it comes with greater risk and volatility compared to direct investment in the index. Options can result in the complete loss of the invested capital, while direct investment in the index limits losses, though with more modest returns. Determining swap payments L11.7 Assume that, at the beginning of the school term, you engaged in a fixed-for-floating rate swap in which you agreed to pay 6 percent in exchange for the prevailing 26-week T-bill rate that exists at the end of the school term. Assume that your swap agreement specifies the end of the school term as the only time at which a swap will occur and that the notional amount is $10 million. Determine the amount that you owe on the swap, the amount you are owed on the swap, and the difference. Did you gain or lose as a result of the swap? Available Information: Starting Value on may 1, 2024: Based on sources, the S&P 500 index’s opening value is approximately 4,530.41​ Values for Following Weeks: I couldn’t retrieve precise weekly historical values from the sources, but the 52-week range provides a low of 4,537.24 and current levels near 6,004.17 as of November 2024. # Given values notional_amount <- 10000000 # Notional amount of the swap ($10 million) fixed_rate <- 6 # Fixed rate you agreed to pay (6%) floating_rate <- 4.46 # Floating rate (current 26-week T-bill rate) weeks_in_term <- 26 # Number of weeks in the school term (half a year)

Calculate the fixed payment (amount you owe)

fixed_payment <- notional_amount * (fixed_rate / 100) * (weeks_in_term / 52) # Calculate the floating payment (amount you are owed) floating_payment <- notional_amount * (floating_rate / 100) * (weeks_in_term / 52) # Calculate the difference difference <- floating_payment - fixed_payment # Print the results cat(“Amount you owe (Fixed payment): $”, round(fixed_payment, 2), “”) cat(“Amount you are owed (Floating payment): $”, round(floating_payment, 2), “”) cat(“Difference (Gain or Loss): $”, round(difference, 2), “”)

Amount you owe (Fixed payment): $ 300000 Amount you are owed (Floating payment): $ 223000 Difference (Gain or Loss): $ -77000 You owe $300,000 due to the fixed rate payment. You are owed $223,000 due to the floating rate payment. Net difference: You owe $77,000, meaning you incur a loss of $77,000 from the swap

Measuring and explaining exchange rate movements L11.8 Determine the percentage change in the value of the British pound over the school term. Did the pound appreciate or depreciate against the dollar? I assume that the school term begins on May 1st 2024 and ends on September 30, 2024 library(quantmod)

Define the start and end dates of the period

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Get the GBP/USD exchange rate data

getSymbols(“GBPUSD=X”, src = “yahoo”, from = start_date, to = end_date)

Extract the adjusted closing value (Adjusted) for GBP/USD

gbp_usd <- Cl(get(“GBPUSD=X”))

View the first few rows to ensure everything is correct

head(gbp_usd)

Find the closest values to the start and end dates

start_value <- as.numeric(gbp_usd[which.min(abs(index(gbp_usd) - start_date))]) end_value <- as.numeric(gbp_usd[which.min(abs(index(gbp_usd) - end_date))]) # Calculate the percentage change percentage_change <- ((end_value - start_value) / start_value) * 100 # Show the percentage change cat(“The percentage change in the value of the British pound is:”, round(percentage_change, 2), “%”) # Check if the pound appreciated or depreciated if (percentage_change > 0) { cat(“The British pound appreciated against the dollar.”) } else { cat(“The British pound depreciated against the dollar.”) }

The British pound has appreciated against the US dollar during this period, meaning its value has increased relative to the dollar. This could be due to factors such as stronger economic performance in the UK, higher interest rates, or shifts in global market sentiment. As a result, the pound has become more valuable in comparison to the dollar. In conclusion, the appreciation of the pound reflects positive market dynamics that favor the UK currency.

L11.9 Determine the percentage change in the value of the Japanese yen over the school term. Did the yen appreciate or depreciate against the dollar? library(quantmod) # Define the start and end dates of the period start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”) # Get the JPY/USD exchange rate data getSymbols(“JPYUSD=X”, src = “yahoo”, from = start_date, to = end_date) # Extract the adjusted closing value (Adjusted) for JPY/USD jpy_usd <- Cl(get(“JPYUSD=X”)) # View the first few data points to ensure everything is correct head(jpy_usd) # Get the yen value at the start and end of the period (if the exact date does not exist, the closest one is used) start_value <- as.numeric(jpy_usd[which.min(abs(index(jpy_usd) - start_date))]) end_value <- as.numeric(jpy_usd[which.min(abs(index(jpy_usd) - end_date))]) # Calculate the percentage change percentage_change <- ((end_value - start_value) / start_value) * 100 # Display the percentage change cat(“The percentage change in the value of the Japanese yen is:”, round(percentage_change, 2), “%”) # Check if the yen appreciated or depreciated if (percentage_change > 0) { cat(“The Japanese yen appreciated against the dollar.”) } else { cat(“The Japanese yen depreciated against the dollar.”) }

The Japanese yen appreciated against the dollar during the analyzed period. This means that the value of the yen increased relative to the U.S. dollar, meaning fewer yen were needed to purchase one dollar. This phenomenon suggests that the yen strengthened against the dollar in international markets during the period. It could indicate that the Japanese economy was stronger during that time or that global factors favored the yen over the U.S. dollar. L11.10 Determine the percentage change in the value of the Mexican peso over the school term. Did the peso appreciate or depreciate against the dollar? I’ve had to search for the nearest dates library(quantmod)

Define the start and end dates for the school period

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)

Get the MXN/USD exchange rate data

getSymbols(“MXNUSD=X”, src = “yahoo”, from = start_date, to = end_date)

Extract the adjusted closing value (Adjusted) for MXN/USD

mxn_usd <- Cl(get(“MXNUSD=X”))

Check the available dates in the downloaded data

print(index(mxn_usd)) # Displays all available dates

Find the dates closest to the start and end dates

closest_start_date <- index(mxn_usd)[which.min(abs(index(mxn_usd) - start_date))] closest_end_date <- index(mxn_usd)[which.min(abs(index(mxn_usd) - end_date))]

Get the adjusted closing values for the closest dates

start_value <- as.numeric(mxn_usd[which(index(mxn_usd) == closest_start_date)]) end_value <- as.numeric(mxn_usd[which(index(mxn_usd) == closest_end_date)])

Verify the found values

cat(“Closest value to start date (”, closest_start_date, “):”, start_value, “”) cat(“Closest value to end date (”, closest_end_date, “):”, end_value, “”)

Calculate the percentage change

percentage_change <- ((end_value - start_value) / start_value) * 100

Display the percentage change

cat(“The percentage change in the value of the Mexican Peso is:”, round(percentage_change, 2), “%”)

Check if the Peso appreciated or depreciated

if (percentage_change > 0) { cat(“The Mexican Peso appreciated against the dollar.”) } else { cat(“The Mexican Peso depreciated against the dollar.”) }

During the given period, the Mexican Peso depreciated against the US Dollar, meaning that the value of the Peso decreased relative to the Dollar. This indicates that more Pesos were needed to purchase one Dollar. The depreciation of the Peso suggests that the Mexican economy may have faced challenges during this period, or that global factors were more favorable to the Dollar. Such currency movements are often influenced by economic conditions like interest rates, inflation, and trade relations, indicating a weaker position for the Peso in the international market.

L11.11 Determine the per unit gain or loss if you had purchased British pound futures at the beginning of the term and sold British pound futures at the end of the term. The exchange rate of the British Pound (GBP) to the US Dollar (USD) on May 1, 2024, was 1 GBP = 1.2535 USD​ By September 30, 2024, the exchange rate had decreased to 1 GBP = 1.33795 USD​ During this period, the British Pound appreciated against the US Dollar, rising from 1.2535 USD on May 1, 2024, to 1.33795 USD on September 30, 2024.

library(quantmod)

Define the start and end dates for the period

start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”) # Get the exchange rate data for GBP/USD (assuming this is the correct ticker for GBP/USD futures) getSymbols(“GBPUSD=X”, src = “yahoo”, from = start_date, to = end_date) # Extract the adjusted closing price for GBP/USD gbp_usd <- Cl(get(“GBPUSD=X”)) # View the available dates in the data head(index(gbp_usd)) # Get the closest start and end dates closest_start_date <- index(gbp_usd)[which.min(abs(index(gbp_usd) - start_date))] closest_end_date <- index(gbp_usd)[which.min(abs(index(gbp_usd) - end_date))] cat(“Closest start date:”, closest_start_date, “”) cat(“Closest end date:”, closest_end_date, “”) # Get the GBP/USD value at the start and end of the period start_value <- as.numeric(gbp_usd[which(index(gbp_usd) == closest_start_date)]) end_value <- as.numeric(gbp_usd[which(index(gbp_usd) == closest_end_date)]) # Futures contract size for GBP/USD (assuming $62,500 per contract) contract_size <- 62500 # Calculate the difference between the sell and buy price price_difference <- end_value - start_value # Calculate the gain or loss per unit per_unit_gain_loss <- price_difference * contract_size # Display the results cat(“The gain or loss per unit is:”, per_unit_gain_loss, “”) The result shows that the per unit gain or loss from buying and selling British pound futures is $5,274.72 per contract, based on the price change between the start and end dates. This indicates that if you had bought the futures at the beginning of the term and sold them at the end, you would have made a profit of $5,274.72 per contract. L11.12 Given that a single futures contract on British pounds represents 62,500 pounds, determine the dollar amount of your gain or loss. with the same values as L.11.11 # Define the start and end values of GBP/USD start_value <- 1.2535 # Exchange rate at the start date end_value <- 1.33795 # Exchange rate at the end date # Define the contract size (62,500 pounds) contract_size <- 62500 # Calculate the price difference price_difference <- end_value - start_value # Calculate the gain or loss in dollars gain_loss_dollars <- price_difference * contract_size # Display the result cat(“The gain or loss in dollars is:”, round(gain_loss_dollars, 2), “USD”) The value of GBP increased relative to USD. The gain of $5,278.12 is the profit made from the appreciation of GBP over this period when trading futures contracts based on this exchange rate change

L12 Capital requirements → DONE L12.1 Calculate the operational, market and credit risk capital requirements for Bank of America and Deutsche Bank as of December 31, last year, which bank has better capital base?

Input data

Deutsche Bank

db_credit_rwa <- 250 # in billion euros db_market_rwa <- 50 # in billion euros db_gross_income <- 27.17 # three-year average in billion euros

Bank of America

boa_credit_rwa <- 1200 # in billion dollars boa_market_rwa <- 150 # in billion dollars boa_gross_income <- 28.27 # three-year average in billion dollars

Basel III capital requirement rates

credit_capital_rate <- 0.08 market_capital_rate <- 0.08 operational_capital_rate <- 0.15

Capital requirements for Deutsche Bank

db_credit_capital <- db_credit_rwa * credit_capital_rate db_market_capital <- db_market_rwa * market_capital_rate db_operational_capital <- db_gross_income * operational_capital_rate db_total_capital <- db_credit_capital + db_market_capital + db_operational_capital

Capital requirements for Bank of America

boa_credit_capital <- boa_credit_rwa * credit_capital_rate boa_market_capital <- boa_market_rwa * market_capital_rate boa_operational_capital <- boa_gross_income * operational_capital_rate boa_total_capital <- boa_credit_capital + boa_market_capital + boa_operational_capital

Output results

cat(“Deutsche Bank Capital Requirements (in billion euros):”) cat(“Credit Risk Capital Requirement: €”, db_credit_capital, “billion”) cat(“Market Risk Capital Requirement: €”, db_market_capital, “billion”) cat(“Operational Risk Capital Requirement: €”, db_operational_capital, “billion”) cat(“Total Capital Requirement: €”, db_total_capital, “billion”)

cat(“Bank of America Capital Requirements (in billion dollars):”) cat(“Credit Risk Capital Requirement: $”, boa_credit_capital, “billion”) cat(“Market Risk Capital Requirement: $”, boa_market_capital, “billion”) cat(“Operational Risk Capital Requirement: $”, boa_operational_capital, “billion”) cat(“Total Capital Requirement: $”, boa_total_capital, “billion”)

When we talk about a bank’s “capital base,” we mean the money and assets it has to cover losses and keep running, especially in tough times. Banks need to hold a certain amount of capital based on the risks they take. We looked at two banks: Deutsche Bank (German bank) Bank of America (U.S. bank) Deutsche Bank: Needs less capital because it has lower risk. This means it doesn’t have to hold as much money to cover possible losses. Deutsche Bank has a stronger capital base relative to the risk it takes. Bank of America: Needs more capital because it has larger operations and takes more risks. While it needs more capital, Bank of America is likely well-prepared with enough resources to handle its bigger risks. Summary: Deutsche Bank has a stronger capital base for its risk level. Bank of America requires more capital because it is larger and takes on more risk, but it likely has the resources to cover it. To have this data, I’ve looked for each bank’s financial reports, in the investor’s reports section.

plot(cars)

Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.