2017-02-15 19 views
0

我有一個csv文件中的符號列表,我想篩選收盤價高於5的那些。如何使用帶字符的Cl()?

我已經爲csv文件中的所有項目運行getSymbols。

我的測試在這裏出錯。我認爲這是因爲Cl()不接受字符作爲參數。我如何將字符轉換爲xts?

> library(quantmod) 

> passingset 
     V1 
1  AAB 
2 AAR-UN 
3  AAV 
4  ABT 
5  ABX 
     (...) 

> class(passingset) 
[1] "data.frame" 
> class(passingset$V1) 
[1] "character" 


> #Remove closing price < 5 
> for (i in 1:nrow(passingset)){ 
+ company <- passingset$V1[i] 
+ if(Cl(company)[length(Cl(company))] < 5){ 
+  passingset <- passingset[!(passingset$V1 == company),, drop = FALSE] 
+ } else 
+  i = i + 1 
+ 
+ rm(company) 
+ } 
**Error in Cl(company) : 
    subscript out of bounds: no column name containing "Close"** 

回答

1

無需循環! 假定您已經閱讀價格系列getSymbols你上面提到的,那麼:

# an example set of tickers: 
pasingset <- data.frame(V1=c('CWB','EEM','VTI','NAK','GIG'),stringsAsFactors = F) 

# this gets you the last closings of your tickers 
lastClose <- sapply(pasingset$V1,function(x) xts::last(Cl(get(x)))) 

# shows the tickers which have a close > 5 
pasingset$V1[which(lastClose > 5)] 
[1] "CWB" "EEM" "VTI" 
+0

@hvollmerier非常感謝!當我嘗試第二行代碼時,它仍然給我「get(x)中的錯誤:無效的第一個參數」。你有沒有遇到過這個? – Montosh123

+0

@hotterthanmath,因爲函數'last'被多個包使用我只能假設你可能有其他包加載,它們使用相同名稱的函數。爲了確保使用'xts-package'中的函數來編寫'xts :: last'而不是'last'。另一個可能的問題可能是您的csv文件沒有與從雅虎下載的文件相同的結構/列名稱。要檢查下載與我的例子中使用雅虎的'getSymbols'完全相同的代碼。你不應該看到一個錯誤。 – hvollmeier