如何解决R Shiny-找不到函数 min_var 和 max_sr (renderHighchart) 最小差异投资组合权重相切组合权重投资组合优化和高效前沿Symulacje最小值、最大值、中值 Sim直方图密度滚动排序
你能帮我找出我的 R-shiny 代码中的问题吗? 我粘贴了整个 R-markdown 脚本,它适用于第二个选项卡“输出”,但是对于第一个名为“Portfel efektywny”的功能,存在无法找到的问题,但它已正确实现...... 警告:min_var 中的错误:找不到函数“min_var” 警告:max_sr 中的错误:找不到函数“max_sr”
我将非常感谢您的帮助:) 提前谢谢!!!
---
title: "Monte_Carlo_Projekt"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: rows
---
library(shiny)
library(tidyverse)
library(highcharter)
library(tidyquant)
library(plotly)
library(timetk)
library(scales)
侧边栏{.sidebar}
fluidRow(
column(6,textInput("stock1","Stock 1","SPY")),column(5,numericInput("w1","Portf. %",25,min = 1,max = 100))
)
fluidRow(
column(6,textInput("stock2","Stock 2","EFA")),numericInput("w2",max = 100))
)
fluidRow(
column(6,textInput("stock3","Stock 3","IJS")),numericInput("w3",20,textInput("stock4","Stock 4","EEM")),numericInput("w4",textInput("stock5","Stock 5","AGG")),numericInput("w5",10,max = 100))
)
fluidRow(
column(7,dateInput("date","Starting Date","2013-01-01",format = "yyyy-mm-dd"))
)
fluidRow(
column(5,numericInput("sim_months","Months",120,min = 6,max = 240,step = 6)),numericInput("sims","Sims",51,min = 31,max = 101,step = 10)),numericInput("mar","MAR%",.8,min = 0,max = 3,step = .01)),numericInput("window","Window",6,min = 2,max = 24,step = 2))
)
actionButton("go","Submit")
#Tu dodajemy wszystkie funkcje
prices <- eventReactive(input$go,{
symbols <- c(input$stock1,input$stock2,input$stock3,input$stock4,input$stock5)
getSymbols(symbols,src = 'yahoo',from = input$date,auto.assign = TRUE,warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
})
mar <- eventReactive(input$go,{input$mar/100})
rolling_sortino <- eventReactive(input$go,{
validate(need(input$w1 + input$w2 + input$w3 + input$w4 + input$w5 == 100,"The portfolio weights must sum to 100%!"))
prices <- prices()
w <- c(input$w1/100,input$w2/100,input$w3/100,input$w4/100,input$w5/100)
MAR <- mar()
window <- input$window
prices_monthly <- to.monthly(prices,indexAt = "last",OHLC = FALSE)
asset_returns_xts <- na.omit(Return.calculate(prices_monthly,method = "log"))
cov_mat <- cov(asset_returns_xts) * 12
mean_ret <- colMeans(asset_returns_xts)
portfolio_returns_xts_rebalanced_monthly <- Return.portfolio(asset_returns_xts,weights = w,rebalance_on = "months")
rolling_sortino <-
apply.rolling(portfolio_returns_xts_rebalanced_monthly,window,fun = 'SortinoRatio',MAR = MAR) %>%
`colnames<-`(paste(window,"-month rolling sortino",sep=""))
})
help("apply.rolling")
portfolio_returns_tq_rebalanced_monthly <- eventReactive(input$go,{
validate(need(input$w1 + input$w2 + input$w3 + input$w4 + input$w5 == 100,"The portfolio weights must sum to 100%!"))
prices <- prices()
w <- c(input$w1/100,input$w5/100)
asset_returns_long <-
prices %>%
to.monthly(indexAt = "last",OHLC = FALSE) %>%
tk_tbl(preserve_index = TRUE,rename_index = "date") %>%
gather(asset,returns,-date) %>%
group_by(asset) %>%
mutate(returns = (log(returns) - log(lag(returns))))
sims <- eventReactive(input$go,{input$sims})
sims <- sims()
# Creating a matrix to store the weights
all_wts <- matrix(nrow = sims,ncol = length(symbols))
# Creating an empty vector to store Portfolio returns,Portfolio Standard deviation,Portfolio Sharpe Ratio
port_returns <- vector('numeric',length = sims)
port_risk <- vector('numeric',length = sims)
sharpe_ratio <- vector('numeric',length = sims)
for (i in seq_along(port_returns)) {
wts <- runif(length(symbols))
wts <- wts/sum(wts)
all_wts[i,] <- wts # Storing weight in the matrix
port_ret <- sum(wts * mean_ret) # Portfolio returns
port_ret <- ((port_ret + 1)^12) - 1
port_returns[i] <- port_ret # Storing Portfolio Returns values
port_sd <- sqrt(t(wts) %*% (cov_mat %*% wts)) # Creating and storing portfolio risk
port_risk[i] <- port_sd
sr <- port_ret/port_sd # Creating and storing Portfolio Sharpe Ratios,sharpe_ratio[i] <- sr #Assuming 0% Risk free rate
}
# Storing the values in the table
portfolio_values <- tibble(Return = port_returns,Risk = port_risk,SharpeRatio = sharpe_ratio)
# Converting matrix to a tibble and changing column names
all_wts <- tk_tbl(all_wts)
colnames(all_wts) <- colnames(asset_returns_xts)
# Combing all the values together
portfolio_values <- tk_tbl(cbind(all_wts,portfolio_values))
# calculating the minimum variance portfolio
min_var <- eventReactive(input$go,{
portfolio_values[which.min(portfolio_values$Risk),]
})
# calculating the tangency portfolio (the portfolio with highest sharpe ratio)
max_sr <- eventReactive(input$go,{
portfolio_values[which.max(portfolio_values$SharpeRatio),]
})
MAR <- mar()
portfolio_returns_tq_rebalanced_monthly <-
asset_returns_long %>%
tq_portfolio(assets_col = asset,returns_col = returns,col_rename = "returns",rebalance_on = "months") %>%
mutate(returns_below_MAR = ifelse(returns < MAR,NA)) %>%
mutate(returns_above_MAR = ifelse(returns > MAR,NA))
portfolio_returns_tq_rebalanced_monthly
})
portfolio_returns_tq_rebalanced_monthly <- eventReactive(input$go,{
prices <- prices()
w <- c(input$w1/100,input$w5/100)
portfolio_returns_tq_rebalanced_monthly <-
prices %>%
to.monthly(indexAt = "last",-date) %>%
group_by(asset) %>%
mutate(returns = (log(returns) - log(lag(returns)))) %>%
tq_portfolio(assets_col = asset,weights = w,col_rename = "returns",rebalance_on = "months")
})
mean_port_return <- eventReactive(input$go,{
portfolio_returns_tq_rebalanced_monthly <- portfolio_returns_tq_rebalanced_monthly()
mean(portfolio_returns_tq_rebalanced_monthly$returns)
})
stddev_port_return <- eventReactive(input$go,{
portfolio_returns_tq_rebalanced_monthly <- portfolio_returns_tq_rebalanced_monthly()
sd(portfolio_returns_tq_rebalanced_monthly$returns)
})
simulation_accum_1 <- function(init_value,N,mean,stdev) {
tibble(c(init_value,1 + rnorm(N,stdev))) %>%
`colnames<-`("returns") %>%
mutate(growth = accumulate(returns,function(x,y) x * y)) %>%
select(growth)
}
sims <- eventReactive(input$go,{input$sims})
monte_carlo_sim_51 <- eventReactive(input$go,{
sims <- sims()
starts <-
rep(1,sims) %>%
set_names(paste("sim",1:sims,sep = ""))
map_dfc(starts,simulation_accum_1,N = input$sim_months,mean = mean_port_return(),stdev = stddev_port_return()) %>%
mutate(month = seq(1:nrow(.))) %>%
select(month,everything()) %>%
`colnames<-`(c("month",names(starts))) %>%
gather(sim,growth,-month) %>%
group_by(sim) %>%
mutate_all(funs(round(.,2)))
})
Portfel efektywny
行{data-height=600,.tabset}
最小差异投资组合权重
renderPlotly({
validate(need(input$go != 0,"Please choose your portfolio assets,weights,MAR,rolling window and start date and click submit."))
min_var <- min_var()
min_var %>%
gather(AAPL:TSLA,key = Asset,value = Weights) %>%
mutate(Asset = as.factor(Asset)) %>%
ggplot(aes(x = fct_reorder(Asset,Weights),y = Weights,fill = Asset)) +
geom_bar(stat = 'identity') +
theme_minimal() +
labs(x = 'Assets',y = 'Weights',title = "Minimum Variance Portfolio Weights") +
scale_y_continuous(labels = scales::percent)
})
相切组合权重
renderHighchart({
hchart( max_sr(),type = 'bar',hcaes(y = Weights,x = fct_reorder(Asset,group = Asset)) %>%
hc_title(text = paste(sims(),"Tangency Portfolio Weights",sep = " ")) %>%
hc_xAxis(title = list(text = "Assets")) %>%
hc_yAxis(title = list(text = "Weights"),labels = list(format = "${value}")) %>%
hc_add_theme(hc_theme_flat()) %>%
hc_exporting(enabled = TRUE) %>%
hc_legend(enabled = FALSE)
})
行{.tabset .tabset-fade}
投资组合优化和高效前沿
renderHighchart({
validate(need(input$go != 0,months,number of simulations and start date and click submit."))
})
输出
行{data-height=600,.tabset}
Symulacje
renderHighchart(
hchart( monte_carlo_sim_51(),type = 'line',hcaes(y = growth,x = month,group = sim)) %>%
hc_title(text = paste(sims(),"Simulations",sep = " ")) %>%
hc_xAxis(title = list(text = "months")) %>%
hc_yAxis(title = list(text = "dollar growth"),labels = list(format = "${value}")) %>%
hc_add_theme(hc_theme_flat()) %>%
hc_exporting(enabled = TRUE) %>%
hc_legend(enabled = FALSE)
)
最小值、最大值、中值 Sim
renderHighchart({
validate(need(input$go != 0,number of simulations and start date and click submit."))
sim_summary <-
monte_carlo_sim_51() %>%
summarise(final = last(growth)) %>%
summarise(
max = max(final),min = min(final),median = median(final))
mc_max_med_min <-
monte_carlo_sim_51() %>%
filter(
last(growth) == sim_summary$max ||
last(growth) == sim_summary$median ||
last(growth) == sim_summary$min)
hchart(mc_max_med_min,group = sim)) %>%
hc_title(text = "Min Max Median Simulations") %>%
hc_xAxis(title = list(text = "months")) %>%
hc_yAxis(title = list(text = "dollar growth"),labels = list(format = "${value}")) %>%
hc_add_theme(hc_theme_flat()) %>%
hc_exporting(enabled = TRUE) %>%
hc_legend(enabled = FALSE)
})
行{.tabset .tabset-fade}
直方图
renderPlot({
validate(need(input$go != 0,rolling window and start date and click submit."))
MAR <- mar()
portfolio_returns_tq_rebalanced_monthly <- portfolio_returns_tq_rebalanced_monthly()
portfolio_returns_tq_rebalanced_monthly %>%
ggplot(aes(x = returns)) +
geom_histogram(alpha = 0.25,binwidth = .01,fill = "cornflowerblue") +
geom_vline(xintercept = MAR,color = "green") +
annotate(geom = "text",x = MAR,y = 10,label = "MAR",fontface = "plain",angle = 90,alpha = .5,vjust = 1)
})
密度
renderPlot({
validate(need(input$go != 0,rolling window and start date and click submit."))
MAR <- mar()
portfolio_returns_tq_rebalanced_monthly <- portfolio_returns_tq_rebalanced_monthly()
sortino_density_plot <- portfolio_returns_tq_rebalanced_monthly %>%
ggplot(aes(x = returns)) +
stat_density(geom = "line",size = 1,color = "cornflowerblue")
shaded_area_data <- ggplot_build(sortino_density_plot)$data[[1]] %>%
filter(x < MAR)
sortino_density_plot +
geom_area(data = shaded_area_data,aes(x = x,y = y),fill="pink",alpha = 0.5) +
geom_segment(data = shaded_area_data,aes(x = MAR,y = 0,xend = MAR,yend = y),color = "red",linetype = "dotted") +
annotate(geom = "text",y = 5,label = paste("MAR =",sep = ""),alpha = .8,vjust = -1) +
annotate(geom = "text",x = (MAR - .02),y = .1,label = "Downside",vjust = -1)
})
滚动排序
renderHighchart({
validate(need(input$go != 0,rolling window and start date and click submit."))
highchart(type = "stock") %>%
hc_title(text = names(rolling_sortino())) %>%
hc_add_series(rolling_sortino(),name = names(rolling_sortino()),color = "cornflowerblue") %>%
hc_navigator(enabled = FALSE) %>%
hc_scrollbar(enabled = FALSE)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。