Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Functions to count number of periods #180

Open
chiraganand opened this issue Mar 21, 2024 · 0 comments
Open

Functions to count number of periods #180

chiraganand opened this issue Mar 21, 2024 · 0 comments

Comments

@chiraganand
Copy link
Member

In xts, they are: nweeks, nseconds, nmonths, etc.

Counting weeks in non-trivial, has to be done like this:

function count(dates::AbstractRange{Date}, ::Type{Week})
    numweeks::Int = 0
    firstmonday = findfirst(x -> dayofweek(x) == 1, dates)
    lastsunday = findlast(x -> dayofweek(x) == 7, dates)
    numweeks += firstmonday == 1 ? 0 : 1
    numweeks += lastsunday == lastindex(dates) ? 0 : 1
    numweeks += div((dates[lastsunday] - dates[firstmonday] + Day(1)).value, 7)
    numweeks
end

Performance

For sorted data

julia> dates = range(Date(1900, 1, 1), Date(2024, 12, 1), step=Day(1))
Date("1900-01-01"):Day(1):Date("2024-12-01")

julia> @btime count(dates, Week)
  182.734 ns (1 allocation: 16 bytes)
6518

julia> dd = collect(dates); @btime count(dd, Week, true)
  191.824 ns (1 allocation: 16 bytes)
6518

For unsorted data:

julia> dates_unsorted = sample(dates, length(dates), replace=true);

julia> @btime count(dates_unsorted, Week, false)
  46.837 μs (1 allocation: 16 bytes)
6518

The above algorithm is $O(1)$ for sorted data but for for unsorted data it is $O(n)$ but that’s the best we can get to. See this Discourse post for some more discussion.

Similarly, other methods can also be written for counting months, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant