0% found this document useful (0 votes)
26 views8 pages

Financial Calc

The document outlines a comprehensive analysis of stock data from 2001 to 2018, including the calculation of log and simple returns, sample means, and covariance matrices. It also explores portfolio optimization techniques, such as calculating the efficient frontier and minimum variance portfolios using R programming. Additionally, it provides methods for achieving a target return using a tangency portfolio approach.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views8 pages

Financial Calc

The document outlines a comprehensive analysis of stock data from 2001 to 2018, including the calculation of log and simple returns, sample means, and covariance matrices. It also explores portfolio optimization techniques, such as calculating the efficient frontier and minimum variance portfolios using R programming. Additionally, it provides methods for achieving a target return using a tangency portfolio approach.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

---

title: "Financial Calculus qn 1"


author: "FinFemme Codes"
date: "2024-11-22"
output:
pdf_document: default
html_document: default
word_document: default
---

```{R}
install.packages("quantmod")
install.packages("tidyquant")
library(quantmod)
library(tidyquant)
```
```{R}
all_stocks<-
c("MSFT","AAPL","INTC","KO","PEP","UL","JNJ","XOM","CL","IBM")
set.seed(123)
selected_stocks<-sample(all_stocks,10)
print(selected_stocks)
```
```{R}
#defining the date range
start_date<-"2001-01-01"
end_date<-"2018-12-31"
```

```{R}
#downloading the data from Yahoo Finance
stock_data<-tq_get(selected_stocks,
from=start_date,
to=end_date,
get="stock.prices")
```

```{R}
head(stock_data)
write.csv(stock_data,"stock_data_2001_2018,csv",row.names=FALSE)
str(stock_data)
View(stock_data)
```
#Part a
#(i)Graphing the log prices
```{R}
library(ggplot2)
library(dplyr)
stock_data<-stock_data %>%
mutate(log_price=log(adjusted))
ggplot(stock_data,aes(x=date,y=log_price,color=symbol))+
geom_line()+
labs(title="Log adjusted closing prices for the 10 stocks from 2001 to
2018",
x="Date",
y="log-adjusted closing prices")+
theme_gray()+
theme(legend.position="bottom")+
facet_wrap(~symbol,scales = 'free_y')+
scale_x_date(date_breaks = "2 years",date_labels ="%Y" )
```
#(ii)Sample means and sample covariance matrix for the log returns and
simple returns
#Returns
```{R}
simple_returns<-stock_data%>%
group_by(symbol)%>%
arrange(date)%>%
mutate(simple_return=adjusted/lag(adjusted)-1)%>%
select(date,symbol,simple_return)%>%
na.omit()
View(simple_returns)
```

```{R}
log_returns<-stock_data%>%
group_by(symbol)%>%
arrange(date)%>%
mutate(log_return=log(adjusted/lag(adjusted)))%>%
select(date,symbol,log_return)%>%
na.omit()
View(log_returns)
```
#Sample means
```{R}
sample_simple_mean<-simple_returns%>%
group_by(symbol)%>%
summarize(mean_simple_return=mean(simple_return,na.rm=TRUE))
print(sample_simple_mean)

sample_log_mean<-log_returns%>%
group_by(symbol)%>%
summarize(mean_log_return=mean(log_return,na.rm=TRUE))
print(sample_log_mean)
```
#Sample covariance matrices
```{R}
library(tidyr)
wide_simple_returns<-simple_returns%>%
select(date,symbol,simple_return)%>%
spread(key =symbol,value=simple_return)
simple_returns_matrix<-wide_simple_returns%>%
select(-date)
sample_simple_cov<-cov(simple_returns_matrix,use="everything")
print(sample_simple_cov)

wide_log_returns<-log_returns%>%
select(date,symbol,log_return)%>%
spread(key =symbol,value=log_return)
log_returns_matrix<-wide_log_returns%>%
select(-date)
sample_log_cov<-cov(log_returns_matrix,use="everything")
print(sample_log_cov)
```
#(iii)Sample skewness, sample kurtosis and Jarque-Bera Test
```{R}
install.packages("moments")
library(moments)
library(tseries)

simple_returns_skew<-simple_returns%>%
group_by(symbol)%>%
summarize(
skewness=skewness(simple_return,na.rm=TRUE),
kurtosis=kurtosis(simple_return,na.rm=TRUE),
jarque.bera.test=jarque.test(simple_return)$p.value
)
print(simple_returns_skew)

log_returns_skew<-log_returns%>%
group_by(symbol)%>%
summarize(
skewness=skewness(log_return,na.rm=TRUE),
kurtosis=kurtosis(log_return,na.rm=TRUE),
jarque.bera.test=jarque.test(log_return)$p.value
)
print(log_returns_skew)
```

