Adding a new variable called 'Count', which Indexes or counts the occurrence of each stock_code based on their dates
Show older comments
Hi All, I need some guidance on adding incremental Count value to each stock_codes. I have a table with variables, Stock_code, date, close, low, high columns. I need help on, For example., Stocks: 200 Stocks totally, No.of Years: 1year(270 days, if we neglect holidays and suspension period etc.,). 1stock would have had 270 days, next stock might be having 200 days, 3rd like 230 days etc., So i need to add a variable called count, and it should have values like 1,2,3,4,5...270 for stock1, Repeat for Stock2 like 1,2,3,4,5...200, Stock3 like 1,2,3,4,5...230. Kindly advise how to achieve this.
5 Comments
Joshua
on 27 Mar 2017
Do you have any code written? What are you trying to do with the variable "count"? Is it going to be a column vector of numbers (say from 1 to 270) that will be displayed as a column of the table? If so you could try:
count=[1:270]'
And then add count into the table as another column.
Lakshmi Gandhi
on 27 Mar 2017
Andrei Bobrov
on 27 Mar 2017
Please attach small example your data here
Lakshmi Gandhi
on 27 Mar 2017
Lakshmi Gandhi
on 27 Mar 2017
Accepted Answer
More Answers (1)
Peter Perkins
on 27 Mar 2017
If you are using R2016b or later, you are almost certainly better off using a timetable, since those already have methods for lagging, synchronizing, aggregating, and so on. Prior to 16b, use varfun with 'GroupingVariables'. Andrei's code would be a one-liner. Since all you're doing here is assigning a monotonic index withing each group, using varfun seems a little like overkill, but I suspect once you do something more complicated, you'll appreciate it's power.
>> t = table({'a';'a';;'b';'b';'b'},datetime(2017,3,[21;22;22;23;24]),randn(5,1),'VariableNames',{'Symbol','Date','X'})
t =
5×3 table
Symbol Date X
______ ___________ ________
'a' 21-Mar-2017 0.32519
'a' 22-Mar-2017 -0.75493
'b' 22-Mar-2017 1.3703
'b' 23-Mar-2017 -1.7115
'b' 24-Mar-2017 -0.10224
>> tCount = varfun(@(x)(1:length(x))', t, 'GroupingVariables','Symbol','InputVariables','X');
>> t.Count = tCount.Fun_X
t =
5×4 table
Symbol Date X Count
______ ___________ ________ _____
'a' 21-Mar-2017 0.32519 1
'a' 22-Mar-2017 -0.75493 2
'b' 22-Mar-2017 1.3703 1
'b' 23-Mar-2017 -1.7115 2
'b' 24-Mar-2017 -0.10224 3
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!