如何在R中绘制资产股票价格?

时间:2020-07-06 16:25:42

标签: r finance

我正在尝试以R绘制资产股票价格。我正在从Yahoo Finance下载csv格式的数据,然后将其导入R,以便可以对其进行一些统计测试并绘制一些图。

我目前正在尝试绘制收盘价与日期的对比,但是我并没有取得多少成功。尽管我试图使用参数type =“ l”,但R只是将其绘制为一系列不同的点,并且不会将这些点与线连接起来。

price <- read.csv("~/Downloads/AAPL.csv")
plot(price$Date,price$Close,type="l")

我只是从这里获取数据:https://finance.yahoo.com/quote/AAPL/history?p=AAPL

无论我尝试哪种额外的参数,我每次都会得到这样的输出。

this

例如,我试图将其设置为红色,但完全没有改变。

谢谢!

3 个答案:

答案 0 :(得分:0)

问题在于 pric $ Date 是一个因素(分类变量),而不是数字。您可以使用 as.POSIXlt 将日期字符串转换为Posix时间戳,然后从中计算浮点表示形式,例如 year + yday / 366

答案 1 :(得分:0)

尝试一下

price$Date = as.Date(price$Date)
plot(price$Date,price$AAPL.Close,type="l",col=4)

或更好

library(quantmod)

fro = '2014-07-31'
Apple = getSymbols('AAPL',auto.assign = F,from=fro)
chartSeries(Apple,subset = "last 3 years")

enter image description here

答案 2 :(得分:0)

除非要创建烛台图,否则无需使用软件包。

df <- read.csv("AAPL.csv")
 > str(df)                      
 'data.frame':   254 obs. of  7 variables:
  $ Date     : Factor w/ 254 levels "2019-07-10","2019-07-11",..: 1 2 3 4 5 6 7 8 9 10 ...
  $ Open     : num  202 203 202 204 205 ...
  $ High     : num  204 204 204 206 206 ...
  $ Low      : num  202 202 202 204 204 ...
  $ Close    : num  203 202 203 205 204 ...
  $ Adj.Close: num  201 199 201 203 202 ...
  $ Volume   : int  17897100 20191800 17595200 16947400 16866800 14107500 18582200 20929300 22277900 18355200 ...
df$Date <- as.Date(df$Date)  # Otherwise it is treated as a factor variable
 > str(df)                   
 'data.frame':   254 obs. of  7 variables:
  $ Date     : Date, format: "2019-07-10" "2019-07-11" "2019-07-12" "2019-07-15" ...
  $ Open     : num  202 203 202 204 205 ...                                               
  $ High     : num  204 204 204 206 206 ...
  $ Low      : num  202 202 202 204 204 ...
  $ Close    : num  203 202 203 205 204 ...
  $ Adj.Close: num  201 199 201 203 202 ...
  $ Volume   : int  17897100 20191800 17595200 16947400 16866800 14107500 18582200 20929300 22277900 18355200 ...
plot(y=df$Close, x=df$Date, col="red", type = "l")  # look at ?plot for more details

enter image description here