#part b
```{R}
# Load required libraries
library(quantmod)
library(PerformanceAnalytics)
library(ggplot2)
```

```{R}
# Define the stock symbols
stocks <- c("AAPL", "CL", "IBM", "INTC", "JNJ", "KO", "MSFT", "PEP",
"UL", "XOM")
```

```{R}
# Download historical data for the selected stocks
getSymbols(stocks, src = 'yahoo', from = '2020-01-01', to = Sys.Date())

# Extract adjusted close prices for each stock


prices <- do.call(merge, lapply(stocks, function(x) Cl(get(x))))
```
```{R}
# Calculate daily returns for each stock
returns <- na.omit(Return.calculate(prices))

# Calculate the covariance matrix


cov_matrix <- cov(returns)

# Calculate the correlation matrix


cor_matrix <- cor(returns)

# Display the covariance and correlation matrices


print("Covariance Matrix:")
print(cov_matrix)

print("Correlation Matrix:")
print(cor_matrix)
```
```{R}
# Portfolio weights (equal weight for simplicity)
weights <- rep(1/length(stocks), length(stocks))

# Calculate portfolio returns


portfolio_returns <- Return.portfolio(returns, weights = weights)

# Calculate portfolio risk (standard deviation)


portfolio_risk <- sd(portfolio_returns)

# Calculate portfolio expected return (mean of individual returns


weighted)
portfolio_return <- sum(weights * colMeans(returns))

# Display portfolio return and risk


print(paste("Portfolio Expected Return: ", round(portfolio_return, 4)))
print(paste("Portfolio Risk (Standard Deviation): ",
round(portfolio_risk, 4)))
```
```{R}
# Generate random portfolio weights to calculate efficient frontier
set.seed(123) # For reproducibility
n_portfolios <- 10000
portfolio_returns_list <- numeric(n_portfolios)
portfolio_risk_list <- numeric(n_portfolios)
portfolio_weights_list <- matrix(0, nrow = n_portfolios, ncol =
length(stocks))

for (i in 1:n_portfolios) {
random_weights <- runif(length(stocks))
random_weights <- random_weights / sum(random_weights) # Normalize to
sum to 1

portfolio_weights_list[i, ] <- random_weights


portfolio_returns_list[i] <- sum(random_weights * colMeans(returns))
portfolio_risk_list[i] <- sqrt(t(random_weights) %% cov_matrix %%
random_weights)
}
# Create a data frame of the results
portfolio_data <- data.frame(
Return = portfolio_returns_list,
Risk = portfolio_risk_list
)
```

```{R}
# Plot the efficient frontier
ggplot(portfolio_data, aes(x = Risk, y = Return)) +
geom_point(alpha = 0.1) +
theme_minimal() +
labs(title = "Efficient Frontier", x = "Portfolio Risk (Standard
Deviation)", y = "Portfolio Expected Return") +
geom_point(aes(x = portfolio_risk, y = portfolio_return), color =
"red", size = 3, shape = 17) +
theme(plot.title = element_text(hjust = 0.5))

```
# Show the portfolio with the minimum risk (which lies on the efficient
frontier)

```{R}
min_risk_idx <- which.min(portfolio_risk_list)
min_risk_portfolio <- portfolio_weights_list[min_risk_idx, ]
min_risk_return <- portfolio_returns_list[min_risk_idx]
min_risk_sd <- portfolio_risk_list[min_risk_idx]

print(paste("Minimum Risk Portfolio Expected Return: ",


round(min_risk_return, 4)))
print(paste("Minimum Risk Portfolio Risk (Standard Deviation): ",
round(min_risk_sd, 4)))
print("Minimum Risk Portfolio Weights:")
print(min_risk_portfolio)
```
#Part c
```{R}
install.packages("quadprog")
install.packages("ggplot2")
ls("package:quadprog")
library(quadprog)
library(ggplot2)
```
# Example monthly returns data for six stocks (use your actual data)
# Replace with actual data
```{R}
monthly_returns <- matrix(rnorm(120 * 6, mean = 0.01, sd = 0.05), ncol =
6)
colnames(monthly_returns) <- paste("Stock", 1:6, sep = "_")

# Calculate mean returns and covariance matrix


mean_returns <- colMeans(monthly_returns)
cov_matrix <- cov(monthly_returns)
risk_free_rate <- 0.1345 / 12
```

# Define portfolio functions


