Search code examples
kdb

Make a list with the quarter and year based on a date range of quarters KDB+/Q


I have a list of date ranges for the past 8 quarters given by the below function

q) findLastYQuarters:{reverse("d"$(-3*til y)+m),'-1+"d"$(-3*-1+til y)+m:3 bar"m"$x}[currentDate;8]
q) findLastYQuarters
2020.01.01 2020.03.31
2020.04.01 2020.06.30
2020.07.01 2020.09.30
2020.10.01 2020.12.31
2021.01.01 2021.03.31
2021.04.01 2021.06.30
2021.07.01 2021.09.30
2021.10.01 2021.12.31

I need to produce a separate list that labels each item in this list by a specific format; the second list would need to be

1Q20,2Q20,3Q20,4Q20,1Q21,2Q21,3Q21,4Q21

This code needs to be able to run on it's own, so how can I take the first list as an input and produce the second list? I thought about casting the latter date in the range as a month and dividing it by 3 to get the quarter and extracting the year, but I couldn't figure out how to actually implement that. Any advice would be much appreciated!


Solution

  • I'm sure there are many ways to solve this, a function like f defined below would do the trick:

    q)f:{`$string[1+mod[`month$d;12]%3],'"Q",/:string[`year$d:x[;0]][;2 3]}
    q)lyq
    2020.01.01 2020.03.31
    2020.04.01 2020.06.30
    2020.07.01 2020.09.30
    2020.10.01 2020.12.31
    2021.01.01 2021.03.31
    2021.04.01 2021.06.30
    2021.07.01 2021.09.30
    2021.10.01 2021.12.31
    q)f lyq
    `1Q20`2Q20`3Q20`4Q20`1Q21`2Q21`3Q21`4Q21