library(PerformanceAnalytics) library(quantmod) library(xts) library(dygraphs)#画图 library(tibble) library(tidyr) library(ggplot2) #画图 library(highcharter) library(tidyquant) library(plotly) library(timetk) # To manipulate the data series library(forcats)

选取投资组合对象

WBYY(威博液压) JGJM(吉冈精密) SXYY(森萱医药) GSSP(盖世食品) KLT(克莱特)

读取数据

price <-read.csv("E:/portfolio/ Final Report/data1.csv")

修改数据格式--转化成时间序列

假设 price[,1] 包含的日期时间数据如 "2021/1/4" price[,1] = as.POSIXct(price[,1], format = "%Y/%m/%d")

price[,1] = as.POSIXct(price[,1]) price[,1]

price[,1] = as.POSIXct(price[,1]):

这行代码将数据框(data frame)中的第一列转换为POSIXct类型,

即日期/时间类型。POSIXct是R语言中用于表示日期和时间的一种数据类型

它以整数形式存储日期和时间,并使用以秒为单位的时间戳来表示。

price = xts(price[,-1], order.by=price[,1])

order.by=price[,1] 指定了时间序列对象的时间索引,

也就是根据数据框中的第一列的时间信息来排序时间序列数据

绘制走势图

price = price[,1:5] names(price)<-c("WBYY","JGJM","SXYY","GSSP","KLT") dygraph(price) #动态图 plot太low了不要用 dy可以实时显示数字

plot(price)

获取月汇报

过滤数据

pr_monthly <- to.monthly(price, indexAt = "lastof", OHLC = FALSE)

head(pr_monthly)

计算回报

rtmonthly <- na.omit(Return.calculate(prmonthly, method = "log"))

head(price)#打印前五行 prdaily <- to.daily(price, indexAt = "lastof", OHLC = FALSE) head(prdaily)

计算回报

rtdaily <- na.omit(Return.calculate(prdaily, method = "log")) #去掉空白值 na就是空值

这里面计算回报率就是后一天检前一天 除以前一天,用对数收益率的方法

head(rtdaily) dygraph(rtdaily)

meanret <- colMeans(rtdaily)#计算回报率的均值 print(round(mean_ret, 5))#收益能力

covmat <- cov(rtdaily) * 252 #计算协方差 【为什么成252??全年吗?】 print(round(cov_mat,5)) #风险情况

随机抽样,给四个股票每人一个比值,让他们和是1

simulation和computation 模拟和计算

↓模拟法 随机生成一千个,算整体收益和风险,一千个中收益最高 就是现实收益最高,

一千个中风险最小就是接近现实中风险越小

tick <- c("WBYY","JGJM","SXYY","GSSP","KLT") wts <- runif(n = length(tick))#tick是四个数 给四个数赋予权重

wts <- runif(n = length(tick))这行代码生成的是一个随机数向量,

每个数字都是介于0和1之间的一个值,

代表了投资组合中每个资产的相对权重。

wts <- wts/sum(wts) print(wts)

portreturns <- (sum(wts * meanret) + 1)^252 - 1#四个整体收益

port_risk <- sqrt(t(wts) %*% (cov_mat %*% wts))#转置 再相乘 sharperatio <- portreturns/port_risk

num_port <- 1000

Creating a matrix to store the weights

allwts <- matrix(nrow = numport, ncol = length(tick))

Creating an empty vector to store

Portfolio returns

portreturns <- vector('numeric', length = numport)

Creating an empty vector to store

Portfolio Standard deviation

portrisk <- vector('numeric', length = numport)

Creating an empty vector to store

Portfolio Sharpe Ratio

sharperatio <- vector('numeric', length = numport)

for (i in seqalong(portreturns)) {

wts <- runif(length(tick)) wts <- wts/sum(wts)

# Storing weight in the matrix all_wts[i,] <- wts

# Portfolio returns

portret <- sum(wts * meanret) portret <- ((portret + 1)^252) - 1

# Storing Portfolio Returns values portreturns[i] <- portret

# Creating and storing portfolio risk port_sd <- sqrt(t(wts) %*% (cov_mat %*% wts)) portrisk[i] <- portsd

# Creating and storing Portfolio Sharpe Ratios # Assuming 0% Risk free rate

sr <- portret/portsd sharpe_ratio[i] <- sr }

Storing the values in the table

portfoliovalues <- tibble(Return = portreturns, Risk = portrisk, SharpeRatio = sharperatio)

Converting matrix to a tibble and changing column names

allwts <- tktbl(all_wts)

colnames(allwts) <- colnames(prdaily)

Combing all the values together

portfoliovalues <- tktbl(cbind(allwts, portfoliovalues))

minvar <- portfoliovalues[which.min(portfolio_values$Risk),] maxsr <- portfoliovalues[which.max(portfolio_values$SharpeRatio),]

p <- minvar %>% gather(WBYY:KLT, key = Asset, value = Weights) %>% mutate(Asset = as.factor(Asset)) %>% ggplot(aes(x = fctreorder(Asset,Weights), y = Weights, fill = Asset)) + geombar(stat = 'identity') + thememinimal() + labs(x = 'Assets', y = 'Weights', title = "Minimum Variance Portfolio Weights") + scaleycontinuous(labels = scales::percent)

ggplotly(p)

p <- maxsr %>% gather(WBYY:KLT, key = Asset, value = Weights) %>% mutate(Asset = as.factor(Asset)) %>% ggplot(aes(x = fctreorder(Asset,Weights), y = Weights, fill = Asset)) + geombar(stat = 'identity') + thememinimal() + labs(x = 'Assets', y = 'Weights', title = "Tangency Portfolio Weights") + scaleycontinuous(labels = scales::percent)

ggplotly(p)

p <- portfoliovalues %>% ggplot(aes(x = Risk, y = Return, color = SharpeRatio)) + geompoint() + themeclassic() + scaleycontinuous(labels = scales::percent) + scalexcontinuous(labels = scales::percent) + labs(x = 'Annualized Risk', y = 'Annualized Returns', title = "Portfolio Optimization & Efficient Frontier") + geompoint(aes(x = Risk, y = Return), data = minvar, color = 'orange') + geompoint(aes(x = Risk, y = Return), data = maxsr, color = 'orange') + scalecolor_gradient(low = "skyblue", high = "pink") #+

annotate('text', x = 3.2, y = 550, label = "Tangency Portfolio") +

annotate('text', x = 1.3, y = 40, label = "Min Var portfolio") #+

annotate(geom = 'segment', x = 0.2, xend = 0.185, y = 0.03,

yend = 0.11, color = 'red', arrow = arrow(type = "open")) +

annotate(geom = 'segment', x = 0.285, xend = 0.26, y = 0.34,

yend = 0.31, color = 'red', arrow = arrow(type = "open"))

ggplotly(p)