[英]`as.POSIXct` get error with `“%Y-%m-%d %H:%M:%S”` format
[英]Edgy plot of a minute interval time series with POSIXct format %Y-%m-%d %H:%M:%S
首先感謝您的幫助。 我試圖 plot 一個股票價格,其時間間隔是非常 5 分鍾。 如果我將 plot 作為時間序列,則生成的 plot 非常前衛。 如果我只是簡單地 plot 價格就好像它是一個數字序列一樣,這是正確的。
library(tidyquant)
library(ggplot2)
Symb <- "spot"
intv<- "5min"
stock_daily <- tq_get(Symb, get = "alphavantage", av_fun = "TIME_SERIES_INTRADAY", interval = "5min", outputsize = "full")
這是數據:
> dput(head(stock_daily, 20))
structure(list(symbol = c("spot", "spot", "spot", "spot", "spot",
"spot", "spot", "spot", "spot", "spot", "spot", "spot", "spot",
"spot", "spot", "spot", "spot", "spot", "spot", "spot"), timestamp = structure(c(1591349700,
1591350000, 1591350300, 1591350600, 1591350900, 1591351200, 1591351500,
1591351800, 1591352100, 1591352400, 1591352700, 1591353000, 1591353300,
1591353600, 1591353900, 1591354200, 1591354500, 1591354800, 1591355100,
1591355400), tzone = "UTC", class = c("POSIXct", "POSIXt")),
open = c(179, 179.38, 180.53, 182.5249, 183.1, 183.4, 183.71,
183.76, 182.705, 181.92, 181.87, 181.9626, 181.99, 181.75,
182.29, 181.9, 181.56, 181.309, 181.37, 181.06), high = c(179.78,
181.51, 182.59, 183.48, 183.665, 183.79, 183.99, 184.155,
182.82, 182.19, 181.99, 182.4, 182.23, 182.27, 182.38, 181.91,
181.6, 181.7, 181.51, 181.1673), low = c(177.505, 179.33,
180.3, 182.18, 182.955, 182.83, 183.17, 182.64, 181.71, 181.09,
181.48, 181.62, 181.43, 181.75, 181.9, 181.43, 181.32, 181.2872,
181.02, 180.37), close = c(179.4, 180.6, 182.3, 183.11, 183.4685,
183.68, 183.655, 182.72, 182.08, 181.66, 181.99, 181.77,
181.6277, 182.27, 181.91, 181.6138, 181.51, 181.435, 181.1,
180.37), volume = c(55046, 24842, 20192, 13935, 19356, 19911,
11355, 12081, 11462, 9882, 5826, 8278, 5058, 6790, 4437,
6248, 4489, 9217, 4638, 12602)), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
#This gives the edgy line when the x-axis consists of time:
plot(stock_daily$timestamp, stock_daily$open, type = "l")
#This gives the smooth line when the x-axis is of index form:
plot(stock_daily$open, type = "l")
我試圖將數據 stock_daily 轉換為 xts object 但它不起作用。 我懷疑這可能是因為時間間隔不均等,例如數據是在 2020-06-23 11:30:00 提供的,但是下一個是 2020-06-23 11:45:00。 它跳過了 11:35:00 和 11:40:00。 但是,我添加了這兩個缺失的行,其值為 NA 並再次嘗試,它仍然無法正常工作。
我找到了問題的根源。 數據不像時間那樣連續,例如周末沒有數據。 plot 或 ggplot function 連接每個數據點之間的線,但這些點的間距不等,因此我們在前衛的 Z32FA6E1B78A9D4028953E60564A2AA4 中看到那些長線。 解決方案是使用其他 plot 函數,例如專為金融數據建模而設計的 chartSeries()。 或者我們可以將時間序列轉換為數據框,其中時間索引保存為單獨的列。 這樣我們可以 plot 數據,並將時間列添加為 x 標簽。
類似問題還有另一篇文章: ggplot: Plotting timeseries data with missing values
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.