我正在尝试绘制全年苹果股票数据的时间序列,我可以使用命令chart_series,但我想自己制作,使用ggplot。
我正在练习来自tidyquant包的AAPl股票数据,但它没有给日期列一个列名,我试图添加一个名称给它,但是当我尝试它改变旁边的列名而不是日期列。
library('tidyquant')
(tidyquant)
install.packages('tidyquant')
library(tidyquant)
getSymbols('AAPL',from = '2021-01-01',to = '2021-09-23',warning=FALSE,auto.sign=TRUE)
AAPL.Open AAPL.High AAPL.Low AAPL.Close
2021-01-04 133.52 133.61 126.76 129.41
2021-01-05 128.89 131.74 128.43 131.01
2021-01-06 127.72 131.05 126.38 126.60
2021-01-07 128.36 131.63 127.86 130.92
2021-01-08 132.43 132.63 130.23 132.05
2021-01-11 129.19 130.17 128.50 128.98
我试过这个代码,它不工作
head(AAPL)
View(AAPL)
AAPL<-cbind(rownames(AAPL),AAPL)
rownames(AAPL)<-NULL
colnames(AAPL)[0]<-'Dates'
View(AAPL)
OP有可能使用quantmod
而不是tidyquant
来获取数据
library(quantmod)
getSymbols("AAPL")
是建立在matrix
类基础上的xts
数据。
> str(AAPL)
An ‘xts’ object on 2007-01-03/2021-09-22 containing:
Data: num [1:3707, 1:6] 3.08 3 3.06 3.07 3.09 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "yahoo"
$ updated: POSIXct[1:1], format: "2021-09-23 20:26:13"
因此,如果cbind
带有索引或行名,它将类从数字转换为字符,因为matrix
只能有一个类。一个选项是使用fortify.zoo
转换为data.frame
AAPL <- fortify.zoo(AAPL)
names(AAPL)[1] <- "Dates"
现在,我们再次检查结构
> str(AAPL)
'data.frame': 3707 obs. of 7 variables:
$ Dates : Date, format: "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-08" ...
$ AAPL.Open : num 3.08 3 3.06 3.07 3.09 ...
$ AAPL.High : num 3.09 3.07 3.08 3.09 3.32 ...
$ AAPL.Low : num 2.92 2.99 3.01 3.05 3.04 ...
$ AAPL.Close : num 2.99 3.06 3.04 3.05 3.31 ...
$ AAPL.Volume : num 1.24e+09 8.47e+08 8.35e+08 7.97e+08 3.35e+09 ...
$ AAPL.Adjusted: num 2.57 2.63 2.61 2.62 2.84 ...
关于tidyquant
的使用,它返回一个tibble
,其中已经有一个列'date'用于日期
library(tidyquant)
aapl <- tq_get('AAPL')
> aapl
# A tibble: 2,699 x 8
symbol date open high low close volume adjusted
<chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 AAPL 2011-01-03 11.6 11.8 11.6 11.8 445138400 10.1
2 AAPL 2011-01-04 11.9 11.9 11.7 11.8 309080800 10.2
3 AAPL 2011-01-05 11.8 11.9 11.8 11.9 255519600 10.2
4 AAPL 2011-01-06 12.0 12.0 11.9 11.9 300428800 10.2
5 AAPL 2011-01-07 11.9 12.0 11.9 12.0 311931200 10.3
6 AAPL 2011-01-10 12.1 12.3 12.0 12.2 448560000 10.5
7 AAPL 2011-01-11 12.3 12.3 12.1 12.2 444108000 10.5
8 AAPL 2011-01-12 12.3 12.3 12.2 12.3 302590400 10.6
9 AAPL 2011-01-13 12.3 12.4 12.3 12.3 296780400 10.6
10 AAPL 2011-01-14 12.4 12.4 12.3 12.4 308840000 10.7
# … with 2,689 more rows