You are on page 1of 11

install.

packages("xts")

install.packages("Hmisc")

install.packages("readxl")

install.packages("corpcor")

install.packages("tseries")

install.packages("matlib")

install.packages("Matrix")

install.packages("xlsx")

install.packages("stockPortfolio")

install.packages("quadprog")

library(xts)

library(readxl)

library(Hmisc)

library(corpcor)

library(tseries)

library(matlib)

library(Matrix)

library(xlsx)

library(stockPortfolio) # Base package for retrieving returns

library(ggplot2) # Used to graph efficient frontier

library(reshape2) # Used to melt the data

library(quadprog) #Needed for solve.QP

# Open Data

FondoLatam <- read_xlsx("C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo


semestre/finanzas 3/EuroStoxx50 Final.xlsx", sheet = "Valores Cuota",range =
"BE6:DA532")

# Data Summary

list(FondoLatam)

summary(FondoLatam)
# Convert to Time Series

FondoLatamData <- data.matrix(FondoLatam[,-1])

FondoLatamData <- na.omit(FondoLatam[,-1])

C = matrix(c(cov(FondoLatamData,use="na.or.complete")),nrow=48, ncol=48)

r = matrix(c(colMeans(FondoLatamData,na.rm = TRUE)))

one = rep(1, 48)

# Expression for the weights

X = t(r)%*%solve(C)%*%r

Y = t(r)%*%solve(C)%*%one

Z = t(one)%*%solve(C)%*%one

D = X%*%Z-Y%*%Y

g = (1/as.vector(D))*(as.vector(X)*(solve(C)%*%one) - as.vector(Y)*(solve(C)%*%r))

h = 1/as.vector(D)*(as.vector(Z)*(solve(C)%*%r) - as.vector(Y)*(solve(C)%*%one))

r_max = 0.25

r_min = 0.00

incr = 0.0005

zz = 1

W_p = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),48)

R_P = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),1)

S_p = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),1)

for(j in seq(from=r_min, to=r_max, by=incr)){

w_j = g + h * j

W_p[zz,] = t(w_j)

R_P[zz,1] = t(w_j)%*%r

S_p[zz,1] = sqrt(t(w_j)%*%C%*%w_j)

zz = zz + 1}

SharpeRatio = R_P/S_p

Effdata = data.frame(W_p,R_P,S_p,SharpeRatio)

OptimoSinRes <- Effdata [Effdata$SharpeRatio==max(Effdata$SharpeRatio),]


write.csv(OptimoSinRes, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESPUESTASconrestricciones1.csv")

# Minimum Variance Portfolio

w_mvp = solve(C)%*%one/as.vector((t(one)%*%solve(C)%*%one))

sig_mvp = sqrt(t(w_mvp)%*%C%*%w_mvp)

r_mvp = t(w_mvp)%*%r

Opt=cbind(sig_mvp,r_mvp)

eff.frontier <- function (returns, short="NO", max.allocation=0.25, risk.premium.up=0.8,


risk.increment=.0005){

# returns <- getReturns(names(stocks[-1]), freq="week") #Currently, drop index

# return argument should be a m x n matrix with one column per security

# short argument is whether short-selling is allowed; default is no (short selling


prohibited)

# max.allocation is the maximum % allowed for any one security (reduces concentration)

# risk.premium.up is the upper limit of the risk premium modeled (see for loop below)

# risk.increment is the increment (by) value used in the for loop

covariance <- cov(returns)

print(covariance)

n <- ncol(covariance)

# Create initial Amat and bvec assuming only equality constraint (short-selling is
allowed, no allocation constraints)

Amat <- matrix (1, nrow=n)

bvec <- 1

meq <- 1

# Then modify the Amat and bvec if short-selling is prohibited


