使用R语言quantmod获取多只股票代码时出现getSymbols.173错误的解决
Hey, nice job tracking down the fix for that weird quantmod error! Let's walk through what was going on here, and why your solution works so well.
What Caused the Strange Error
That confusing getSymbols.173 message boils down to a data type mismatch in the argument you passed to getSymbols.
Looking at your print(stocks[3,1]) output:
[1] AEROMEX.MX
173 Levels: AC.MX ACTINVRB.MX AEROMEX.MX AG.MX AGUA.MX ALFAA.MX ALPEKA.MX ALSEA.MX AMXA.MX AMXL.MX ... WALMEX.MX
The 173 Levels line tells us that stocks[i,1] is a factor (R's categorical data type), not a plain character string. When getSymbols gets a factor instead of the string it expects, its internal code messes up and tries to call a non-existent function named getSymbols.[number of factor levels]—in this case, getSymbols.173—which is why you saw that error.
Why Your Revised Code Works
Your fixed line:
AllSymbols[i]<-getSymbols(toString(stocks[i,1]),src="yahoo",from=date,to=Sys.Date(),auto.assign = FALSE)
Does two critical things correctly:
toString(stocks[i,1])converts the factor-type ticker symbol into a character string, which is exactly whatgetSymbolsneeds for its first argument.- You switched
auto.assign = TRUEtoFALSE:- With
auto.assign = TRUE,getSymbolsautomatically dumps the stock data into your global environment instead of returning a value you can assign toAllSymbols[i]. - Setting it to
FALSEmakesgetSymbolsreturn the ticker string, which properly fills yourAllSymbolsarray.
- With
Extra Tips to Make This Easier
You can skip the conversion step entirely by adjusting how you read your CSV file:
# Read CSV and keep string columns as characters (not factors) stockNamesBMV <- read.csv("AccionesBMV.csv", header=TRUE, stringsAsFactors=FALSE) stocks <- stockNamesBMV[2]
Now stocks[i,1] will already be a character string, so you don't need toString() at all.
If you need to keep factors for other parts of your code, you can also use as.character() (the standard R method for converting factors to strings):
getSymbols(as.character(stocks[i,1]), src="yahoo", from=date, to=Sys.Date(), auto.assign=FALSE)
内容的提问来源于stack exchange,提问作者Makenshi

