Financial Calc
Financial Calc
```{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())
print("Correlation Matrix:")
print(cor_matrix)
```
```{R}
# Portfolio weights (equal weight for simplicity)
weights <- rep(1/length(stocks), 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
```{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]
```{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
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)
}
```
```{R}
min_var_weights <- min_variance_portfolio(mean_returns, cov_matrix)
min_var_stats <- portfolio_stats(min_var_weights, 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
```{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
)
```