Date of the project: December 1, 2024
Date of the submission: January 8, 2025
We agree to make this project available under a public access license for transparency and educational purposes.
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(xts)
library(zoo)
library(dplyr)
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:xts':
##
## first, last
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
We are going to define the date range for Beginning of Term (BoT) and End of Term (EoT), and initialize the empty data frame:
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
)
Function to add a row to the table_data with error handling
add_row <- function(category, value_beg, value_end = "") {
if (!is.null(value_beg) && !is.na(value_beg) && value_beg != "") {
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
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)) {
sp500_open <- round(as.numeric(first(Op(sp500_data))), 2)
sp500_close <- round(as.numeric(last(Cl(sp500_data))), 2)
add_row("S&P 500 Index Level", sp500_open, sp500_close)
}
if (!is.null(nasdaq_data)) {
nasdaq_open <- round(as.numeric(first(Op(nasdaq_data))), 2)
nasdaq_close <- round(as.numeric(last(Cl(nasdaq_data))), 2)
add_row("Nasdaq Composite Index Level", nasdaq_open, nasdaq_close)
}
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)
Now we are going to add the interests and 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))
}
## Warning: Data for Commercial Paper Rate (90 days) is missing or incomplete.
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))
}
We are fetching 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)
Now, we are going to 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))
}
Fetching 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)
We 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
put_option_premium <- 0.0005
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)
Display the data frame with proper formatting
print(table_data, right = FALSE)
## Category Beginning_of_Term
## 1 S&P 500 Index Level 01 May 2023
## 2 Nasdaq Composite Index Level 01 May 2023
## 3 Prime Rate 01 May 2023
## 4 Federal Funds Rate 01 May 2023
## 5 Certificate of Deposit Rate (3-month) 01 May 2023
## 6 Treasury Bill Rate (13 weeks) 01 May 2023
## 7 Treasury Bill Rate (26 weeks) 01 May 2023
## 8 Treasury Long-term Bond Yield 01 May 2023
## 9 Corporate (Master) Bond Yield 01 May 2023
## 10 High-yield Corporate Bond Yield 01 May 2023
## 11 Exchange Rate of the British Pound (in $) 01 May 2023
## 12 Exchange Rate of the Japanese Yen (in $) 01 May 2023
## 13 Exchange Rate of the Mexican Peso (in $) 01 May 2023
## 14 Treasury Bond Futures 01 May 2023
## 15 S&P 500 Index Futures 01 May 2023
## 16 British Pound Futures 01 May 2023
## 17 Call Option on AAPL - Stock Price 01 May 2023
## 18 Call Option on AAPL - Option Premium 01 May 2023
## 19 Call Option on AAPL - Strike Price 01 May 2023
## 20 Call Option on AAPL - Expiration 01 May 2023
## 21 Put Option on INTC - Stock Price 01 May 2023
## 22 Put Option on INTC - Option Premium 01 May 2023
## 23 Put Option on INTC - Strike Price 01 May 2023
## 24 Put Option on INTC - Expiration 01 May 2023
## 25 Call Option on Euro (EURUSD) - Currency Value 01 May 2023
## 26 Call Option on Euro (EURUSD) - Option Premium 01 May 2023
## 27 Call Option on Euro (EURUSD) - Strike Price 01 May 2023
## 28 Call Option on Euro (EURUSD) - Expiration 01 May 2023
## 29 Put Option on Japanese Yen (JPYUSD) - Currency Value 01 May 2023
## 30 Put Option on Japanese Yen (JPYUSD) - Option Premium 01 May 2023
## 31 Put Option on Japanese Yen (JPYUSD) - Strike Price 01 May 2023
## 32 Put Option on Japanese Yen (JPYUSD) - Expiration 01 May 2023
## End_of_Term Value_Beg Value_End
## 1 30 September 2023 4166.79 4288.05
## 2 30 September 2023 12210.05 13219.32
## 3 30 September 2023 8 8.5
## 4 30 September 2023 5.06 5.33
## 5 30 September 2023 5.14 5.32
## 6 30 September 2023 5.1 5.32
## 7 30 September 2023 4.91 5.32
## 8 30 September 2023 3.57 4.38
## 9 30 September 2023 5.77 6.16
## 10 30 September 2023 8.25 8.8
## 11 30 September 2023 1.2558 1.2205
## 12 30 September 2023 0.007332 0.006696
## 13 30 September 2023 0.055582 0.057016
## 14 30 September 2023 129.66 113.78
## 15 30 September 2023 4185.75 4325.5
## 16 30 September 2023 1.2491 1.2207
## 17 30 September 2023 245
## 18 30 September 2023 10
## 19 30 September 2023 150
## 20 30 September 2023 2024-12-20
## 21 30 September 2023 19.87
## 22 30 September 2023 0.0005
## 23 30 September 2023 50
## 24 30 September 2023 2024-12-20
## 25 30 September 2023 1.0386
## 26 30 September 2023 0.05
## 27 30 September 2023 1.2
## 28 30 September 2023 2024-12-20
## 29 30 September 2023 0.006339
## 30 30 September 2023 0.0005
## 31 30 September 2023 0.009
## 32 30 September 2023 2024-12-20
Download basic statistic of NASDAQ and London Stock Exchange and compare them.
In this exercicse, will download historical data for the NASDAQ Composite and the FTSE 100. Basic statistics (mean, volatility, highs, and lows) will be calculated to compare performance and risk between these markets. This comparison helps investors understand market behavior, assess risks, and make informed investment decisions.
Here, we can see what information can we extract for each calculation:
Mean = Average market level (indicates size and growth).
Standard deviation = Degree of fluctuation (indicates risk and volatility).
Range (maximum and minimum) = Movement amplitude (indicates stability or dynamism).
# 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:")
## [1] "Comparison of FTSE 100 and NASDAQ Composite statistics:"
print(round(stats_comparison, 2))
## Mean Median Std_Dev Min Max
## FTSE 100 8254.22 8247.80 87.41 8008.20 8445.80
## NASDAQ Composite 17356.83 17506.62 656.12 15605.48 18647.45
# 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)
With this values, we can extract the following conclusions:
Here are the conclusions based on the provided text:
Market Growth and Size: The NASDAQ has significantly higher values, reflecting a more dynamic and growing market driven mainly by technology companies. In contrast, the FTSE 100, with lower values, represents a more traditional and stable market.
Risk and Volatility: The NASDAQ shows much greater volatility, implying larger price fluctuations. This can offer higher return opportunities but also comes with greater risk. On the other hand, the FTSE 100, with lower volatility, is more predictable and suitable for conservative investors.
Strategic Decisions:
NASDAQ: Its higher values and volatility make it ideal for investors seeking high returns who are willing to tolerate greater uncertainty.
FTSE 100: With lower values and less volatility, it appeals to those who prefer protecting their capital from significant fluctuations.
We can define each market such as:
The NASDAQ Composite is a technology-heavy index characterized by high growth potential and significant volatility. It offers investors opportunities for higher returns but also carries greater risk due to its exposure to sectors with rapid change and high volatility.
The FTSE 100 represents a stable and traditional market, primarily composed of large, established companies in various industries. It is known for its lower volatility, making it a safer investment option for conservative investors seeking steady returns with reduced risk.
Now, we calculating the correlation between the NASDAQ and FTSE 100 in order to see how closely they move together. If the correlation is high, it means both indices tend to go up and down in the same direction. If it is low, the movements of one do not necessarily match with the other. This helps investors on understanding the risk and make decisions on how to diversify their investments to minimize losses.
# 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)
# Print the rounded correlation
cat("Correlation between FTSE 100 and NASDAQ Composite:", round(correlation, 2), "\n")
## Correlation between FTSE 100 and NASDAQ Composite: -0.14
# Optionally, print the correlation directly if needed
print(round(correlation, 2))
## NASDAQ
## FTSE -0.14
A correlation of -0.14 between the FTSE 100 and the NASDAQ Composite indicates that their relationship is very weak and slightly negative. This suggests that the two markets do not influence each other much, likely because they operate in different regions and focus on different types of companies (FTSE on established UK firms and NASDAQ on U.S. tech companies). Given that the indices aren’t strongly linked, investing in both can help diversify a portfolio. When one is unstable, the other might not be affected much, thereby reducing overall risk. This partial diversification allows investors to spread risk more effectively while recognizing that further diversification with uncorrelated assets is advisable for optimal risk management.
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))
Firstly, we know that 13-week Treasury Bill rate is the interest the government earns for borrowing money over a short period of 13 weeks. It acts as a “price” that investors are willing to pay to lend money to the government, and it is used to measure short-term borrowing costs in the financial market.
We will compare it’s values at the beginning and end of the school term, using the following academic calendar dates:
By using historical data, we can see how the short-term market conditions have changed. Analyzing the differences will help us understand the impact on financing costs and how this might affect both consumers and businesses during the term. We will determine if the rates have increased or decreased and what might be driving these changes.
# 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)
## [1] "TB3MS"
# 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.")
}
}
## [1] "Range of available data: 1934-01-01" "Range of available data: 2024-12-01"
## [1] "Start Rate (closest to 1-May-2024): 5.25"
## [1] "End Rate (closest to 30-Sep-2024): 4.72"
## [1] "Rate difference from start to end of term: -0.53"
The 13-week Treasury Bill rate decreased from 5.25% on May 1, 2024, to 4.72% on September 30, 2024, a reduction of 0.53%. This shows a small decline in short-term interest rates, which 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 suggests that the market expects a more dovish (growth-supporting) stance from the Federal Reserve, possibly due to easing economic factors or inflationary pressures. In the short term, this change is not significant but highlights a shift in the financial environment.
For investors, this decline in the 13-week Treasury Bill rate suggests lower borrowing costs, which can make financing cheaper for businesses and individuals. This can lead to increased investment in equities and other higher-risk assets as investors seek higher returns in a low-interest-rate environment. However, it also indicates caution about the economy’s future, which may affect investment strategies and risk preferences.
Why interest rates change over time?
Interest rates represent the cost of borrowing money. When you borrow, you pay interest; when you save, the bank pays you interest. Interests rates changes because there are several factors influence them, such as:
Central Banks: Central banks control interest rates to manage the economy. They raise rates to curb inflation (when prices rise too quickly) and lower them to stimulate economic growth during tough times.
Inflation: High inflation pressures interest rates to rise because lenders need to protect the real value of their money. Conversely, low inflation leads to lower interest rates as there is less concern about losing money’s value.
Supply and Demand: If many people are seeking loans, interest rates typically go up. If fewer people are borrowing, rates decrease.
Government Borrowing: When the government borrows a lot, it can push interest rates up as it increases the demand for loans.
Global Events: Changes in global markets, decisions in major economies, and currency fluctuations can affect interest rates by altering the supply of and demand for money.
Risk: Higher risk in the economy, such as during a financial crisis, can lead to lower interest rates as lenders seek safer investments.
Why It Matters
- For Borrowers: Higher rates mean more expensive loans.
For Savers: Higher rates lead to better returns on savings.
For Businesses:Interest rates impact the cost of investment and expansion.
Interest rates change primarily because central banks adjust them to control inflation and manage economic growth. They also reflect the supply and demand for money—if more people are borrowing or there’s less money in the system, rates increase. Global factors and risk perceptions also play a significant role in influencing interest rates, as they affect how lenders and borrowers view the future value of money.
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).
In this exercise, we will analyze whether the adverse information released on October 26, 2017 affected Coca-Cola’s stock price. Changes in stock prices reflect how investors reacted to this news and whether it had an impact on the perception of the company’s value and future prospects. By comparing these changes, we can evaluate if the adverse information had significant negative effects on the market for Coca-Cola.
We’ll start looking for the data:
# 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")
## [1] "KO"
# View the downloaded data
head(KO)
## KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted
## 2017-10-02 45.05 45.27 44.75 44.80 10707800 35.65382
## 2017-10-03 44.86 45.26 44.76 45.19 12038100 35.96420
## 2017-10-04 45.11 45.56 44.94 45.50 14060300 36.21092
## 2017-10-05 45.51 45.75 45.50 45.52 10215300 36.22683
## 2017-10-06 45.39 45.52 45.28 45.49 5437900 36.20295
## 2017-10-09 45.55 45.65 45.34 45.41 5268300 36.13930
# Step 2: Convert to a data frame for easier manipulation
ko_data <- data.frame(Date = index(KO), coredata(KO))
head(ko_data)
## Date KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted
## 1 2017-10-02 45.05 45.27 44.75 44.80 10707800 35.65382
## 2 2017-10-03 44.86 45.26 44.76 45.19 12038100 35.96420
## 3 2017-10-04 45.11 45.56 44.94 45.50 14060300 36.21092
## 4 2017-10-05 45.51 45.75 45.50 45.52 10215300 36.22683
## 5 2017-10-06 45.39 45.52 45.28 45.49 5437900 36.20295
## 6 2017-10-09 45.55 45.65 45.34 45.41 5268300 36.13930
# 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:")
## [1] "Filtered Data for October 25-27, 2017:"
print(ko_data_filtered)
## Date KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted
## 1 2017-10-25 46.37 46.76 45.93 46.05 11994200 36.64862
## 2 2017-10-26 46.32 46.75 46.22 46.23 10569100 36.79189
## 3 2017-10-27 46.13 46.33 45.91 46.07 9988000 36.66454
# 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:")
## [1] "Filtered Data with Percentage Change:"
print(ko_data_filtered)
## Date KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted Change
## 1 2017-10-25 46.37 46.76 45.93 46.05 11994200 36.64862 NA
## 2 2017-10-26 46.32 46.75 46.22 46.23 10569100 36.79189 0.390904
## 3 2017-10-27 46.13 46.33 45.91 46.07 9988000 36.66454 -0.346115
Now, we’ll look for the trading and prices evolution:
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()
The increase in trading volume and the slight rise in stock price just before October 26, 2017, suggests that investors may have been anticipating some significant news or event. However, after the information was released, the subsequent decrease in both trading volume and stock price indicates that the market reacted negatively to the news. This suggests that the adverse information on October 26 had a significant impact on Coca-Cola’s stock price and investor sentiment.
Investors were wary of the company’s ability to handle the situation, affecting their confidence in the brand and leading to a decrease in stock value and a reduction in trading activity in the following days. As a result, investors need to be especially cautious and monitor how this news affects the long-term value of their investments in Coca-Cola.
We are going to download to R the Financial statements of Microsoft 2018.
We’ll load the necessary libraries
library(readxl)
library(edgar)
library(dplyr)
library(tidyr)
library(finreportr)
We need to give our mail to Edgar in order to use it’s data in Rpubs studio
options(HTTPUserAgent = "igordros@icloud.com")
In order to download Microsoft annual report, we need to manually download the file from EDGAR sec. Microsofts ticker is MSFT and CIK number is 0000789019. Then we put it into Rpubs.
Load the financial report for Microsoft (Excel file with data)
Financial_Report_Microsoft <- 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)
Commercial bank operations
For the commercial bank that we’ve selected at the beginning of the term, we’ll be using its annual report or any other related information to answer the following questions:
Identify the types of deposits that the commercial bank uses to obtain most of its funds
This Bank has the most of its funds because of :
Interest bearing deposits
Non-interest bearing deposits
Interest bearing deposits (foreign)
Non-interest bearing deposits (foreign)
Identify the main uses of funds by the bank. c. Summarize any statements made by the commercial bank in its annual report about how recent or potential regulations will affect its performance.
Bank mainly invests in federal funds and securities. From Consolidated balance sheet from edgar sec (261,131 million of $ worth of sold securities)
Does it appear that the bank is attempting to enter the securities industry by offering securities services? If so, explain how.
I believe that the bank already sells securities as we can see in ‘Notes to financial statements’ under ‘securities’ they offer various securities. And there are securities for sale so Bank of America does not want to enter the securities market, because it is already in it.
Does it appear that the bank is attempting to enter the insurance industry by offering insurance services? If so, explain how.
Bank of America offers various types of insurances. You can find them in the Financial statement as well.
Commercial bank management
Assess the bank’s balance sheet as well as any comments in its annual report about the gap between its rate-sensitive assets and its rate-sensitive liabilities. Does it appear that the bank has a positive gap or a negative gap?
Bank of America has a significant part of its assets in loans and leases which very often have variable rates. Bank earns on any interest rate rise. On the other side, bank has interest bearing deposits but they mostly have fixed rates. Therefore, I believe that Bank of America has a positive gap between rate-sensitive assets and liabilities.
Determine the bank’s interest income as a percentage of its total assets.
All of the data are taken from official edgar sec page from 10-k Annual Financial statements.
Total Assets from ‘Consolidated Balance sheet’
Total interest income from ‘Consolidated Statement of Income’
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
print(interest_income_percentage)
## [1] 2.835795
In this section we are going through some ETFs and well know companies, to establish what was their equity through the period.
First we are going to see the performance of the S&P 500. to establish a baseline. This needs to be done by getting the data from 2024-05-01, to 2024-09-30 and then plotting in order to see the performance. But, first we need to download the necessary libraries.
library(quantmod)
# Load S&P 500 data
getSymbols("^GSPC", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "GSPC"
# Plot
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()
# Plot
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()
## Tesla
Now we are going to analyze the Tesla company. Doing the same steps that we have done for S&P500, for the next companies we also do the same steps with their own ticker symbol.
# Load Tesla data
getSymbols("TSLA", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "TSLA"
# Plot
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
summary(TSLA$TSLA.Adjusted)
## Index TSLA.Adjusted
## Min. :2024-05-01 Min. :168.5
## 1st Qu.:2024-06-06 1st Qu.:180.0
## Median :2024-07-16 Median :208.5
## Mean :2024-07-15 Mean :208.6
## 3rd Qu.:2024-08-21 3rd Qu.:229.9
## Max. :2024-09-27 Max. :263.3
# Load Microsoft data
getSymbols("MSFT", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "MSFT"
# Plot
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
summary(MSFT$MSFT.Adjusted)
## Index MSFT.Adjusted
## Min. :2024-05-01 Min. :392.7
## 1st Qu.:2024-06-06 1st Qu.:412.9
## Median :2024-07-16 Median :423.7
## Mean :2024-07-15 Mean :425.9
## 3rd Qu.:2024-08-21 3rd Qu.:438.9
## Max. :2024-09-27 Max. :465.8
# Load IBM data
getSymbols("IBM", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "IBM"
# Plot
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
summary(IBM$IBM.Adjusted)
## Index IBM.Adjusted
## Min. :2024-05-01 Min. :160.1
## 1st Qu.:2024-06-06 1st Qu.:167.1
## Median :2024-07-16 Median :180.3
## Mean :2024-07-15 Mean :182.7
## 3rd Qu.:2024-08-21 3rd Qu.:194.5
## Max. :2024-09-27 Max. :221.7
# Load NVIDIA data
getSymbols("NVDA", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "NVDA"
# Plot
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
summary(NVDA$NVDA.Adjusted)
## Index NVDA.Adjusted
## Min. :2024-05-01 Min. : 83.02
## 1st Qu.:2024-06-06 1st Qu.:106.45
## Median :2024-07-16 Median :117.72
## Mean :2024-07-15 Mean :114.62
## 3rd Qu.:2024-08-21 3rd Qu.:124.35
## Max. :2024-09-27 Max. :135.56
L7.1 Difference between corporate high quality bonds and 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 4.38% so 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 the long term bonds because of tax advantage and credit risk differences that are associated with municipal bonds. Interest incomes from municipal bonds are often exempt from federal income taxes, sometimes state and local as well. Municipal bods have been backed by the federal government. Demand from tax-exempt income can lower municipal bond yields.
L7.3 Difference between 26-week T-bill and 13-week T-bill
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 Slope Direction
Downward at the term start, indicating lower future interest rates due to economic slowdown expectations.
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 rate futures?
Taking into account the expectation theory, the market expects lower interest rates. In the scenario, the higher yield reflects the markets belief that interest rates will decline over the next 26 weeks.
L7.6 Interest Rate Movement
Rates did not align fully with expectations, showing divergence between prediction and actual outcome.
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 begining 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 long term treasury bond yield and the 13-week T-bill yield at the end of the term?
The difference at the end is 13-week T-bill 5.32 and the treasury long term bond yield 4.38 the difference being -0.94. the 13 week T-bill being higher.
L7.9 Given your answers to the two previous questions, describe how the yield curve changed over the school term. Explain changes in the 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.
L7.10 Did the Fed change the federal funds rate over the school term?
library(quantmod)
#Get the federal fund rate data from FRED
getSymbols("FEDFUNDS", src = "FRED")
## [1] "FEDFUNDS"
# Subset data of 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)
L7.11 Do you think the movements in interest rates over the
school term were caused by the Feds monetary policy? Explain While we
can 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.
This code posits the idea that investors should construct portfolios based on expected risk, or minimizing risk for a given level of return.
In this case we will calculate the Apple, Microsoft, Amazon, Google and Meta for the given period.
library(PerformanceAnalytics)
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
# Symbols and data
symbols <- c("AAPL", "MSFT", "AMZN", "GOOG", "META")
getSymbols(symbols, from = "2024-05-01", to = "2024-09-30")
## [1] "AAPL" "MSFT" "AMZN" "GOOG" "META"
prices <- merge(AAPL[,6], MSFT[,6], AMZN[,6], GOOG[,6], META[,6])
returns <- na.omit(ROC(prices))
# Portfolio statistics
mu <- colMeans(returns)
cov_mat <- cov(returns)
weights <- rep(1/length(symbols), length(symbols))
portfolio_return <- sum(weights * mu)
portfolio_variance <- t(weights) %*% cov_mat %*% weights
# Results
cat("Portfolio expected return (annualized):", round(portfolio_return * 252 * 100, 2), "%\n")
## Portfolio expected return (annualized): 33.81 %
cat("Portfolio annualized volatility:", round(sqrt(portfolio_variance * 252) * 100, 2), "%\n")
## Portfolio annualized volatility: 19.96 %
The Capital Asset Pricing Model is a model that describes the relationship between the expected return and risk of investing in a security. It shows that the expected return on a security is equal to the risk-free plus a risk premium, which is based on the beta of that security.
#Define the stock symbols and market index
symbols <- c("AMZN", "MSFT", "AAPL", "GOOG", "META", "^GSPC")
#Get the data
getSymbols(symbols, from = "2024-05-01", to = "2024-09-30")
## [1] "AMZN" "MSFT" "AAPL" "GOOG" "META" "GSPC"
#Extract adjusted prices for stock 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 stock 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 of 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)
#Print the results
cat("Betas:\n")
## Betas:
print(betas)
## AMZN MSFT AAPL GOOG META
## 1.416118 1.073079 1.077254 1.210220 1.375356
cat("\nExpected Returns (annualized):\n")
##
## Expected Returns (annualized):
print(round(expected_returns * 252 * 100, 2)) # Annualize and convert to percentage
## AMZN MSFT AAPL GOOG META
## 44.11 34.78 34.89 38.51 43.00
The difference between CAMP and Markowitz is that CAMP is a pricing model for individual assets based on market risk, while Markowitz is a portfolio optomozation method that focuses on diversification to archieve the best risk-return tradeoff.
Replicate the book case of 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:
library(quantmod)
Set User Agent (if necessary for your connection)
options(HTTPUserAgent = "igordros@icloud.com")
Load Microsoft stock data
getSymbols("MSFT")
## [1] "MSFT"
Constants:
outstanding_shares <- 30000000 # Number of outstanding shares
market_cap <- last(MSFT$MSFT.Adjusted) * outstanding_shares
cost_of_debt <- 0.03 # 3%
tax_rate <- 0.25 # 25%
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
market_value_of_debt <- 100e9 # $100 billion
Calculations:
cost_of_equity <- risk_free_rate + beta * market_risk_premium
print(cost_of_equity)
## [1] 0.086
market_cap <- as.numeric(market_cap)
print(market_cap)
## [1] 12671099854
total_market_value <- market_cap + market_value_of_debt
print(total_market_value)
## [1] 112671099854
Total market value = 112,645,000,000 USD
weight_of_debt <- market_value_of_debt / total_market_value
print(weight_of_debt)
## [1] 0.887539
weight_of_equity <- market_cap / total_market_value
print(weight_of_equity)
## [1] 0.112461
WACC calculation
wacc <- (weight_of_debt * cost_of_debt * (1 - tax_rate)) + (weight_of_equity * cost_of_equity)
print(wacc)
## [1] 0.02964127
Output WACC
cat("WACC for Microsoft:", wacc * 100, "%\n")
## WACC for Microsoft: 2.964127 %
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
if (!requireNamespace("quantmod", quietly = TRUE)) {
install.packages("quantmod")
}
library(quantmod)
# define dates
start_date <- as.Date("2024-05-01")
end_date <- as.Date("2024-09-30")
# download data from S&P 500 using ^GSPC
getSymbols("^GSPC", from = "2024-05-01", to = "2024-09-30")
## [1] "GSPC"
# 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.\n")
} 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")
}
## Nearest date to May 1, 2024: 19844
## Future price on that date: $ 5018.39
## Nearest date to September 30, 2024: 19993
## Future price on that date: $ 5738.17
## Contract value at purchase: $ 1254598
## Contract value at sale: $ 1434542
## Difference in contract value: $ 179944.9
# 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")
# Print the actual start and end dates
cat("Nearest date to May 1, 2024: ", start_date_actual, "\n")
## Nearest date to May 1, 2024: 19629
cat("Nearest date to September 30, 2024: ", end_date_actual, "\n")
## Nearest date to September 30, 2024: 19748
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 data:
The ad.close values are: May 1, 2024: 5018.39 September 30, 2024: 5708.73
# Load the required package
library(quantmod)
# Define the analysis dates
start_date <- as.Date("2024-05-01")
end_date <- as.Date("2024-09-30")
# Download data for the S&P 500 index (^GSPC)
getSymbols("^GSPC", src = "yahoo", from = "2024-05-01", to = "2024-09-30")
## [1] "GSPC"
# Check if the data was downloaded successfully
if (exists("GSPC") && nrow(GSPC) > 0) {
# Find the closest price to the start date
start_date_near <- index(GSPC)[which.max(index(GSPC) <= start_date)]
start_price <- Cl(GSPC[start_date_near])
# Find the closest price to the end date
end_date_near <- index(GSPC)[which.max(index(GSPC) <= end_date)]
end_price <- Cl(GSPC[end_date_near])
# Calculate contract values
contract_value_start <- as.numeric(start_price) * 250
contract_value_end <- as.numeric(end_price) * 250
# Calculate the difference in contract value
value_difference <- contract_value_end - contract_value_start
# Display results
cat("Nearest date to May 1, 2024: ", start_date_near, "\n")
cat("Future price on that date: $", round(as.numeric(start_price), 2), "\n")
cat("Nearest date to September 30, 2024: ", end_date_near, "\n")
cat("Future price on that date: $", round(as.numeric(end_price), 2), "\n")
cat("Contract value at purchase: $", round(contract_value_start, 2), "\n")
cat("Contract value at sale: $", round(contract_value_end, 2), "\n")
cat("Difference in contract value: $", round(value_difference, 2), "\n")
} else {
# Error message if data cannot be retrieved
cat("Could not retrieve data for the specified dates.\n")
}
## Nearest date to May 1, 2024: 19844
## Future price on that date: $ 5018.39
## Nearest date to September 30, 2024: 19844
## Future price on that date: $ 5018.39
## Contract value at purchase: $ 1254598
## Contract value at sale: $ 1254598
## Difference in contract value: $ 0
# Convert numeric values to actual dates
start_date_actual <- as.Date(19629, origin = "1970-01-01")
end_date_actual <- as.Date(19748, origin = "1970-01-01")
# Display the actual dates
cat("Nearest date to May 1, 2024: ", start_date_actual, "\n")
## Nearest date to May 1, 2024: 19629
cat("Nearest date to September 30, 2024: ", end_date_actual, "\n")
## Nearest date to September 30, 2024: 19748
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.
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 12/m, 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), "%"))
## [1] "The annualized return is: 165.07 %"
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.
Assume that you purchased a call option (representing 100 shares) on the specific stock that you identified of this project. What was your return from purchasing this option? [Your return can be measured as (Premt − Premt−1)/Premt−1 , where Premt−1 represents the premium paid at the beginning of the school term and Premt represents the premium at which the same option can be sold at the end of the school term.] If the premium for this option is not quoted at the end of the school term, measure the return as if you had exercised the call option at the end of the school term (assuming that it is feasible to exercise the option at that time). That is, the return is based on purchasing the stock at the option’s strike price and then selling the stock at its market price at the end of the school term.
In this exercise, we will analyze the return of a call option representing 100 shares, using stock price data obtained from Yahoo Finance. A call option is a contract that gives the holder the right, but not the obligation, to buy a stock at a fixed price before a specified date, often used to speculate on price increases. We will use the stock prices at the beginning and end of the school term to calculate the return and assess the potential profitability of the investment.
The values are:
# 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)
## [1] "GSPC"
# 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]
}
# Print the obtained prices (convert xts objects to numeric values)
cat("Price on May 1, 2024:", as.numeric(start_price), "\n")
## Price on May 1, 2024: 5018.39
cat("Price on September 30, 2024:", as.numeric(end_price), "\n")
## Price on September 30, 2024: 5762.48
# Calculate the option return
option_return <- (as.numeric(end_price) - as.numeric(start_price)) / as.numeric(start_price)
# Print the return as a percentage
cat("The return on the option is:", round(option_return * 100, 2), "%\n")
## The return on the option is: 14.83 %
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 14.83% increase in the S&P 500 index suggests that investors who invested in this market saw significant gains over a five-month period. It indicates that the market has grown and been favorable for those who invested during this time.
However, it also highlights that, although there was good performance, investors must be prepared for volatility and risks that can impact stock prices in the short term.
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.
To annualize the return of the option, we will multiply the return obtained in the previous question by 12 and then divide the result by the number of months in the school term (five months in this case). This will give us the annual equivalent return, showing how the return would look if it were sustained over an entire year.
The previous return was from 14.83%.
# Number of months in the semester is m
m <- 5 # 5 months in the semester duration
# The return of the option from the previous question
option_return <- 0.1483
# Annualize the return
annualized_return <- option_return * (12 / m)
# Print the result
print(paste("The annualized return of the option is:", annualized_return))
## [1] "The annualized return of the option is: 0.35592"
The annualized return of 35.59% on the S&P 500 option is exceptionally strong, indicating significant growth in the index over the period. This return reflects a highly attractive opportunity for investors, but it also underscores the volatility and higher risk associated with options trading compared to direct investments in the index. This result demonstrates a strong performance, highlighting the potential for substantial gains while also emphasizing the inherent risks and volatility typical of options.
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
These results are due to the fact that the returns from a call option are leveraged, meaning they can amplify gains when the underlying asset performs well. However, this leverage also magnifies losses if the asset’s price does not move in the expected direction. Therefore, while offering higher potential returns, call options come with a greater level of risk due to these amplified gains and losses.
# 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 the comparison
print("Comparison of Returns:")
## [1] "Comparison of Returns:"
print(comparison)
## Investment Return
## 1 Call Option 0.1483
## 2 S&P 500 Index 0.6876
# 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)
## [1] "The return on the S&P 500 index is larger in magnitude compared to the call option return."
In this case, we can se that stock’s return is higher than the calls one. We’ll try to explain why is still better the call’s option with an example:
If we invest directly in stocks, we need a lot of money because we buy the full value of those shares. In this case, to earn a 68.76% return with a stock investment, you must invest a large amount upfront.
On the other hand, a call option lets you control those same shares by paying only a small percentage of their price (called the premium). This means that even though the percentage return might be lower, we can make good profits with a much smaller initial investment. However, if the price doesn’t rise enough, we could lose the entire premium, which makes it riskier.
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?
Firstly, we have to know that a fixed-for-floating rate swap is a financial agreement where one party pays a fixed interest rate on a loan or debt, while receiving payments based on a variable interest rate (which can change over time). This helps companies manage interest rate risk and protect against potential increases in interest payments.
So now, we’ll calculate the amount owed and received on a fixed-for-floating rate swap based on the prevailing 26-week T-bill rate at the end of the school term, and determine if we gained or lost money from this swap by comparing the fixed rate agreed to pay with the actual rate that occurred.
Available Information:
To find the closing value, we have searched Yahoo Finances for the weekly historical values of the S&P 500.
The starting value as of May 1, 2024 is: 4,136.25
The closing value as of September 30, 2024 is: 5,738.17
# Given values
notional_amount <- 10000000 # Notional amount ($10 million)
fixed_rate <- 6 # Fixed rate (6%)
floating_rate <- 5.57 # Floating rate (26-week T-bill rate at the end of the term)
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), "\n")
## Amount you owe (Fixed payment): $ 3e+05
cat("Amount you are owed (Floating payment): $", round(floating_payment, 2), "\n")
## Amount you are owed (Floating payment): $ 278500
cat("Difference (Gain or Loss): $", round(difference, 2), "\n")
## Difference (Gain or Loss): $ -21500
if (difference > 0) {
cat("Result: You gained on the swap.\n")
} else if (difference < 0) {
cat("Result: You lost on the swap.\n")
} else {
cat("Result: No gain or loss on the swap.\n")
}
## Result: You lost on the swap.
In conclusion, the fixed-for-floating rate swap resulted in a loss of $21,500 due to the floating rate being lower than the agreed fixed rate of 6%. This highlights the risk associated with such financial instruments, where outcomes depend heavily on interest rate fluctuations. For investors, this case underscores the importance of accurately predicting market trends before entering into swaps. While swaps can be useful for hedging or speculation, they carry inherent risks that must be carefully considered.
Determine the percentage change in the value of the British pound over the school term. Did the pound appreciate or depreciate against the dollar?
We 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)
## [1] "GBPUSD=X"
# 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)
## GBPUSD=X.Close
## 2024-04-30 1.249016
## 2024-05-01 1.253934
## 2024-05-02 1.254060
## 2024-05-05 1.254107
## 2024-05-06 1.255982
## 2024-05-07 1.250141
# 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), "%\n")
## The percentage change in the value of the British pound is: 6.73 %
# Check if the pound appreciated or depreciated
if (percentage_change > 0) {
cat("The British pound appreciated against the dollar.\n")
} else {
cat("The British pound depreciated against the dollar.\n")
}
## The British pound appreciated 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. For investors, this appreciation means higher returns on investments denominated in pounds when converted back to dollars, but it may also indicate increased costs for US-based investors looking to invest in the UK. In conclusion, the appreciation of the pound reflects positive market dynamics that favor the UK currency while presenting opportunities and challenges for global investors.
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)
## [1] "JPYUSD=X"
# 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)
## JPYUSD=X.Close
## 2024-04-30 0.006340269
## 2024-05-01 0.006422443
## 2024-05-02 0.006534026
## 2024-05-05 0.006511858
## 2024-05-06 0.006483529
## 2024-05-07 0.006462119
# 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), "%\n")
## The percentage change in the value of the Japanese yen is: 9.05 %
# Check if the yen appreciated or depreciated
if (percentage_change > 0) {
cat("The Japanese yen appreciated against the dollar.\n")
} else {
cat("The Japanese yen depreciated against the dollar.\n")
}
## The Japanese yen appreciated 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.
Determine the percentage change in the value of the Mexican peso over the school term. Did the peso appreciate or depreciate against the dollar?
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)
## [1] "MXNUSD=X"
# 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
## [1] "2024-04-30" "2024-05-01" "2024-05-02" "2024-05-05" "2024-05-06"
## [6] "2024-05-07" "2024-05-08" "2024-05-09" "2024-05-12" "2024-05-13"
## [11] "2024-05-14" "2024-05-15" "2024-05-16" "2024-05-19" "2024-05-20"
## [16] "2024-05-21" "2024-05-22" "2024-05-23" "2024-05-26" "2024-05-27"
## [21] "2024-05-28" "2024-05-29" "2024-05-30" "2024-06-02" "2024-06-03"
## [26] "2024-06-04" "2024-06-05" "2024-06-06" "2024-06-09" "2024-06-10"
## [31] "2024-06-11" "2024-06-12" "2024-06-13" "2024-06-16" "2024-06-17"
## [36] "2024-06-18" "2024-06-19" "2024-06-20" "2024-06-23" "2024-06-24"
## [41] "2024-06-25" "2024-06-26" "2024-06-27" "2024-06-30" "2024-07-01"
## [46] "2024-07-02" "2024-07-03" "2024-07-04" "2024-07-07" "2024-07-08"
## [51] "2024-07-09" "2024-07-10" "2024-07-11" "2024-07-14" "2024-07-15"
## [56] "2024-07-16" "2024-07-17" "2024-07-18" "2024-07-21" "2024-07-22"
## [61] "2024-07-23" "2024-07-24" "2024-07-25" "2024-07-28" "2024-07-29"
## [66] "2024-07-30" "2024-07-31" "2024-08-01" "2024-08-04" "2024-08-05"
## [71] "2024-08-06" "2024-08-07" "2024-08-08" "2024-08-11" "2024-08-12"
## [76] "2024-08-13" "2024-08-14" "2024-08-15" "2024-08-18" "2024-08-19"
## [81] "2024-08-20" "2024-08-21" "2024-08-22" "2024-08-25" "2024-08-26"
## [86] "2024-08-27" "2024-08-28" "2024-08-29" "2024-09-01" "2024-09-02"
## [91] "2024-09-03" "2024-09-04" "2024-09-05" "2024-09-08" "2024-09-09"
## [96] "2024-09-10" "2024-09-11" "2024-09-12" "2024-09-15" "2024-09-16"
## [101] "2024-09-17" "2024-09-18" "2024-09-19" "2024-09-22" "2024-09-23"
## [106] "2024-09-24" "2024-09-25" "2024-09-26" "2024-09-29"
# 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, "\n")
## Closest value to start date ( 19844 ): 0.05907163
cat("Closest value to end date (", closest_end_date, "):", end_value, "\n")
## Closest value to end date ( 19995 ): 0.05094114
# 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), "%\n")
## The percentage change in the value of the Mexican Peso is: -13.76 %
# Check if the Peso appreciated or depreciated
if (percentage_change > 0) {
cat("The Mexican Peso appreciated against the dollar.\n")
} else {
cat("The Mexican Peso depreciated against the dollar.\n")
}
## 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.
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:
By September 30, 2024, the exchange rate had decreased to
During this period, the British Pound appreciated against the US Dollar, rising from
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)
## [1] "GBPUSD=X"
# 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))
## [1] "2024-04-30" "2024-05-01" "2024-05-02" "2024-05-05" "2024-05-06"
## [6] "2024-05-07"
# 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, "\n")
## Closest start date: 19844
cat("Closest end date:", closest_end_date, "\n")
## Closest end date: 19995
# 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, "\n")
## The gain or loss per unit is: 5274.72
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.
Given that a single futures contract on British pounds represents 62,500 pounds, determine the dollar amount of your gain or loss.
We’ll be working with the same values as in point L11.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\n")
## The gain or loss in dollars is: 5278.12 USD
We can see that tjhere is a gain of $5,278.12, which is the profit made from the appreciation of GBP over this period when trading futures contracts based on this exchange rate change.
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?
Firstly, we have to know what each risk means:
Operational Risk: Addresses unexpected losses from failed internal processes, people, systems, and external events. This is about ensuring the bank’s ability to absorb disruptions not caused by market conditions.
Market Risk: Focuses on exposure to market movements and fluctuations, such as changes in interest rates, currency exchange rates, and commodity prices. It’s about managing risk from external market conditions.
Credit Risk: Ensures the bank holds adequate capital to cover potential losses from the default of loans and other credit exposures. It relates directly to the creditworthiness of borrowers and the financial stability of the bank’s loan portfolio.
To be able to do the calculations, we’ve looked for each bank’s financial reports, in the investor’s reports section.
We’ll input the data and make the calculations for each bank:
# 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):\n",
"Credit Risk Capital Requirement: €", db_credit_capital, "billion\n",
"Market Risk Capital Requirement: €", db_market_capital, "billion\n",
"Operational Risk Capital Requirement: €", db_operational_capital, "billion\n",
"Total Capital Requirement: €", db_total_capital, "billion\n")
## Deutsche Bank Capital Requirements (in billion euros):
## Credit Risk Capital Requirement: € 20 billion
## Market Risk Capital Requirement: € 4 billion
## Operational Risk Capital Requirement: € 4.0755 billion
## Total Capital Requirement: € 28.0755 billion
In order to make a further comparision, we’ll pass this values to dolars, in order to have all the values in the same currency.
We’ll use the following exchange rate: 1 euro = 1.10 dolars
# Deutsche Bank values in euros calculated before
db_credit_capital <- 20 # in euros
db_market_capital <- 4 # in euros
db_operational_capital <- 4.0755 # in euros
db_total_capital <- 28.0755 # in euros
euro_to_usd <- 1.10
#Output in dolars
cat("Deutsche Bank Capital Requirements (in billion dollars):\n",
"Credit Risk Capital Requirement: $", db_credit_capital * euro_to_usd, "billion\n",
"Market Risk Capital Requirement: $", db_market_capital * euro_to_usd, "billion\n",
"Operational Risk Capital Requirement: $", db_operational_capital * euro_to_usd, "billion\n",
"Total Capital Requirement: $", db_total_capital * euro_to_usd, "billion\n")
## Deutsche Bank Capital Requirements (in billion dollars):
## Credit Risk Capital Requirement: $ 22 billion
## Market Risk Capital Requirement: $ 4.4 billion
## Operational Risk Capital Requirement: $ 4.48305 billion
## Total Capital Requirement: $ 30.88305 billion
cat("Bank of America Capital Requirements (in billion dollars):\n",
"Credit Risk Capital Requirement: $", boa_credit_capital, "billion\n",
"Market Risk Capital Requirement: $", boa_market_capital, "billion\n",
"Operational Risk Capital Requirement: $", boa_operational_capital, "billion\n",
"Total Capital Requirement: $", boa_total_capital, "billion\n")
## Bank of America Capital Requirements (in billion dollars):
## Credit Risk Capital Requirement: $ 96 billion
## Market Risk Capital Requirement: $ 12 billion
## Operational Risk Capital Requirement: $ 4.2405 billion
## Total Capital Requirement: $ 112.2405 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.
The information we extract for each bank is:
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.
We can conclude that Deutsche Bank focuses more on covering operational and regulatory risks, while Bank of America is more exposed to changes in financial markets. This means Deutsche Bank may be more stable in terms of internal risks but has less capacity to handle market volatility.
In contrast, Bank of America, with its higher market risk capital requirement, shows greater ability to absorb losses in volatile situations, but also faces a higher risk from market fluctuations.