如何将股票数据从xts对象转换为ts对象

时间:2018-08-16 03:27:38

标签: r time-series xts

我使用quantmod从雅虎财经下载股票数据。这里的msft是一个xts对象。

library(quantmod)
library(forecast)
library(xts)
library(zoo)
start <- as.Date('2018-01-01')
end <- as.Date('2018-08-14')
getSymbols('MSFT', src='yahoo', from=start, to=end)
msft <- MSFT[, 'MSFT.Adjusted']

我正在尝试将xts对象转换为ts对象。以下是我的工作。我的结果有点奇怪。在这种情况下,我应该设定什么频率?库存数据是每日数据(仅工作日)。非常感谢您的帮助。

ts(msft, start=c(2018,1,1), frequency = 365)

2 个答案:

答案 0 :(得分:0)

我希望这会有所帮助

$str = 'a: 7: {s: 3: "mon";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "tue";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "wed";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "thu";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "fri";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "sat";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}s: 3: "sun";a: 2: {s: 5: "start";s: 5: "09:00";s: 3: "end";s: 5: "21:00";}}';

$data = unserialize(str_replace(' ', '', $str));

foreach($data as $key=>$value)
{
    echo $key." ".$value['start']." ".$value['end']."<br/>";
}

您可以从以下代码中选择工作日

msft1<- as.data.frame(msft) #converting it to Data frame 
rownames(msft1) <- NULL #Nullify all the rownames 

timeseries<-ts(msft1, start=c(2018,1,1), frequency = 365) #convert it into a ts object
plot(timeseries) ## Plot to verify the time series 

答案 1 :(得分:0)

您可以使用as.timeSeries.xts库中的xts

msft <- as.timeSeries.xts(MSFT)
str(as.timeSeries.xts(msft))
plot(msft)