代码之家  ›  专栏  ›  技术社区  ›  AIM

使用NAS的时间序列矩阵

  •  0
  • AIM  · 技术社区  · 6 年前

    我有一个数据框架,其中第一行包含货币名称,第二行包含日期,渴行包含这些日期的历史价格。

    如何将其转换为一个时间序列对象,该对象的列由不同的货币组成,行由这些日期的历史价格组成?问题是国企货币在某些日子里没有价格……如何用NAS填充并自动对齐它们?

    1 回复  |  直到 6 年前
        1
  •  1
  •   AIM    6 年前

    假设数据帧名为cryto.markets.post.2108,列名为“symbol”、“dates”和“close”表示收盘价。

    然后我会这样做:

    # Creates matrix whose columns are different crypto-currencies and whose rows are different times
    #---------------------------------------------------------------------------------------------------#
    # N Columns
    Col.coins<-unique(crypto.markets.post.2018$symbol);N.coins<-length(Col.coins) # Counts the number of coins in recent history
    
    
    # N Rows
    Row.coins<-seq(from=min(dates),to=max(dates),by=1);N.Rows<-length(Row.coins)
    
    # Initialize Matrix
    historical.max.min<-historical.volum<-historical.prices<-matrix(NA,nrow = N.Rows,ncol=N.coins); rownames(historical.prices)<-Row.coins; colnames(historical.prices)<-Col.coins
    
    # Writes data-frame of closing prices
    for(j.coin in 1:N.coins){
      time.series.iteration<-crypto.markets.post.2018$symbol == Col.coins[j.coin]#Loads timeseries of this iteration
      time.series.iteration<-crypto.markets.post.2018[time.series.iteration,]
      N.NAs.needed.for.corecsion<-N.Rows-length(as.Date(time.series.iteration$date)) # Determines the difference between the data-size and the matrix's dimensions (for incomplete time-series only :D)
      # Historical Prices
      historical.prices[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),time.series.iteration$close) # Tags on the ts length
      # Historical Volum
      historical.volum[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),time.series.iteration$volume) # Tags on the ts length
      # Difference between max and min
      historical.max.min[,j.coin]<-append(rep(NA,N.NAs.needed.for.corecsion),((time.series.iteration$high)-(time.series.iteration$low))
                                    ) # Tags on the ts length
    }