R语言如何计算K线图开/收/高/低价格?补全循环遗漏数据
解决R中K线图OHLC计算与循环代码问题
嘿,针对你在R中计算K线图所需的*OHLC(Open, High, Low, Close)*数据以及循环代码的问题,我来帮你一步步解决!
一、R中计算OHLC的便捷工具包
其实不用自己手动写循环,R里有很多现成的工具可以高效完成每日开盘、最高、最低、收盘价的计算,推荐这几个实用方案:
1. quantmod包(金融时间序列专用)
这个包是为金融数据分析量身打造的,处理OHLC数据非常顺手,还能直接生成K线图:
# 安装并加载包 install.packages("quantmod") library(quantmod) # 先将InvoiceDate转换为标准时间格式 myData$InvoiceDate <- as.POSIXct(myData$InvoiceDate) # 使用to.daily函数自动按日期聚合生成OHLC数据 ohlc_data <- to.daily(myData$UnitPrice, indexAt = "days", drop.time = TRUE) # 转换为data.frame格式方便后续处理 ohlc_df <- as.data.frame(ohlc_data) # 重命名列名更直观 colnames(ohlc_df) <- c("Open", "High", "Low", "Close")
2. dplyr包(tidyverse风格分组聚合)
如果你习惯用tidyverse的语法,用dplyr分组计算会更灵活,逻辑和你自己写的循环完全一致,但代码更简洁易读:
install.packages("dplyr") library(dplyr) ohlc_df <- myData %>% # 提取日期部分 mutate(Date = as.Date(InvoiceDate)) %>% # 按日期分组 group_by(Date) %>% # 计算每日的OHLC summarise( Open = first(UnitPrice), High = max(UnitPrice), Low = min(UnitPrice), Close = last(UnitPrice) )
二、修复你的循环代码
你的循环逻辑是正确的,但确实会遗漏最后一个日期的数据——因为代码只有在遇到新日期时,才会把上一个日期的结果存入df,循环结束后最后一组数据还没被写入。只需要在循环结束后,追加最后一组数据的处理即可,同时我还修正了变量名和内置函数重名的问题:
修改后的完整代码:
df <- data.frame( open=double(), close=double(), minPrice=double(), maxPrice=double(), date=as.Date(character()) ) firstDate <- as.Date(myData$InvoiceDate[1]) firstOpen <- myData$UnitPrice[1] minPrice <- myData$UnitPrice[1] maxPrice <- myData$UnitPrice[1] for(row in 1:nrow(myData)) { actualDate <- as.Date(myData$InvoiceDate[row]) actualPrice <- myData$UnitPrice[row] if(actualDate == firstDate) { if(minPrice > actualPrice) { minPrice <- actualPrice } if(maxPrice < actualPrice) { maxPrice <- actualPrice } } if(actualDate != firstDate) { open <- firstOpen close <- myData$UnitPrice[row-1] date <- as.Date(myData$InvoiceDate[row-1]) values <- data.frame(open, close, minPrice, maxPrice, date) df <- rbind(df, values) firstDate <- actualDate firstOpen <- myData$UnitPrice[row] minPrice <- myData$UnitPrice[row] maxPrice <- myData$UnitPrice[row] } } # 循环结束后,追加最后一个日期的数据 last_open <- firstOpen last_close <- myData$UnitPrice[nrow(myData)] last_date <- firstDate last_values <- data.frame(open=last_open, close=last_close, minPrice, maxPrice, date=last_date) df <- rbind(df, last_values)
这样修改后,2018-01-04的日期数据就会被正确加入到结果df中了。
内容的提问来源于stack exchange,提问作者Mandy
相关产品推荐
相关产品推荐

