0
>stk.dquote[, .(SecuCode, TradingDay, ChangePCT)]
    SecuCode TradingDay ChangePCT
 1:   000001 2013-07-25   0.00511
 2:   000002 2013-07-25  -0.00943
 3:   000004 2013-07-25  -0.02275
 4:   000005 2013-07-25   0.00447
 5:   000006 2013-07-25  -0.00487
---                              
790536:   603699 2014-11-11  -0.04537
790537:   603766 2014-11-11  -0.08306
790538:   603806 2014-11-11  -0.03491
790539:   603988 2014-11-11   0.09540
790540:   603993 2014-11-11   0.02569


> stk.dquote[, .N, by=SecuCode]
    SecuCode   N
  1:   000001 316
  2:   000002 316
  3:   000004 316
  4:   000005 316
  5:   000006 316
 ---             
2568:   603988   6
2569:   601015   5
2570:   603019   4
2571:   603011   3
2572:   603088   1

I try to do sth on this data.table

stk.dquote[, Momentum_1M := rollsum(ChangePCT, 21, fill = NA, align = 
"right"), by=SecuCode]

and i get

Error: k <= n is not TRUE

the number of some SecuCode in this data.table is less than 21. How can i sovle this, any help would be much appreciated..

Jason
  • 21
  • 3
  • not tested, but maybe `stk.dquote[, Momentum_1M := rollsum(ChangePCT, ifelse(.N > 21, 21, .N), fill = NA, align = "right"), by = SecuCode]` ? – Jaap May 10 '17 at 09:07
  • yeah,it could work, but i want get NA if .N <21 – Jason May 10 '17 at 09:32
  • You can do this solely with `data.table::shift` and `Reduce` combination, see [here](http://stackoverflow.com/a/33366290/3001626). It should work for k <= n too. – David Arenburg May 10 '17 at 09:56
  • thx, reduce in R same as in Python? – Jason May 10 '17 at 10:12
  • @Jaap thx, I try `stk.dquote[, Momentum_1M := ifelse(.N > 21, rollsum(ChangePCT, 21, fill = NA, align = "right"), as.numeric(NA)), by=SecuCode] `, but not work, the result is all NA – Jason May 11 '17 at 02:14

0 Answers0