Home > Back-end >  How can I print the Dates of an equity in quantmod package in R?
How can I print the Dates of an equity in quantmod package in R?

Time:03-23

I want to load the 5 years history of Tesla equity from quanatmod package in R.Doing so I have :

tsla <- quantmod::getSymbols("TSLA", from = base::as.Date("2017-01-01"), to = base::as.Date("2022-01-31"), auto.assign = F)
tsla = as_tibble(tsla)
head(tsla)

But I also want a column with the dates on each index.How can this be done without just adding dates, because these prices correspond to specific dates .

CodePudding user response:

We may use rownames_to_column after converting to data.frame from the xts output.

library(dplyr)
library(tibble)
tsla %>% 
   as.data.frame %>% 
   rownames_to_column("Index")

-output

      Index TSLA.Open TSLA.High TSLA.Low TSLA.Close TSLA.Volume TSLA.Adjusted
1 2017-01-03    42.972    44.066   42.192     43.398    29616500        43.398
2 2017-01-04    42.950    45.600   42.862     45.398    56067500        45.398
3 2017-01-05    45.284    45.496   44.390     45.350    29558500        45.350
4 2017-01-06    45.386    46.062   45.090     45.802    27639500        45.802
5 2017-01-09    45.794    46.384   45.600     46.256    19897500        46.256
6 2017-01-10    46.400    46.400   45.378     45.974    18300000        45.974
...

Or it can be done with fortify.zoo

zoo::fortify.zoo(tsla)

CodePudding user response:

Just print the TSLA xts object. ( fortify.zoo(TSLA) converts it to a data frame with the index in the first column but isn't really needed for simply printing it.)

library(quantmod)
getSymbols("TSLA", from = "2017-01-01", to = "2022-01-31")
TSLA

giving:

           TSLA.Open TSLA.High TSLA.Low TSLA.Close TSLA.Volume TSLA.Adjusted
2017-01-03    42.972    44.066   42.192     43.398    29616500        43.398
2017-01-04    42.950    45.600   42.862     45.398    56067500        45.398
2017-01-05    45.284    45.496   44.390     45.350    29558500        45.350
2017-01-06    45.386    46.062   45.090     45.802    27639500        45.802
2017-01-09    45.794    46.384   45.600     46.256    19897500        46.256
2017-01-10    46.400    46.400   45.378     45.974    18300000        45.974
...etc...
  • Related