R Markdown

To read the price data of the assets Minimum risk weights and corresponding histogram. Max return weights and corresponding histogram. Max Sharpe Ratio weights and corresponding histogram. Portfolio Optimization & Efficient Frontier Plot.

price <-read.csv("D:/Desktop/data(4).csv")
#input the data of the 4 shares
library(xts)
## 载入需要的程辑包:zoo
## 
## 载入程辑包:'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
price[,1] = as.POSIXct(price[,1])
price <- xts(price[, -1], order.by = as.POSIXct(price[, 1]))
names<-c("LC","FG","AR","QL")
library(dygraphs)
dygraph(price)

#caculating the cov matix

library(PerformanceAnalytics)
## 
## 载入程辑包:'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
head(price)
##            乐创技术 丰光精密 艾融软件 齐鲁华信
## 2022-01-04     24.5    19.70    15.53     8.26
## 2022-01-05     24.7    19.78    15.48     8.35
## 2022-01-06     24.7    19.78    15.01     8.40
## 2022-01-07     24.7    19.33    15.12     8.32
## 2022-01-10     24.7    19.29    15.29     8.40
## 2022-01-11     24.6    19.10    14.98     8.36
pr_daily <- to.daily(price, indexAt = "lastof", OHLC = FALSE) 
head(pr_daily)
##            乐创技术 丰光精密 艾融软件 齐鲁华信
## 2022-01-31     24.5    19.70    15.53     8.26
## 2022-01-31     24.7    19.78    15.48     8.35
## 2022-01-31     24.7    19.78    15.01     8.40
## 2022-01-31     24.7    19.33    15.12     8.32
## 2022-01-31     24.7    19.29    15.29     8.40
## 2022-01-31     24.6    19.10    14.98     8.36
rt_daily <- na.omit(Return.calculate(pr_daily, method = "log")) 
head(rt_daily)
##                乐创技术     丰光精密     艾融软件     齐鲁华信
## 2022-01-31  0.008130126  0.004052690 -0.003224769  0.010836951
## 2022-01-31  0.000000000  0.000000000 -0.030832223  0.005970167
## 2022-01-31  0.000000000 -0.023013033  0.007301725 -0.009569451
## 2022-01-31  0.000000000 -0.002071466  0.011180649  0.009569451
## 2022-01-31 -0.004056801 -0.009898492 -0.020483042 -0.004773279
## 2022-01-31  0.004461577 -0.034082106 -0.008042939 -0.005998818
dygraph(rt_daily)
mean_ret <- colMeans(rt_daily)
print(round(mean_ret, 4))
## 乐创技术 丰光精密 艾融软件 齐鲁华信 
##  -0.0021  -0.0026  -0.0024  -0.0013
cov_mat <- cov(rt_daily) * 252
print(round(cov_mat,4))
##          乐创技术 丰光精密 艾融软件 齐鲁华信
## 乐创技术   0.5691  -0.0126  -0.0026   0.0102
## 丰光精密  -0.0126   0.2233   0.0394   0.0553
## 艾融软件  -0.0026   0.0394   0.3076   0.0352
## 齐鲁华信   0.0102   0.0553   0.0352   0.0970

#To calculate the portfolio returns and risk (standard deviation) we will us need

er_p<-c()
sigma_p<-c()
sharpe_p<-c()
all_wts <- matrix(nrow = 1000,
                  ncol = 4)
for(i in 1:1000){w<-runif(4,min=0,max=1)
w<-w/sum(w)
all_wts[i,] <- w
miu<-((t(w)%*%mean_ret+1)^252)-1
std<-sqrt(t(w)%*%cov_mat%*%w)
sharpe_ration<-miu/std
sharpe_p<-append(sharpe_p,sharpe_ration,length(sharpe_p))
er_p<-append(er_p,miu,length(er_p))
sigma_p<-append(sigma_p,std,length(sigma_p))}

#look up for the maximum

library(tibble)
portfolio_values <- tibble(Return = er_p,
                           Risk = sigma_p,
                           SharpeRatio = sharpe_p,weights=all_wts)
min_var <- portfolio_values[which.min(portfolio_values$Risk),]
max_return<-portfolio_values[which.max(portfolio_values$Return),]
max_sr <- portfolio_values[which.max(portfolio_values$SharpeRatio),]
library(ggplot2)

#最值权重分配直方图

p_return<-data.frame('name'=names,'weights'=as.vector(as.matrix(max_return[,4])))
p_1<-ggplot(data=p_return,aes(x=name,y=weights))+
  geom_bar(stat='identity',fill='pink')+
  theme_minimal() +
          labs( title = "Tangency Portfolio Weights")+
          scale_y_continuous(labels = scales::percent)
        print(p_1)

        p_var<-data.frame('name'=names,'weights'=as.vector(as.matrix(min_var[,4])))
        p_2<-ggplot(data=p_var,aes(x=name,y=weights))+
          geom_bar(stat='identity',fill='blue')+
          theme_minimal() +
          labs( title = "min risk Portifolio Weights")+
          scale_y_continuous(labels = scales::percent) 
        print(p_2)

        p_sr<-data.frame('name'=names,'weights'=as.vector(as.matrix(max_sr[,4])))
        p_3<-ggplot(data=p_sr,aes(x=name,y=weights))+
          geom_bar(stat='identity',fill='yellow')+
          theme_minimal() +
          labs( title = "max returns Portfolio Weights")+
          scale_y_continuous(labels = scales::percent) 
        print(p_3)

        #min sigma frontier
        mydata2<-data.frame('expected'=er_p,'volatility'=sigma_p)
        p<-ggplot(data=mydata2,aes(x=volatility,y=expected))+
          geom_point(col="blue")+
          geom_point(data=min_var,aes(x=Risk,y=Return),col="red")+
          geom_point(data=max_return,aes(x=Risk,y=Return),col="orange")+
          geom_point(data=max_sr,aes(x=Risk,y=Return),col="blue")+
          labs(title="Min frontier",caption="Portofolio")+
          theme_classic()
        plot(p)