【问题标题】:How can I print a stock symbol that throws an error?如何打印引发错误的股票代码?
【发布时间】:2016-01-15 16:10:18
【问题描述】:

我正在尝试运行下面的脚本,但一直失败。

###### rm(list=ls())

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



# Create the portfolio using ETFs, incl. hypothetical non-efficient allocation
stocks <- c ("VCRA",
"AFFX",
"SGI",
"SAFM",
"SCAI",
"LINC",
"OGS",
"HIIQ",
"FLIR",
"MGEE",
"INTT",
"IPCI",
"DMRC",
"SBGL",
"UNTY",
"AEP",
"NAME",
"ED",
"WEC",
"MMYT",
"AWK",
"DRD",
"ISRG",
"CHUY",
"EDE",
"CHT",
"BGFV",
"VPCOU",
"NJR",
"FC",
"ROVI",
"SO",
"BXLT",
"NATH",
"VRNS",
"XEL",
"MBTF",
"MJCO",
"CMS",
"DLR",
"O",
"ADTN",
"SSS",
"SLP",
"PBY",
"NI",
"ORBC",
"CPB",
"OCLR",
"TLP",
"PROV",
"NWN",
"LNT",
"NTLS",
"PPC",
"NTT",
"WBMD",
"PLCE",
"NEE",
"EE",
"PMBC",
"PACB",
"AVA",
"IESC",
"HOFT",
"QSII",
"LPTH",
"INFY",
"DYAX",
"CPK",
"MMAC",
"CBNJ",
"IDSY",
"ONE",
"ITC",
"HLI",
"VHC",
"CTWS",
"SMBC",
"EQIX",
"LOCO",
"LEI",
"PNM",
"CYBE",
"PSA",
"YOKU",
"BDBD",
"ADMS",
"GMCR",
"DWA",
"LBMH",
"SCG",
"KMB",
"POR",
"ARG",
"ETR",
"WGL",
"CRAY",
"ES")



# Retrieve returns, from earliest start date possible (where all stocks have
# data) through most recent date
returns <- getReturns(stocks, freq="day", start = "2015-02-01", end = "2015-07-30") #Currently, drop index


#### Efficient Frontier function ####
eff.frontier <- function (returns, short="yes", max.allocation=NULL,
 risk.premium.up=2.95, risk.increment=.1){
 # 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) and 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
 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 along the EF
 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))
}


# Run the eff.frontier function based on no short and 50% alloc. restrictions
eff <- eff.frontier(returns=returns$R, short="no", max.allocation=.50,
 risk.premium.up=2.95, risk.increment=.1)


# Find the optimal portfolio
eff.optimal.point <- eff[eff$sharpe==max(eff$sharpe),]


# graph efficient frontier
# Start with color scheme
ealred <- "#7D110C"
ealtan <- "#CDC4B6"
eallighttan <- "#F7F6F0"
ealdark <- "#423C30"

ggplot(eff, aes(x=Std.Dev, y=Exp.Return)) + geom_point(alpha=.1, color=ealdark) +
 geom_point(data=eff.optimal.point, aes(x=Std.Dev, y=Exp.Return, label=sharpe),
 color=ealred, size=5) +
 annotate(geom="text", x=eff.optimal.point$Std.Dev,
 y=eff.optimal.point$Exp.Return,
 label=paste("Risk: ",
 round(eff.optimal.point$Std.Dev*100, digits=3),"\nReturn: ",
 round(eff.optimal.point$Exp.Return*100, digits=4),"%\nSharpe: ",
 round(eff.optimal.point$sharpe*100, digits=2), "%", sep=""),
 hjust=0, vjust=1.2) +
 ggtitle("Efficient Frontier\nand Optimal Portfolio") +
 labs(x="Risk (standard deviation of portfolio)", y="Return") +
 theme(panel.background=element_rect(fill=eallighttan),
 text=element_text(color=ealdark),
 plot.title=element_text(size=24, color=ealred))
ggsave("Efficient Frontier.png")



transposed_object<-as.data.frame(t(eff.optimal.point))
colnames(transposed_object)<- c("stat")
subset(transposed_object, transposed_object $stat>0.05)

问题是,这些股票中的一只或多只在我查看的期间没有价格,这会引发错误,因为没有价格 = 没有回报。如何修改脚本以打印任何没有价格的股票代码,这样我就可以从列表中删除任何/全部,然后重新运行脚本并让它第二次工作?

谢谢大家。

【问题讨论】:

  • 您能发布您的示例数据和预期输出吗?股票符号向量无助于回答您的问题。
  • 我刚刚编辑了我的原始帖子。我认为所需要的只是第一部分。现在一切都在那里。这个概念来自这里。 economistatlarge.com/portfolio-theory/r-optimized-portfolio
  • 虽然这很好,但我建议您发布一组最低限度可重现的数据。我们中的任何人都不可能运行大量依赖于大量包的代码并为您提供帮助。您可以创建假数据并从该假数据中提供所需的输出,解释您期望中间步骤执行的逻辑。
  • 另外,不要将rm(list=ls()) 放在发布给其他人运行的代码中。

标签: r


【解决方案1】:
returns <- if( prices = returns) { getReturns(stocks, freq="day", start = "2015-02-01", end = "2015-07-30") } else (no prices = no returns) {add current date};
returns<- returns[-currentdate, ];

然后重新运行您的代码。这是我将要做的事情的大纲。有人想吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多