Neda Fathi
Neda Fathi

Reputation: 13

how to deal with Special characters in stock symbol to download adj.close in R software

I need download VIX historical data with R software.and then pick the adjusted price I run the code

getSymbols("^VIX", from="2016-01-01" , to="2018-01-01") 

and download the data but when I want to pick only adjusted value with the code

^VIX <-^VIX$^VIX.Adjusted

I got this error:

Error: unexpected '^' in "^"

How can I fix it?

Upvotes: 0

Views: 113

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270448

1) ls() Your getSymbols command in the question is correct but the name which is used to store the data is slightly different than the Yahoo ticker symbol. Run ls() to see the names of the objects in your workspace and you will see that the name under which the data is stored is VIX and not ^VIX.

To get the adjusted close use Ad

vix.ad <- Ad(VIX)

2) auto.assign= Another way to do this is to use the auto.assign=argument like this. In this case we don't need to know the name since it returns the object rather than setting it in the global environment,

vix.ad <- Ad(getSymbols("^VIX", auto.assign = FALSE))

3) env= A different way to do this is to create an environment e to hold the data. The only object there is the one wanted. Since there is only one object in e using eapply to apply Ad to every object in e will apply it to the object of interest without knowing its name. eapply returns a list with one element per object in e but since e has only one object we can use [[1]] to get this single component and put it in an object using whatever name you choose. Below we called it vix.ad. Remove e at the end just in case this is repeated with another symbol since we wouldn't want to have two objects in e.

getSymbols("^VIX", env = e <- new.env())
vix.ad <- eapply(e, Ad)[[1]]
rm(e) # don't need e any more

Suggest you review all the quantmod help files: help(package = "quantmod")

Upvotes: 1

HoelR
HoelR

Reputation: 6583

library(tidyverse)
library(tidyquant)
library(magrittr)

tq_get("^VIX", 
       from = "2016-01-01",
       to = "2018-01-01") %>% 
  select(adjusted) %$% 
  mean(adjusted)

[1] 13.46264

Upvotes: 0

Related Questions