```{R}
portfolio_stats <- function(weights, mean_returns, cov_matrix) {
portfolio_return <- sum(weights * mean_returns)
portfolio_risk <- sqrt(t(weights) %*% cov_matrix %*% weights)
return(c(Return = portfolio_return, Risk = portfolio_risk))
}
```

```{R}
min_variance_portfolio <- function(mean_returns, cov_matrix) {
n <- length(mean_returns)
Dmat <- cov_matrix
dvec <- rep(0, n)
Amat <- cbind(rep(1, n)) # Constraint: weights sum to 1
bvec <- 1
result <- solve.QP(Dmat, dvec, Amat, bvec, meq = 1)
weights <- result$solution
return(weights)
}
```

```{R}
tangency_portfolio <- function(mean_returns, cov_matrix, risk_free_rate)
{
excess_returns <- mean_returns - risk_free_rate
inv_cov_matrix <- solve(cov_matrix)
weights <- inv_cov_matrix %*% excess_returns / sum(inv_cov_matrix %*%
excess_returns)
return(as.vector(weights))
}
```

```{R}
efficient_frontier <- function(mean_returns, cov_matrix, num_portfolios =
100) {
n <- length(mean_returns)
Dmat <- cov_matrix
dvec <- rep(0, n)
Amat <- cbind(rep(1, n), mean_returns) # Constraints: sum of weights =
1 and target return
frontier <- data.frame(Return = numeric(0), Risk = numeric(0)) #
Initialize an empty data frame

target_returns <- seq(min(mean_returns), max(mean_returns), length.out


= num_portfolios)

for (r in target_returns) {
bvec <- c(1, r)
result <- solve.QP(Dmat, dvec, Amat, bvec, meq = 1)
weights <- result$solution
stats <- portfolio_stats(weights, mean_returns, cov_matrix)
frontier <- rbind(frontier, as.data.frame(t(stats))) # Append row to
frontier
}

return(frontier)
}
```

# Calculate minimum variance and tangency portfolios

```{R}
min_var_weights <- min_variance_portfolio(mean_returns, cov_matrix)
min_var_stats <- portfolio_stats(min_var_weights, mean_returns,
cov_matrix)

tangency_weights <- tangency_portfolio(mean_returns, cov_matrix,


risk_free_rate)
tangency_stats <- portfolio_stats(tangency_weights, mean_returns,
cov_matrix)

# Calculate the efficient frontier


frontier <- efficient_frontier(mean_returns, cov_matrix)
```

```{R}
# Data for individual stock returns and risks
stock_data <- data.frame(
Stock = colnames(monthly_returns),
Return = mean_returns,
Risk = sqrt(diag(cov_matrix))
)
```

```{R}
# Add minimum variance and tangency portfolios to the data for plotting
min_var_point <- data.frame(Portfolio = "Minimum Variance", Return =
min_var_stats["Return"], Risk = min_var_stats["Risk"])
tangency_point <- data.frame(Portfolio = "Tangency", Return =
tangency_stats["Return"], Risk = tangency_stats["Risk"])
portfolio_points <- rbind(min_var_point, tangency_point)
```

```{R}
# Plot using ggplot2
ggplot() +
geom_point(data = stock_data, aes(x = Risk, y = Return, color = Stock),
size = 3) +
geom_line(data = frontier, aes(x = Risk, y = Return), color = "blue",
size = 1) +
geom_point(data = portfolio_points, aes(x = Risk, y = Return, color =
Portfolio), size = 4, shape = 17) +
geom_text(data = stock_data, aes(x = Risk, y = Return, label = Stock),
vjust = -1) +
labs(title = "Efficient Frontier with Tangency and Minimum Variance
Portfolios",
x = "Risk (Standard Deviation)", y = "Expected Return") +
theme_minimal()
```
#QUESTION (D)

# Given values
```{R}
target_daily_return <- 0.0007 # Target daily return of 0.07%
risk_free_rate <- 0.1345 / 252 # Assuming a 2% annual risk-free rate,
converted to daily
```

```{R}
# Calculate the expected daily return of the tangency portfolio

tangency_return <- sum(tangency_weights * mean_returns / 252) # Convert


mean returns to daily

# Calculate the weight in the tangency portfolio to achieve the target


return
w_tangency <- (target_daily_return - risk_free_rate) / (tangency_return -
risk_free_rate)
```

```{R}
# Calculate final allocation weights for each asset
final_weights <- w_tangency * tangency_weights # Weights in each asset
based on tangency allocation
```

# Display final weights for each asset and the risk-free asset
```{R}
list(
Tangency_Portfolio_Weights = final_weights,
Risk_Free_Weight = 1 - w_tangency
)
```

You might also like