#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")
}
}
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) }) }
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)
}
update_data()
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
if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
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)
ftse_close <- na.omit(Cl(ftse_data)) # Adjusted closing prices for FTSE nasdaq_close <- na.omit(Cl(nasdaq_data)) # Adjusted closing prices for NASDAQ
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) )
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) )
stats_comparison <- rbind( “FTSE 100” = lond_stats, “NASDAQ Composite” = nasdaq_stats )
print(“Comparison of FTSE 100 and NASDAQ Composite statistics:”) print(round(stats_comparison, 2))
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.
if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
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)
ftse_close <- na.omit(Cl(ftse_data)) # Remove missing values from FTSE nasdaq_close <- na.omit(Cl(nasdaq_data)) # Remove missing values from NASDAQ
aligned_data <- merge(ftse_close, nasdaq_close, all = FALSE) colnames(aligned_data) <- c(“FTSE”, “NASDAQ”)
correlation <- cor(aligned_data\(FTSE, aligned_data\)NASDAQ)
cat(“Correlation between FTSE 100 and NASDAQ Composite:”, round(correlation, 2), “”)
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/TclB3MS → https://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)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
getSymbols(“TB3MS”, src = “FRED”, auto.assign = TRUE)
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)
getSymbols(“KO”, from = “2017-10-01”, to = “2017-11-01”)
head(KO)
ko_data <- data.frame(Date = index(KO), coredata(KO)) head(ko_data)
library(dplyr) ko_data_filtered <- ko_data %>% filter(Date >= as.Date(“2017-10-25”) & Date <= as.Date(“2017-10-27”))
print(“Filtered Data for October 25-27, 2017:”) print(ko_data_filtered)
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)
getSymbols(“KO”, from = “2017-10-01”, to = “2017-11-01”)
ko_data <- data.frame(Date = index(KO), coredata(KO))
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)
options(HTTPUserAgent = “igordros@icloud.com”)
Financial_Report_Microsoft <- read_excel(“Financial_Report.xlsx”)
Financial_Report <- read_excel(“Financial_Report.xlsx”)
View(Financial_Report)
BankofAmerica <- GetBalanceSheet(‘BAC’, 2018)
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)”)
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)”)
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.”)
cat(“L5.4”) cat(“Bank of America offers various types of insurances. You can find them in the Financial statement as well.”)
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.”)
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, “%”)
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, “%”)
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, “%”)
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, “%”)
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%”)
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%”)
cat(“L5.13”) cat(“Interest income – positive impact, because bank would earn more on loans and investments”)
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.”)
cat(“L5.15”) cat(“The S&P 500 mutual fund is a moderate risk investment due to its diversification across 500 large companies.”)
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%”)
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.”)
cat(“L5.18”) cat(“Vanguard charges $25 for each brokerage account and 0.25% to 1% of transaction value depending on the amount.”)
cat(“L5.19”) cat(“The expense ratio is 0.04 = 4%. You can see this on the Vanguard website.”)
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.”)
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.”)
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
library(quantmod)
getSymbols(“^GSPC”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)
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()
summary(GSPC$GSPC.Adjusted)
head(GSPC)
TESLA
library(quantmod)
getSymbols(“TSLA”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)
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()
summary(TSLA$TSLA.Adjusted)
head(TSLA)
MICROSOFT
library(quantmod)
getSymbols(“MSFT”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)
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()
summary(MSFT$MSFT.Adjusted)
head(MSFT)
IBM
library(quantmod)
getSymbols(“IBM”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)
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()
summary(IBM$IBM.Adjusted)
head(IBM)
NVIDIA
library(quantmod)
getSymbols(“NVDA”, src = “yahoo”, from = “2024-05-01”, to = “2024-09-30”)
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()
summary(NVDA$NVDA.Adjusted)
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?
library(quantmod)
getSymbols(“FEDFUNDS”, src = “FRED”)
fed_subset <- window(FEDFUNDS, start = as.Date(“2024-05-01”), end = as.Date(“2024-09-30”))
plot(fed_subset, main = “Federal Funds Rate (May 2024 - September 2024)”, ylab = “Federal Funds Rate (%)”, xlab = “Date”, col = “blue”, lwd = 2)
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)
symbols <- c(“AAPL”, “MSFT”, “AMZN”, “GOOG”, “META”) getSymbols(symbols, from = “2024-05-01”, to = “2024-09-30”)
prices <- merge(AAPL[,6], MSFT[,6], AMZN[,6], GOOG[,6], META[,6]) returns <- na.omit(ROC(prices))
mu <- colMeans(returns) # Expected daily returns cov_mat <- cov(returns) # Covariance matrix
weights <- rep(1/length(symbols), length(symbols)) # Equal weights for 5 stocks
portfolio_return <- sum(weights * mu) portfolio_variance <- t(weights) %% cov_mat %% weights
print(paste(“Portfolio expected return (annualized):”, round(portfolio_return * 252 * 100, 2), “%”)) print(paste(“Portfolio annualized volatility:”, round(sqrt(portfolio_variance * 252) * 100, 2), “%”))
AAPL[,6], MSFT[,6], AMZN[,6], GOOG[,6], META[,6] L9 Portfolio - CAMP # Load required libraries library(quantmod) library(PerformanceAnalytics)
symbols <- c(“AMZN”, “MSFT”, “AAPL”, “GOOG”, “META”, “^GSPC”)
getSymbols(symbols, from = “2024-05-01”, to = “2024-09-30”)
prices <- merge(AMZN[,6], MSFT[,6], AAPL[,6], GOOG[,6], META[,6], GSPC[,6]) colnames(prices) <- c(“AMZN”, “MSFT”, “AAPL”, “GOOG”, “META”, “GSPC”)
returns <- na.omit(ROC(prices)) stock_returns <- returns[, -6] # Exclude GSPC (market index) market_returns <- returns[, “GSPC”]
risk_free_rate <- 0.0559 / 252 # Convert to daily rate
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)
cat(“Betas:”) print(betas)
cat(“Returns (annualized):”) print(round(expected_returns * 252 * 100, 2)) # Annualize and convert to percentage
State the difference between CAMP and Markovitz
L10 WACC WACC (weighted average cost of capital) - can be measured at market values and accounting values. You cannot mix them up. They are completely different in a way for counting, so if you mix them up you will get incorrect result that may be misleading. At market values you need both equity and debt of company and the cost of equity and the cost of debt. This measure tells the investors the rate of return they might expect with how much risk they would bare on their investment. #Example: getSymbols(“MSFT”) oustanding_shares<- 30000000 #note: you might use the current volume instant as the instrument for. market_cap <- last(MSFT$MSFT.Adjusted) * oustanding_shares cost_of_debt <- 0.03 # 3% tax_rate <- 0.25 # 25% tax rate beta <- 1.1 # Beta of Microsoft’s stock risk_free_rate <- 0.02 # 2% risk-free rate market_risk_premium <- 0.06 # 6% market risk premium cost_of_equity <- risk_free_rate + beta * market_risk_premium market_value_of_debt <- 100e9 # $100 billion total_market_value <- market_cap + market_value_of_debt weight_of_debt <- market_value_of_debt / total_market_value weight_of_equity <- market_cap / total_market_value wacc <- (weight_of_debt * cost_of_debt * (1 - tax_rate)) + (weight_of_equity * cost_of_equity) cat(“WACC for Microsoft:”, wacc * 100, “%”) WACC for Microsoft: 2.965762 %
L11 Derivatives → DONE L11.1 Assume that you purchased an S&P 500 futures contract at the beginning of the school term, with the first settlement date beyond the end of the school term. Also assume that you sold an S&P 500 futures contract with this same settlement date at the end of the school term. Given that this contract has a value of the futures price times $250, determine the difference between the dollar value of the contract you sold and the dollar amount of the contract that you purchased. As with those dates I wasn’t having results, I’ve searched for near dates, ending using Nearest date to May 1, 2024: 2024-05-01 Nearest date to September 30, 2024: 2024-09-30 # define dates start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
getSymbols(“^GSPC”, from = “2024-05-01”, to = “2024-09-30”)
start_date_near <- index(GSPC)[index(GSPC) <= start_date][length(index(GSPC)[index(GSPC) <= start_date])] start_price <- Cl(GSPC)[start_date_near]
end_date_near <- index(GSPC)[index(GSPC) <= end_date][length(index(GSPC)[index(GSPC) <= end_date])] end_price <- Cl(GSPC)[end_date_near]
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")
}
start_date_actual <- as.Date(19629, origin = “1970-01-01”) end_date_actual <- as.Date(19748, origin = “1970-01-01”)
cat(“Nearest date to May 1, 2024:”, start_date_actual, “”) cat(“Nearest date to September 30, 2024:”, end_date_actual, “”)
L11.2 Assume that you invested an initial margin of 20 percent of the amount that you would owe to purchase the S&P 500 index at the settlement date. Measure your return from taking a position in the S&P 500 index futures as follows. Take the difference determined in the previous question (which represents the dollar amount of the gain on the futures position) and divide it by the amount you originally invested (the amount you originally invested is 20 percent of the dollar value of the futures contract that you purchased). Given that the gain or difference in the contract value is $ 179944.9, I will calculate the return on investment (ROI) assuming an initial margin of 20% of the initial contract value. I will use the nearest dates, in this case 29th September 2023. I couldn’t install the tidyquant package, so I had to look up the value directly on Yahoo Finance. This is the screenshot that shows the values.” The ad.close values are: May 1, 2024: 5018.39 September 30, 2024: 5708.73
start_price <- 5018.39 # May 1, 2024 end_price <- 5708.73 # September 30, 2024
contract_size <- 250
contract_value_start <- start_price * contract_size contract_value_end <- end_price * contract_size
value_difference <- contract_value_end - contract_value_start
initial_margin <- contract_value_start * 0.2
roi <- (value_difference / initial_margin) * 100
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
roi <- 0.6878
m <- 5
annualized_roi <- roi * (12 / m)
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”
if (!require(quantmod)) install.packages(“quantmod”, dependencies = TRUE) library(quantmod)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
getSymbols(“^GSPC”, src = “yahoo”, from = start_date - 10, to = end_date + 10)
start_price <- Cl(GSPC)[index(GSPC) == start_date] end_price <- Cl(GSPC)[index(GSPC) == end_date]
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] }
cat(“Price on May 1, 2024:”, as.numeric(start_price), “”) cat(“Price on September 30, 2024:”, as.numeric(end_price), “”)
option_return <- (as.numeric(end_price) - as.numeric(start_price)) / as.numeric(start_price)
cat(“The return on the option is:”, round(option_return * 100, 2), “%”)
The return on the option from May 1, 2024 to September 30, 2024 is approximately 14.83%. This means the price of the S&P 500 index increased by 14.83% over this five-month period. This increase suggests that the option has gained in value, likely due to favorable market movements for the underlying asset (e.g., the stock index), which could lead to higher premiums for the option. Overall, this is a positive return, meaning the strategy of purchasing the option has been profitable.
L11.5 Annualize the return on your option by multiplying the return you derived in the previous question by 12/m, where m represents the number of months in your school term.
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) )
print(“Comparison of Returns:”) print(comparison) # Conclusion: Magnitude of the return if (abs(return_option) > abs(return_index)) { conclusion <- “The return on the call option is larger in magnitude compared to the S&P 500 index return.” } else { conclusion <- “The return on the S&P 500 index is larger in magnitude compared to the call option return.” }
print(conclusion)
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)
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)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
getSymbols(“GBPUSD=X”, src = “yahoo”, from = start_date, to = end_date)
gbp_usd <- Cl(get(“GBPUSD=X”))
head(gbp_usd)
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)
start_date <- as.Date(“2024-05-01”) end_date <- as.Date(“2024-09-30”)
getSymbols(“MXNUSD=X”, src = “yahoo”, from = start_date, to = end_date)
mxn_usd <- Cl(get(“MXNUSD=X”))
print(index(mxn_usd)) # Displays all available 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))]
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)])
cat(“Closest value to start date (”, closest_start_date, “):”, start_value, “”) cat(“Closest value to end date (”, closest_end_date, “):”, end_value, “”)
percentage_change <- ((end_value - start_value) / start_value) * 100
cat(“The percentage change in the value of the Mexican Peso is:”, round(percentage_change, 2), “%”)
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)
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?
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
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
credit_capital_rate <- 0.08 market_capital_rate <- 0.08 operational_capital_rate <- 0.15
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
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
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.