如何将数据帧转换为时间序列? [英] How to convert dataframe into time series?
问题描述
我有一个csv文件,其中有2个股票的收盘价(每天)
I have one csv file in which I have 2 closing prices of stock(on daily basis)
Dates Bajaj_close Hero_close
3/14/2013 1854.8 1669.1
3/15/2013 1850.3 1684.45
3/18/2013 1812.1 1690.5
3/19/2013 1835.9 1645.6
3/20/2013 1840 1651.15
3/21/2013 1755.3 1623.3
3/22/2013 1820.65 1659.6
3/25/2013 1802.5 1617.7
3/26/2013 1801.25 1571.85
3/28/2013 1799.55 1542
我想将上述数据转换为时间序列格式. (开始日期为3/14/2013
并且结束日期为3/13/2015
)我已经尝试过了,但是它给了我一些奇怪的输出结果
I want to convert above data into time series format. (start date is 3/14/2013
and end date is 3/13/2015
) I have tried this but its giving me some weird output
values <- bajaj_hero[, -1] (excluded first column i.e date in real dataset)
bajaj_hero_timeseries <- ts(values,start=c(2013,1),end=c(2015,3),frequency=365)
输出为:
Bajaj_close Hero_close
2013.000 1854.80 1669.10
2013.003 1850.30 1684.45
2013.005 1812.10 1690.50
2013.008 1835.90 1645.60
2013.011 1840.00 1651.15
2013.014 1755.30 1623.30
2013.016 1820.65 1659.60
2013.019 1802.50 1617.70
2013.022 1801.25 1571.85
推荐答案
R具有多种重新设置时间序列的方式.由于您使用的是股票的每日价格,因此您可能希望考虑金融市场在周末和工作假期休市,因此交易日和日历日不相同.但是,您可能需要在交易日和日历日方面使用时间序列.例如,无论周末是否介入,每日收益都是根据连续的每日收盘价计算得出的.但是您可能还想进行基于日历的报告,例如每周价格摘要.由于这些原因,xts包是zoo的扩展,通常与R中的财务数据一起使用.下面是如何与数据一起使用的示例.
R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.
假设示例中显示的数据在数据帧df中
Assuming the data shown in your example is in the dataframe df
library(xts)
stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
# daily returns
#
returns <- diff(stocks, arithmetic=FALSE ) - 1
#
# weekly open, high, low, close reports
#
to.weekly(stocks$Hero_close, name="Hero")
给出输出
Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15 1669.1 1684.45 1669.1 1684.45
2013-03-22 1690.5 1690.50 1623.3 1659.60
2013-03-28 1617.7 1617.70 1542.0 1542.00
这篇关于如何将数据帧转换为时间序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!