楼主: galilee
9323 1

[问答] R如何进行异常处理 [推广有奖]

  • 2关注
  • 1粉丝

已卖:3061份资源

讲师

69%

还不是VIP/贵宾

-

威望
0
论坛币
1713 个
通用积分
1.8288
学术水平
11 点
热心指数
12 点
信用等级
8 点
经验
13732 点
帖子
357
精华
0
在线时间
750 小时
注册时间
2005-6-19
最后登录
2022-5-19

楼主
galilee 在职认证  发表于 2014-7-1 21:02:36 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
各位大大,本菜想从yahoo finance上面弄一些数据,我有一个文档里面是股票的symbol,但貌似有些symbol不能用,所以循环总会出现问题。
想用异常处理跳过这些坏的symbol,请问怎么做呢? ps: symbol文件是sp500.txt,已经上传附件。
  1. library(quantmod)
  2. library(tseries)
  3. library(timeDate)

  4. #get symbols
  5. symbols <- read.csv("sp500.txt", header = F, stringsAsFactors = F)

  6. nrStocks = length(symbols[,1])
  7. funds <- NULL
  8. dateStart <- "2009-1-1"

  9. for (i in 1:nrStocks) {
  10.     cat("Downloading ", i, " out of ", nrStocks , "\n")
  11.     prices <- get.hist.quote(instrument = symbols[i,], start = dateStart, quote = "AdjClose", retclass = "zoo", quiet = T)   
  12.     # Convert daily closing prices to monthly closing prices
  13.     monthly.prices <- aggregate(prices, as.yearmon, tail, 1);
  14.     # Convert selected monthly prices into monthly returns to run regression
  15.     r <- diff(log(monthly.prices));  # convert prices to log returns
  16.     r1 <- exp(r)-1        ;          # back to simple returns  
  17.     # Now shift out of zoo object into ordinary matrix
  18.     rj <- coredata(r1)   
  19.     # Put fund returns into matrix
  20.     if(length(rj) ==length(funds[,1]) )   {funds <- cbind(funds, rj);   }
  21.     Sys.sleep(1);   
  22.   }
复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:异常处理 quantmod Library SYMBOLS tseries 如何

我的征途是星辰大海。

沙发
DM小菜鸟 发表于 2014-12-6 23:33:49
R语言用tryCatch进行错误处理,现在的问题是,你要锁定那段内容。
比如你要锁定这样一个内容:msg <- text[seq(which(text == "")[1] + 1, length(text), 1)]
那就可以这么写:
msg <- tryCatch({
   text[seq(which(text == "")[1] + 1, length(text), 1)]   }, error = function(e) {    ""   })
  
附上tryCatch的使用方法——
  

result = tryCatch ( {

expr

} , warning = function ( w ) {

warning - handler - code

} , error = function ( e ) {

error - handler - code

} , finally = {

cleanup - code

}


您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-1-2 01:29