pandas examplesΒΆ
Calendar accepts pandas date-like inputs directly. The important point is that the top-level API remains NumPy-backed: pandas values are accepted as inputs, while outputs remain NumPy scalars or NumPy arrays: dates are datetime64[D] with NaT for missing values, counts are float64 with NaN for missing values, and isbizday vectors are masked arrays with fill_value=False.
[1]:
import pandas as pd
from bizdays import Calendar
cal = Calendar.load(name="ANBIMA")
Pandas DatetimeIndex values work directly with isbizday.
[2]:
dates = pd.to_datetime(["2014-01-12", "2014-01-13", None])
cal.isbizday(dates)
[2]:
masked_array(data=[False, True, --],
mask=[False, False, True],
fill_value=False)
Scalar pandas timestamps are accepted and still produce NumPy scalars.
[3]:
result = cal.following(pd.Timestamp("2015-12-25"))
result, type(result)
[3]:
(np.datetime64('2015-12-28'), numpy.datetime64)
Vectorized business-day calculations fit naturally into a DataFrame workflow.
[4]:
df = pd.DataFrame(
{
"trade_date": pd.to_datetime(["2024-01-02", "2024-01-03"]),
"settlement_date": pd.to_datetime(["2024-01-05", "2024-01-10"]),
}
)
df["bdays"] = cal.bizdays(df["trade_date"], df["settlement_date"])
df
[4]:
| trade_date | settlement_date | bdays | |
|---|---|---|---|
| 0 | 2024-01-02 | 2024-01-05 | 3.0 |
| 1 | 2024-01-03 | 2024-01-10 | 5.0 |
Results are positional NumPy arrays: the Series index is not kept. Assign a result straight to a column, as above. When you need a Series, pass index=.
[5]:
df2 = df.set_index(pd.Index(["a", "b"]))
pd.Series(cal.bizdays(df2["trade_date"], df2["settlement_date"]), index=df2.index)
[5]:
a 3.0
b 5.0
dtype: float64
Dates outside the calendar range raise DateOutOfRange. Check input dates first with inrange, and compute only the rows inside the range. filled(False) turns missing flags into False.
[6]:
loans = pd.DataFrame({"start": ["2024-01-02", "2024-01-03"], "maturity": ["2024-06-15", "2100-01-03"]})
ok = cal.inrange(loans.maturity).filled(False)
loans.loc[ok, "du"] = cal.bizdays(loans.start[ok], loans.maturity[ok])
loans
[6]:
| start | maturity | du | |
|---|---|---|---|
| 0 | 2024-01-02 | 2024-06-15 | 113.0 |
| 1 | 2024-01-03 | 2100-01-03 | NaN |
getdate also works with vectorized month references that come from pandas objects.
[7]:
months = pd.Index(["2024-01", "2024-02", "2024-03"])
cal.getdate("15th bizday", months)
[7]:
array(['2024-01-22', '2024-02-23', '2024-03-21'], dtype='datetime64[D]')
Missing pandas inputs are preserved as NaT (dates), NaN (counts) or masked values (isbizday), depending on the method.
[8]:
cal.bizdays(pd.to_datetime(["2024-01-02", None]), pd.Timestamp("2024-01-05"))
[8]:
array([ 3., nan])