-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
feat: add business_day_count function #15512
Merged
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
Copyright (c) 2005-2023, NumPy Developers. | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are | ||
met: | ||
|
||
* Redistributions of source code must retain the above copyright | ||
notice, this list of conditions and the following disclaimer. | ||
|
||
* Redistributions in binary form must reproduce the above | ||
copyright notice, this list of conditions and the following | ||
disclaimer in the documentation and/or other materials provided | ||
with the distribution. | ||
|
||
* Neither the name of the NumPy Developers nor the names of any | ||
contributors may be used to endorse or promote products derived | ||
from this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
use polars_core::prelude::arity::binary_elementwise_values; | ||
use polars_core::prelude::*; | ||
|
||
/// Count the number of business days between `start` and `end`, excluding `end`. | ||
pub fn business_day_count(start: &Series, end: &Series) -> PolarsResult<Series> { | ||
let start_dates = start.date()?; | ||
let end_dates = end.date()?; | ||
|
||
// TODO: support customising weekdays | ||
let week_mask: [bool; 7] = [true, true, true, true, true, false, false]; | ||
let n_business_days_in_week_mask = week_mask.iter().filter(|&x| *x).count() as i32; | ||
|
||
let out = match (start_dates.len(), end_dates.len()) { | ||
(_, 1) => { | ||
if let Some(end_date) = end_dates.get(0) { | ||
start_dates.apply_values(|start_date| { | ||
business_day_count_impl( | ||
start_date, | ||
end_date, | ||
&week_mask, | ||
n_business_days_in_week_mask, | ||
) | ||
}) | ||
} else { | ||
Int32Chunked::full_null(start_dates.name(), start_dates.len()) | ||
} | ||
}, | ||
(1, _) => { | ||
if let Some(start_date) = start_dates.get(0) { | ||
end_dates.apply_values(|end_date| { | ||
business_day_count_impl( | ||
start_date, | ||
end_date, | ||
&week_mask, | ||
n_business_days_in_week_mask, | ||
) | ||
}) | ||
} else { | ||
Int32Chunked::full_null(start_dates.name(), end_dates.len()) | ||
} | ||
}, | ||
_ => binary_elementwise_values(start_dates, end_dates, |start_date, end_date| { | ||
business_day_count_impl( | ||
start_date, | ||
end_date, | ||
&week_mask, | ||
n_business_days_in_week_mask, | ||
) | ||
}), | ||
}; | ||
Ok(out.into_series()) | ||
} | ||
|
||
/// Ported from: | ||
/// https://github.com/numpy/numpy/blob/e59c074842e3f73483afa5ddef031e856b9fd313/numpy/_core/src/multiarray/datetime_busday.c#L355-L433 | ||
fn business_day_count_impl( | ||
mut start_date: i32, | ||
mut end_date: i32, | ||
week_mask: &[bool; 7], | ||
n_business_days_in_week_mask: i32, | ||
) -> i32 { | ||
let swapped = start_date > end_date; | ||
if swapped { | ||
(start_date, end_date) = (end_date, start_date); | ||
start_date += 1; | ||
end_date += 1; | ||
} | ||
|
||
let mut start_weekday = weekday(start_date); | ||
let diff = end_date - start_date; | ||
let whole_weeks = diff / 7; | ||
let mut count = 0; | ||
count += whole_weeks * n_business_days_in_week_mask; | ||
start_date += whole_weeks * 7; | ||
while start_date < end_date { | ||
if unsafe { *week_mask.get_unchecked(start_weekday) } { | ||
count += 1; | ||
} | ||
start_date += 1; | ||
start_weekday += 1; | ||
if start_weekday >= 7 { | ||
start_weekday = 0; | ||
} | ||
} | ||
if swapped { | ||
-count | ||
} else { | ||
count | ||
} | ||
} | ||
|
||
fn weekday(x: i32) -> usize { | ||
// the first modulo might return a negative number, so we add 7 and take | ||
// the modulo again so we're sure we have something between 0 (Monday) | ||
// and 6 (Sunday) | ||
(((x - 4) % 7 + 7) % 7) as usize | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
use std::fmt::{Display, Formatter}; | ||
|
||
use polars_core::prelude::*; | ||
#[cfg(feature = "serde")] | ||
use serde::{Deserialize, Serialize}; | ||
|
||
use crate::dsl::SpecialEq; | ||
use crate::map_as_slice; | ||
use crate::prelude::SeriesUdf; | ||
|
||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] | ||
#[derive(Clone, PartialEq, Debug, Eq, Hash)] | ||
pub enum BusinessFunction { | ||
#[cfg(feature = "business")] | ||
BusinessDayCount, | ||
} | ||
|
||
impl Display for BusinessFunction { | ||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
use BusinessFunction::*; | ||
let s = match self { | ||
#[cfg(feature = "business")] | ||
&BusinessDayCount => "business_day_count", | ||
}; | ||
write!(f, "{s}") | ||
} | ||
} | ||
impl From<BusinessFunction> for SpecialEq<Arc<dyn SeriesUdf>> { | ||
fn from(func: BusinessFunction) -> Self { | ||
use BusinessFunction::*; | ||
match func { | ||
#[cfg(feature = "business")] | ||
BusinessDayCount => { | ||
map_as_slice!(business_day_count) | ||
}, | ||
} | ||
} | ||
} | ||
|
||
#[cfg(feature = "business")] | ||
pub(super) fn business_day_count(s: &[Series]) -> PolarsResult<Series> { | ||
let start = &s[0]; | ||
let end = &s[1]; | ||
polars_ops::prelude::business_day_count(start, end) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
use super::*; | ||
|
||
#[cfg(feature = "dtype-date")] | ||
pub fn business_day_count(start: Expr, end: Expr) -> Expr { | ||
let input = vec![start, end]; | ||
|
||
Expr::Function { | ||
input, | ||
function: FunctionExpr::Business(BusinessFunction::BusinessDayCount {}), | ||
options: FunctionOptions { | ||
allow_rename: true, | ||
..Default::default() | ||
}, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This could lead to problems as we want to distribute as MIT/Apache. But I also don't believe this required. You have interpreted their source code and written it as Rust. I think a link with credits should suffice.