if(short=="no"){

Amat <- cbind(1, diag(n))

bvec <- c(bvec, rep(0, n))

# And modify Amat and bvec if a max allocation (concentration) is specified

if(!is.null(max.allocation)){

if(max.allocation > 1 | max.allocation <0){

stop("max.allocation must be greater than 0 and less than 1")

if(max.allocation * n < 1){

stop("Need to set max.allocation higher; not enough assets to add to 1")

Amat <- cbind(Amat, -diag(n))

bvec <- c(bvec, rep(-max.allocation, n))

# Calculate the number of loops based on how high to vary the risk premium and by
what increment

loops <- risk.premium.up / risk.increment + 1

loop <- 1

# Initialize a matrix to contain allocation and statistics

# This is not necessary, but speeds up processing and uses less memory

eff <- matrix(nrow=loops, ncol=n+3)

# Now I need to give the matrix column names

colnames(eff) <- c(colnames(returns), "Std.Dev", "Exp.Return", "sharpe")

# Loop through the quadratic program solver

for (i in seq(from=0, to=risk.premium.up, by=risk.increment)){

dvec <- colMeans(returns) * i # This moves the solution up along the efficient frontier

sol <- solve.QP(covariance, dvec=dvec, Amat=Amat, bvec=bvec, meq=meq)


eff[loop,"Std.Dev"] <- sqrt(sum(sol$solution *colSums((covariance * sol$solution))))

eff[loop,"Exp.Return"] <- as.numeric(sol$solution %*% colMeans(returns))

eff[loop,"sharpe"] <- eff[loop,"Exp.Return"] / eff[loop,"Std.Dev"]

eff[loop,1:n] <- sol$solution

loop <- loop+1

return(as.data.frame(eff))

#340:448

#FondoLatamData <- data.matrix(FondoLatam[,-1])

#FondoLatamData1 <- data.matrix(FondoLatam[1975:721,-1])

#WeeklyReturnData <- data.matrix(WeeklyReturn[,-1])

#WeeklyReturnData1 <- data.matrix(WeeklyReturn[395:484,-1])

FondoLatamData <- na.omit(FondoLatamData)

effFondoLatam <- eff.frontier(returns=FondoLatamData, short="no",


max.allocation=0.25, risk.premium.up=0.80, risk.increment=.00005)

write.csv(effFondoLatam, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESUPUESTA3.csv")

# Find the optimal portfolio

eff.optimal.pointFondoLatam <-
effFondoLatam[effFondoLatam$sharpe==max(effFondoLatam$sharpe),]

effFondoLatam= rbind(eff.optimal.pointFondoLatam)

write.csv(effFondoLatam, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESPUESTA4.csv")
install.packages("xts")

install.packages("Hmisc")

install.packages("readxl")

install.packages("corpcor")

install.packages("tseries")

install.packages("matlib")

install.packages("Matrix")

install.packages("xlsx")

install.packages("stockPortfolio")

install.packages("quadprog")

library(xts)

library(readxl)

library(Hmisc)
library(corpcor)

library(tseries)

library(matlib)

library(Matrix)

library(xlsx)

library(stockPortfolio) # Base package for retrieving returns

library(ggplot2) # Used to graph efficient frontier

library(reshape2) # Used to melt the data

library(quadprog) #Needed for solve.QP

# Open Data

FondoLatam <- read_xlsx("C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo


semestre/finanzas 3/EuroStoxx50 Final.xlsx", sheet = "Valores Cuota",range =
"BE6:DA532")

# Data Summary

list(FondoLatam)

summary(FondoLatam)

# Convert to Time Series

FondoLatamData <- data.matrix(FondoLatam[,-1])

FondoLatamData <- na.omit(FondoLatam[,-1])


C = matrix(c(cov(FondoLatamData,use="na.or.complete")),nrow=48, ncol=48)

r = matrix(c(colMeans(FondoLatamData,na.rm = TRUE)))

one = rep(1, 48)

# Expression for the weights

X = t(r)%*%solve(C)%*%r

Y = t(r)%*%solve(C)%*%one

Z = t(one)%*%solve(C)%*%one

D = X%*%Z-Y%*%Y

g = (1/as.vector(D))*(as.vector(X)*(solve(C)%*%one) - as.vector(Y)*(solve(C)%*%r))

h = 1/as.vector(D)*(as.vector(Z)*(solve(C)%*%r) - as.vector(Y)*(solve(C)%*%one))
r_max = 1

r_min = -1

incr = 0.0005

zz = 1

W_p = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),48)

R_P = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),1)

S_p = matrix(0,length(seq(from=r_min, to=r_max, by=incr)),1)

for(j in seq(from=r_min, to=r_max, by=incr)){

w_j = g + h * j

W_p[zz,] = t(w_j)

R_P[zz,1] = t(w_j)%*%r

S_p[zz,1] = sqrt(t(w_j)%*%C%*%w_j)

zz = zz + 1}

SharpeRatio = R_P/S_p

Effdata = data.frame(W_p,R_P,S_p,SharpeRatio)

OptimoSinRes <- Effdata [Effdata$SharpeRatio==max(Effdata$SharpeRatio),]

write.csv(OptimoSinRes, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESPUESTASconrestricciones12.csv")

# Minimum Variance Portfolio

w_mvp = solve(C)%*%one/as.vector((t(one)%*%solve(C)%*%one))

sig_mvp = sqrt(t(w_mvp)%*%C%*%w_mvp)

r_mvp = t(w_mvp)%*%r

Opt=cbind(sig_mvp,r_mvp)

eff.frontier <- function (returns, short="NO", max.allocation=0.25, risk.premium.up=0.8,


risk.increment=.0005){

# returns <- getReturns(names(stocks[-1]), freq="week") #Currently, drop index


# return argument should be a m x n matrix with one column per security

# short argument is whether short-selling is allowed; default is no (short selling


prohibited)

# max.allocation is the maximum % allowed for any one security (reduces concentration)

# risk.premium.up is the upper limit of the risk premium modeled (see for loop below)

# risk.increment is the increment (by) value used in the for loop

covariance <- cov(returns)

print(covariance)

n <- ncol(covariance)

# Create initial Amat and bvec assuming only equality constraint (short-selling is
allowed, no allocation constraints)

Amat <- matrix (1, nrow=n)

bvec <- 1

meq <- 1

# Then modify the Amat and bvec if short-selling is prohibited

if(short=="no"){

Amat <- cbind(1, diag(n))

bvec <- c(bvec, rep(0, n))

# And modify Amat and bvec if a max allocation (concentration) is specified

if(!is.null(max.allocation)){

if(max.allocation > 1 | max.allocation <0){

stop("max.allocation must be greater than 0 and less than 1")

if(max.allocation * n < 1){

stop("Need to set max.allocation higher; not enough assets to add to 1")

Amat <- cbind(Amat, -diag(n))


bvec <- c(bvec, rep(-max.allocation, n))

# Calculate the number of loops based on how high to vary the risk premium and by
what increment

loops <- risk.premium.up / risk.increment + 1

loop <- 1

# Initialize a matrix to contain allocation and statistics

# This is not necessary, but speeds up processing and uses less memory

eff <- matrix(nrow=loops, ncol=n+3)

# Now I need to give the matrix column names

colnames(eff) <- c(colnames(returns), "Std.Dev", "Exp.Return", "sharpe")

# Loop through the quadratic program solver

for (i in seq(from=0, to=risk.premium.up, by=risk.increment)){

dvec <- colMeans(returns) * i # This moves the solution up along the efficient frontier

sol <- solve.QP(covariance, dvec=dvec, Amat=Amat, bvec=bvec, meq=meq)

eff[loop,"Std.Dev"] <- sqrt(sum(sol$solution *colSums((covariance * sol$solution))))

eff[loop,"Exp.Return"] <- as.numeric(sol$solution %*% colMeans(returns))

eff[loop,"sharpe"] <- eff[loop,"Exp.Return"] / eff[loop,"Std.Dev"]

eff[loop,1:n] <- sol$solution

loop <- loop+1

return(as.data.frame(eff))

#340:448

#FondoLatamData <- data.matrix(FondoLatam[,-1])

#FondoLatamData1 <- data.matrix(FondoLatam[1975:721,-1])

#WeeklyReturnData <- data.matrix(WeeklyReturn[,-1])

#WeeklyReturnData1 <- data.matrix(WeeklyReturn[395:484,-1])


FondoLatamData <- na.omit(FondoLatamData)

effFondoLatam <- eff.frontier(returns=FondoLatamData, short="no",


max.allocation=0.25, risk.premium.up=0.80, risk.increment=.00005)

write.csv(effFondoLatam, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESUPUESTA3.csv")

# Find the optimal portfolio

eff.optimal.pointFondoLatam <-
effFondoLatam[effFondoLatam$sharpe==max(effFondoLatam$sharpe),]

effFondoLatam= rbind(eff.optimal.pointFondoLatam)

write.csv(effFondoLatam, "C:/Users/Usuario/Desktop/UNIVERSIDAD/septimo
semestre/finanzas 3/RESPUESTA4.csv")

You might also like