R语言绘制SPY日内30分钟K线图及均线的问题排查
问题解决步骤
1. 修复xts转换错误
你用spy30_reordered[,1]作为order.by参数时,因数据框是tibble,返回的是单列tibble而非POSIXct向量,导致xts无法识别。正确做法是提取POSIXct向量作为时间索引,同时排除原数据中的timestamp列(避免重复存储):
library(xts) # 提取时间向量,排除timestamp列作为xts的数据部分 spy_xts <- xts(spy30_reordered %>% select(-timestamp), order.by = spy30_reordered$timestamp) # 验证转换结果 head(spy_xts)
转换完成后,即可用quantmod正常绘制K线并添加均线:
library(quantmod) chartSeries(spy_xts, type = "candlesticks", theme = "white") # 添加14期30分钟均线 addSMA(n = 14, col = "red")
2. 修复ggplot2的K线显示问题
ggplot2本身没有geom_candlestick,需先安装加载ggalt包,同时正确映射涨跌颜色、适配30分钟周期的K线宽度:
library(ggplot2) library(ggalt) library(dplyr) # 添加涨跌颜色标识 spy30_reordered <- spy30_reordered %>% mutate(color = ifelse(close > open, "green", "red")) # 绘制K线图 ggplot(spy30_reordered, aes(x = timestamp)) + geom_candlestick(aes(open = open, high = high, low = low, close = close, fill = color), width = 60*30/2) # 宽度设为15分钟(单位:秒) scale_fill_identity() + # 直接使用color列的颜色值 theme_minimal() + labs(x = "时间", y = "价格")
3. 循环每日生成带14日均线的K线图
先按日期分组计算当日的14期30分钟滚动均线,再循环绘制并保存每日图表:
library(purrr) # 计算每日的14期滚动均线 spy30_reordered <- spy30_reordered %>% group_by(date) %>% mutate(dma14 = rollmean(close, k = 14, fill = NA, align = "right")) %>% ungroup() # 按日期拆分数据 daily_data <- split(spy30_reordered, spy30_reordered$date) # 循环绘制并保存 walk(daily_data, function(df) { plot_date <- unique(df$date) p <- ggplot(df, aes(x = timestamp)) + geom_candlestick(aes(open = open, high = high, low = low, close = close, fill = color), width = 60*30/2) + geom_line(aes(y = dma14), color = "blue", size = 0.8, na.rm = TRUE) + scale_fill_identity() + theme_minimal() + labs(title = paste("SPY 30分钟K线 + 14期均线 -", plot_date), x = "时间", y = "价格") # 保存图片,文件名用日期命名 ggsave(paste0("spy_kline_", plot_date, ".png"), p, width = 10, height = 6) })
关键注意点
- xts转换必须用POSIXct向量作为
order.by,不能用tibble的单列数据框 - ggplot绘制K线依赖
ggalt包,需手动设置K线宽度适配30分钟周期 - 14日均线按日期分组计算,确保只在当日的30分钟数据内滚动
内容的提问来源于stack exchange,提问作者user2275413
相关产品推荐
相关产品推荐

