将带有日期列的数据框转换为时间序列 [英] Convert data frame with date column to timeseries
问题描述
我有一个包含以下数据的数据框:
I've got a data frame with the following data:
>PRICE
DATE CLOSE
1 20070103 54.700
2 20070104 54.770
3 20070105 55.120
4 20070108 54.870
5 20070109 54.860
6 20070110 54.270
7 20070111 54.770
8 20070112 55.360
9 20070115 55.760
...
如您所见,我的 DATE 列代表日期 (yyyyMMdd),而我的 CLOSE 列代表价格.
As you can see my DATE column represents a date (yyyyMMdd) and my CLOSE column represents prices.
我现在必须从 PerformanceAnalytics 包计算 CalmarRatio.
I now have to calculate CalmarRatio, from the PerformanceAnalytics package.
我是 R 的新手,所以我无法理解所有内容,但是从我在 google 上搜索的内容到现在我看到该函数的 R 参数需要是一个类似时间序列的对象.
I'm new to R, so i can't understand everything, but from what i have googled to the moment i see that the R parameter to that function needs to be a time-series-like object.
鉴于可能没有一段时间内的每个日期的数据(仅适用于我指定的日期),有什么方法可以将我的数组转换为时间序列对象?
Is there any way i can convert my array to a time-series object given that there might not be data for every date in a period (only for the ones i specify)?
推荐答案
您的 DATE
列可能表示日期,但它实际上是字符、因子、整数或数值向量.
Your DATE
column may represent a date, but it is actually either a character, factor, integer, or a numeric vector.
首先,您需要将 DATE
列转换为 Date
对象.然后,您可以从 PRICE
数据框架的 CLOSE
和 DATE
列创建一个 xts 对象.最后,您可以使用 xts 对象来计算收益和 Calmar 比率.
First, you need to convert the DATE
column to a Date
object. Then you can create an xts object from the CLOSE
and DATE
columns of your PRICE
data.frame. Finally, you can use the xts object to calculate returns and the Calmar ratio.
PRICE <- structure(list(
DATE = c(20070103L, 20070104L, 20070105L, 20070108L, 20070109L,
20070110L, 20070111L, 20070112L, 20070115L),
CLOSE = c(54.7, 54.77, 55.12, 54.87, 54.86, 54.27, 54.77, 55.36, 55.76)),
.Names = c("DATE", "CLOSE"), class = "data.frame",
row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"))
library(PerformanceAnalytics) # loads/attaches xts
# Convert DATE to Date class
PRICE$DATE <- as.Date(as.character(PRICE$DATE),format="%Y%m%d")
# create xts object
x <- xts(PRICE$CLOSE,PRICE$DATE)
CalmarRatio(Return.calculate(x))
# [,1]
# Calmar Ratio 52.82026
这篇关于将带有日期列的数据框转换为时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!