mirror of
https://github.com/Magnus167/msyrs.git
synced 2025-11-19 20:06:10 +00:00
Compare commits
16 Commits
328fb24509
...
rawdf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19e91cfe47 | ||
| 4e4d1c6625 | |||
|
|
cfbd54be7a | ||
|
|
a4645dbc93 | ||
|
|
658eb0d121 | ||
|
|
93f88ab537 | ||
|
|
39d1a1b632 | ||
|
|
28ff5c95cf | ||
|
|
8343e93b46 | ||
|
|
b4d42c1dda | ||
|
|
2b969f4eaf | ||
|
|
1d301b45b7 | ||
|
|
4f60e31d55 | ||
|
|
d938d9adc3 | ||
|
|
5a5bd4777d | ||
|
|
cf2779c5a1 |
360
notebooks/funcwise/bdate_range_util.ipynb
Normal file
360
notebooks/funcwise/bdate_range_util.ipynb
Normal file
@@ -0,0 +1,360 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# ! uv pip install E:\\Work\\ruzt\\msyrs --upgrade"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Import Python packages\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import macrosynergy\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import polars as pl\n",
|
||||||
|
"import os\n",
|
||||||
|
"import time\n",
|
||||||
|
"\n",
|
||||||
|
"from macrosynergy.panel import view_timelines\n",
|
||||||
|
"from macrosynergy.management.types import QuantamentalDataFrame\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Import Python bindings - `msyrs`\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import msyrs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/html": [
|
||||||
|
"<div>\n",
|
||||||
|
"<style scoped>\n",
|
||||||
|
" .dataframe tbody tr th:only-of-type {\n",
|
||||||
|
" vertical-align: middle;\n",
|
||||||
|
" }\n",
|
||||||
|
"\n",
|
||||||
|
" .dataframe tbody tr th {\n",
|
||||||
|
" vertical-align: top;\n",
|
||||||
|
" }\n",
|
||||||
|
"\n",
|
||||||
|
" .dataframe thead th {\n",
|
||||||
|
" text-align: right;\n",
|
||||||
|
" }\n",
|
||||||
|
"</style>\n",
|
||||||
|
"<table border=\"1\" class=\"dataframe\">\n",
|
||||||
|
" <thead>\n",
|
||||||
|
" <tr style=\"text-align: right;\">\n",
|
||||||
|
" <th></th>\n",
|
||||||
|
" <th>bdates</th>\n",
|
||||||
|
" <th>0</th>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" </thead>\n",
|
||||||
|
" <tbody>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>0</th>\n",
|
||||||
|
" <td>2000-01-03</td>\n",
|
||||||
|
" <td>2000-01-03</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1</th>\n",
|
||||||
|
" <td>2000-01-10</td>\n",
|
||||||
|
" <td>2000-01-10</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>2</th>\n",
|
||||||
|
" <td>2000-01-17</td>\n",
|
||||||
|
" <td>2000-01-17</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>3</th>\n",
|
||||||
|
" <td>2000-01-24</td>\n",
|
||||||
|
" <td>2000-01-24</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>4</th>\n",
|
||||||
|
" <td>2000-01-31</td>\n",
|
||||||
|
" <td>2000-01-31</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>...</th>\n",
|
||||||
|
" <td>...</td>\n",
|
||||||
|
" <td>...</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1056</th>\n",
|
||||||
|
" <td>2020-03-30</td>\n",
|
||||||
|
" <td>2020-03-30</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1057</th>\n",
|
||||||
|
" <td>2020-04-06</td>\n",
|
||||||
|
" <td>2020-04-06</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1058</th>\n",
|
||||||
|
" <td>2020-04-13</td>\n",
|
||||||
|
" <td>2020-04-13</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1059</th>\n",
|
||||||
|
" <td>2020-04-20</td>\n",
|
||||||
|
" <td>2020-04-20</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" <tr>\n",
|
||||||
|
" <th>1060</th>\n",
|
||||||
|
" <td>2020-04-27</td>\n",
|
||||||
|
" <td>2020-04-27</td>\n",
|
||||||
|
" </tr>\n",
|
||||||
|
" </tbody>\n",
|
||||||
|
"</table>\n",
|
||||||
|
"<p>1061 rows × 2 columns</p>\n",
|
||||||
|
"</div>"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
" bdates 0\n",
|
||||||
|
"0 2000-01-03 2000-01-03\n",
|
||||||
|
"1 2000-01-10 2000-01-10\n",
|
||||||
|
"2 2000-01-17 2000-01-17\n",
|
||||||
|
"3 2000-01-24 2000-01-24\n",
|
||||||
|
"4 2000-01-31 2000-01-31\n",
|
||||||
|
"... ... ...\n",
|
||||||
|
"1056 2020-03-30 2020-03-30\n",
|
||||||
|
"1057 2020-04-06 2020-04-06\n",
|
||||||
|
"1058 2020-04-13 2020-04-13\n",
|
||||||
|
"1059 2020-04-20 2020-04-20\n",
|
||||||
|
"1060 2020-04-27 2020-04-27\n",
|
||||||
|
"\n",
|
||||||
|
"[1061 rows x 2 columns]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"x = msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='W').to_pandas()\n",
|
||||||
|
"y = pd.Series(pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='W-MON'))\n",
|
||||||
|
"\n",
|
||||||
|
"pd.concat([x, y], axis=1)\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Results for M\t & \tBMS\t are exactly the same\n",
|
||||||
|
"Results for Q\t & \tBQS\t are exactly the same\n",
|
||||||
|
"Results for W\t & \tW-MON\t are exactly the same\n",
|
||||||
|
"Results for WF\t & \tW-FRI\t are exactly the same\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"for rs_freq, pd_freq in [('M', 'BMS'), ('Q', 'BQS'), ('W', 'W-MON'), ('WF', 'W-FRI')]:\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" x = msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq=rs_freq).to_pandas()\n",
|
||||||
|
" y = pd.Series(pd.bdate_range(start='2000-01-01', end='2020-05-01', freq=pd_freq))\n",
|
||||||
|
"\n",
|
||||||
|
" e = x == y\n",
|
||||||
|
" res = e.all()\n",
|
||||||
|
" non_matching_df = pd.concat([x[~e], y[~e]], axis=1)\n",
|
||||||
|
" assert res, f\"Results for {rs_freq}\\t and \\t{pd_freq}\\t are not the same\\n{non_matching_df}\"\n",
|
||||||
|
" print(f\"Results for {rs_freq}\\t & \\t{pd_freq}\\t are exactly the same\")\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"23.5 μs ± 1.02 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n",
|
||||||
|
"67.4 μs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n",
|
||||||
|
"1.97 ms ± 57.3 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"4.65 ms ± 170 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"28.3 ms ± 898 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n",
|
||||||
|
"93.8 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='D')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='1971-01-01', end_date='2040-05-01', freq='D')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='2000-01-01', end_date='2020-05-01', freq='D')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='1971-01-01', end_date='2040-05-01', freq='D')\n",
|
||||||
|
"%timeit pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='B')\n",
|
||||||
|
"%timeit pd.bdate_range(start='1971-01-01', end='2040-05-01', freq='B')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"7.95 μs ± 146 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"17.9 μs ± 108 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"1.73 ms ± 20.8 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"4 ms ± 69.3 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"5.69 ms ± 139 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"19.1 ms ± 268 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='WF')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='1971-01-01', end_date='2040-05-01', freq='WF')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='2000-01-01', end_date='2020-05-01', freq='WF')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='1971-01-01', end_date='2040-05-01', freq='WF')\n",
|
||||||
|
"%timeit pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='W-FRI')\n",
|
||||||
|
"%timeit pd.bdate_range(start='1971-01-01', end='2040-05-01', freq='W-FRI')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"6.9 μs ± 126 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"13.1 μs ± 93.3 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"1.73 ms ± 29.3 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"4.2 ms ± 81.5 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"931 μs ± 14.2 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"3.05 ms ± 47.5 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='ME')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='1971-01-01', end_date='2040-05-01', freq='ME')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='2000-01-01', end_date='2020-05-01', freq='ME')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='1971-01-01', end_date='2040-05-01', freq='ME')\n",
|
||||||
|
"%timeit pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='BME')\n",
|
||||||
|
"%timeit pd.bdate_range(start='1971-01-01', end='2040-05-01', freq='BME')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.65 μs ± 69.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"4.78 μs ± 38.7 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"1.73 ms ± 122 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"4.16 ms ± 286 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"340 μs ± 11.3 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
|
||||||
|
"1.1 ms ± 11.5 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='Q')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='1971-01-01', end_date='2040-05-01', freq='Q')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='2000-01-01', end_date='2020-05-01', freq='Q')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='1971-01-01', end_date='2040-05-01', freq='Q')\n",
|
||||||
|
"%timeit pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='BQS')\n",
|
||||||
|
"%timeit pd.bdate_range(start='1971-01-01', end='2040-05-01', freq='BQS')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.21 μs ± 83.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"3.66 μs ± 198 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
|
||||||
|
"2.67 ms ± 459 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"3.71 ms ± 143 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
|
||||||
|
"98.7 μs ± 1.47 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n",
|
||||||
|
"289 μs ± 15.3 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='2000-01-01', end_date='2020-05-01', freq='YE')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_opt(start_date='1971-01-01', end_date='2040-05-01', freq='YE')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='2000-01-01', end_date='2020-05-01', freq='YE')\n",
|
||||||
|
"%timeit msyrs.utils.get_bdates_series_default_pl(start_date='1971-01-01', end_date='2040-05-01', freq='YE')\n",
|
||||||
|
"%timeit pd.bdate_range(start='2000-01-01', end='2020-05-01', freq='BYE')\n",
|
||||||
|
"%timeit pd.bdate_range(start='1971-01-01', end='2040-05-01', freq='BYE')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": ".venv",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.12.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -5,18 +5,31 @@ use pyo3_polars::{PyDataFrame, PySeries};
|
|||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
#[pymodule]
|
#[pymodule]
|
||||||
pub fn utils(_py: Python, m: &PyModule) -> PyResult<()> {
|
pub fn utils(_py: Python, m: &PyModule) -> PyResult<()> {
|
||||||
m.add_function(wrap_pyfunction!(get_bdates_series_default, m)?)?;
|
m.add_function(wrap_pyfunction!(get_bdates_series_default_pl, m)?)?;
|
||||||
|
m.add_function(wrap_pyfunction!(get_bdates_series_default_opt, m)?)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pyfunction]
|
#[pyfunction]
|
||||||
pub fn get_bdates_series_default(
|
pub fn get_bdates_series_default_pl(
|
||||||
start_date: String,
|
start_date: String,
|
||||||
end_date: String,
|
end_date: String,
|
||||||
freq: Option<String>,
|
freq: Option<String>,
|
||||||
) -> PyResult<PySeries> {
|
) -> PyResult<PySeries> {
|
||||||
Ok(PySeries(
|
Ok(PySeries(
|
||||||
crate::utils::dateutils::get_bdates_series_default(start_date, end_date, freq)
|
crate::utils::dateutils::get_bdates_series_default_pl(start_date, end_date, freq)
|
||||||
|
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pyfunction]
|
||||||
|
pub fn get_bdates_series_default_opt(
|
||||||
|
start_date: String,
|
||||||
|
end_date: String,
|
||||||
|
freq: Option<String>,
|
||||||
|
) -> PyResult<PySeries> {
|
||||||
|
Ok(PySeries(
|
||||||
|
crate::utils::dateutils::get_bdates_series_default_opt(start_date, end_date, freq)
|
||||||
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?,
|
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{}", e)))?,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
281
src/core/dateseries.rs
Normal file
281
src/core/dateseries.rs
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
//! # DateSeries and BDateSeries Implementations
|
||||||
|
//!
|
||||||
|
//! This module provides two date-handling types using the [`chrono`](https://docs.rs/chrono) crate:
|
||||||
|
//!
|
||||||
|
//! - [`DateSeries`]: Stores any set of calendar dates and allows adding/subtracting *calendar days*.
|
||||||
|
//! - [`BDateSeries`]: Stores only Monday–Friday business days and interprets add/sub as *business day* shifts,
|
||||||
|
//! skipping weekends (e.g., adding 1 to Friday goes to Monday).
|
||||||
|
//!
|
||||||
|
//! Both types also provide a [`from_iso8601_range`](#method.from_iso8601_range) constructor
|
||||||
|
//! that builds a date series (or business‑date series) from a start/end string (YYYY‑MM‑DD).
|
||||||
|
|
||||||
|
use chrono::{Datelike, Duration, NaiveDate, ParseResult};
|
||||||
|
use std::ops::{Add, Sub};
|
||||||
|
|
||||||
|
/// Determines if the date is Saturday or Sunday.
|
||||||
|
fn is_weekend(date: NaiveDate) -> bool {
|
||||||
|
matches!(date.weekday(), chrono::Weekday::Sat | chrono::Weekday::Sun)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `DateSeries` stores a list of [`NaiveDate`] values and shifts by **calendar days**.
|
||||||
|
///
|
||||||
|
/// ## Example Usage
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use chrono::NaiveDate;
|
||||||
|
/// use msyrs::core::dateseries::DateSeries;
|
||||||
|
///
|
||||||
|
/// // Create from explicit dates
|
||||||
|
/// let ds = DateSeries::new(vec![
|
||||||
|
/// NaiveDate::from_ymd_opt(2023, 7, 14).unwrap(), // a Friday
|
||||||
|
/// NaiveDate::from_ymd_opt(2023, 7, 15).unwrap(), // a Saturday
|
||||||
|
/// ]);
|
||||||
|
///
|
||||||
|
/// // Shift forward by 5 calendar days
|
||||||
|
/// let ds_plus = ds + 5;
|
||||||
|
/// // 2023-07-14 + 5 => 2023-07-19 (Wednesday)
|
||||||
|
/// // 2023-07-15 + 5 => 2023-07-20 (Thursday)
|
||||||
|
///
|
||||||
|
/// assert_eq!(ds_plus.data()[0], NaiveDate::from_ymd_opt(2023, 7, 19).unwrap());
|
||||||
|
/// assert_eq!(ds_plus.data()[1], NaiveDate::from_ymd_opt(2023, 7, 20).unwrap());
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DateSeries {
|
||||||
|
data: Vec<NaiveDate>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DateSeries {
|
||||||
|
/// Creates a new `DateSeries` from a vector of [`NaiveDate`] values.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
/// - Does not panic on invalid weekend or anything; this type accepts all valid dates.
|
||||||
|
pub fn new(data: Vec<NaiveDate>) -> Self {
|
||||||
|
Self { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constructs a `DateSeries` by parsing an ISO‑8601 start/end string (YYYY‑MM‑DD)
|
||||||
|
/// and including **every calendar date** from start to end (inclusive).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// - Returns a [`chrono::ParseError`](chrono::ParseError) if parsing fails.
|
||||||
|
/// - Panics if `start` > `end` chronologically.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use msyrs::core::dateseries::DateSeries;
|
||||||
|
/// # fn main() -> Result<(), chrono::ParseError> {
|
||||||
|
/// let ds = DateSeries::from_iso8601_range("2023-07-14", "2023-07-16")?;
|
||||||
|
/// assert_eq!(ds.data().len(), 3);
|
||||||
|
/// # Ok(())
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
pub fn from_iso8601_range(start: &str, end: &str) -> ParseResult<Self> {
|
||||||
|
let start_date = NaiveDate::parse_from_str(start, "%Y-%m-%d")?;
|
||||||
|
let end_date = NaiveDate::parse_from_str(end, "%Y-%m-%d")?;
|
||||||
|
assert!(
|
||||||
|
start_date <= end_date,
|
||||||
|
"start date cannot be after end date"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut dates = Vec::new();
|
||||||
|
let mut current = start_date;
|
||||||
|
while current <= end_date {
|
||||||
|
dates.push(current);
|
||||||
|
current = current
|
||||||
|
.checked_add_signed(Duration::days(1))
|
||||||
|
.expect("Date overflow in from_iso8601_range");
|
||||||
|
}
|
||||||
|
Ok(Self::new(dates))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a reference to the underlying slice of dates.
|
||||||
|
pub fn data(&self) -> &[NaiveDate] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Internal helper applying a function to each date.
|
||||||
|
fn apply<F>(&self, op: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(NaiveDate) -> NaiveDate,
|
||||||
|
{
|
||||||
|
let new_data = self.data.iter().map(|&date| op(date)).collect();
|
||||||
|
Self { data: new_data }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implements adding calendar days to each `NaiveDate`.
|
||||||
|
///
|
||||||
|
/// If the shifted date goes out of chrono's valid range, it panics.
|
||||||
|
impl Add<i64> for DateSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn add(self, rhs: i64) -> Self::Output {
|
||||||
|
self.apply(|date| {
|
||||||
|
date.checked_add_signed(Duration::days(rhs))
|
||||||
|
.expect("Overflow in date addition")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implements subtracting calendar days from each `NaiveDate`.
|
||||||
|
///
|
||||||
|
/// If the shifted date goes out of chrono's valid range, it panics.
|
||||||
|
impl Sub<i64> for DateSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn sub(self, rhs: i64) -> Self::Output {
|
||||||
|
self.apply(|date| {
|
||||||
|
date.checked_sub_signed(Duration::days(rhs))
|
||||||
|
.expect("Overflow in date subtraction")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A “Business Date Series” for Monday–Friday only.
|
||||||
|
///
|
||||||
|
/// 1. The constructor disallows weekend dates (panics if any date is Sat/Sun).
|
||||||
|
/// 2. Adding or subtracting an `i64` interprets that integer as *business days*, skipping weekends.
|
||||||
|
/// For example, adding 1 to a Friday yields the following Monday.
|
||||||
|
///
|
||||||
|
/// ## Example Usage
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use chrono::NaiveDate;
|
||||||
|
/// use msyrs::core::dateseries::BDateSeries;
|
||||||
|
///
|
||||||
|
/// // Friday
|
||||||
|
/// let friday = NaiveDate::from_ymd_opt(2023, 7, 14).unwrap();
|
||||||
|
/// let mut bds = BDateSeries::new(vec![friday]);
|
||||||
|
///
|
||||||
|
/// // Adding 1 “business day” => next Monday, 2023-07-17
|
||||||
|
/// bds = bds + 1;
|
||||||
|
/// assert_eq!(bds.data()[0], NaiveDate::from_ymd_opt(2023, 7, 17).unwrap());
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BDateSeries {
|
||||||
|
data: Vec<NaiveDate>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BDateSeries {
|
||||||
|
/// Creates a new `BDateSeries`, panicking if any of the supplied dates is on Saturday/Sunday.
|
||||||
|
pub fn new(data: Vec<NaiveDate>) -> Self {
|
||||||
|
for &d in &data {
|
||||||
|
if is_weekend(d) {
|
||||||
|
panic!("BDateSeries cannot contain weekend dates: {}", d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Self { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constructs a `BDateSeries` by parsing an ISO‑8601 start/end string (YYYY‑MM‑DD).
|
||||||
|
///
|
||||||
|
/// Only Monday–Friday dates within `[start, end]` are included in the series.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// - Returns a [`chrono::ParseError`](chrono::ParseError) if parsing fails.
|
||||||
|
/// - Panics if `start` > `end` chronologically.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use msyrs::core::dateseries::BDateSeries;
|
||||||
|
/// # fn main() -> Result<(), chrono::ParseError> {
|
||||||
|
/// let bds = BDateSeries::from_iso8601_range("2023-07-14", "2023-07-18")?;
|
||||||
|
/// // 2023-07-14 (Friday), 2023-07-15 (Saturday) => skipped,
|
||||||
|
/// // 2023-07-16 (Sunday) => skipped,
|
||||||
|
/// // 2023-07-17 (Monday), 2023-07-18 (Tuesday)
|
||||||
|
/// // so total 3 valid business days
|
||||||
|
/// assert_eq!(bds.data().len(), 3);
|
||||||
|
/// # Ok(())
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
pub fn from_iso8601_range(start: &str, end: &str) -> ParseResult<Self> {
|
||||||
|
let start_date = NaiveDate::parse_from_str(start, "%Y-%m-%d")?;
|
||||||
|
let end_date = NaiveDate::parse_from_str(end, "%Y-%m-%d")?;
|
||||||
|
assert!(
|
||||||
|
start_date <= end_date,
|
||||||
|
"start date cannot be after end date"
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut dates = Vec::new();
|
||||||
|
let mut current = start_date;
|
||||||
|
while current <= end_date {
|
||||||
|
if !is_weekend(current) {
|
||||||
|
dates.push(current);
|
||||||
|
}
|
||||||
|
current = current
|
||||||
|
.checked_add_signed(Duration::days(1))
|
||||||
|
.expect("Date overflow in from_iso8601_range");
|
||||||
|
}
|
||||||
|
Ok(Self::new(dates))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a reference to the underlying slice of dates.
|
||||||
|
pub fn data(&self) -> &[NaiveDate] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Internal helper that tries to shift a date forward or backward by one day at a time,
|
||||||
|
/// skipping weekends, for a total of `delta` business days.
|
||||||
|
fn shift_business_days(date: NaiveDate, delta: i64) -> NaiveDate {
|
||||||
|
if delta == 0 {
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
|
||||||
|
let step = if delta > 0 { 1 } else { -1 };
|
||||||
|
let abs_delta = delta.abs();
|
||||||
|
|
||||||
|
let mut new_date = date;
|
||||||
|
for _ in 0..abs_delta {
|
||||||
|
// Move by 1 day in the correct direction
|
||||||
|
new_date = new_date
|
||||||
|
.checked_add_signed(Duration::days(step))
|
||||||
|
.expect("Overflow in BDateSeries add/sub");
|
||||||
|
// If we land on weekend, keep moving until Monday..Friday
|
||||||
|
while is_weekend(new_date) {
|
||||||
|
new_date = new_date
|
||||||
|
.checked_add_signed(Duration::days(step))
|
||||||
|
.expect("Overflow in BDateSeries skipping weekend");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
new_date
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Internal helper to apply a shift of `delta` business days to each date.
|
||||||
|
fn apply(&self, delta: i64) -> Self {
|
||||||
|
let new_data = self
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.map(|&date| Self::shift_business_days(date, delta))
|
||||||
|
.collect();
|
||||||
|
Self { data: new_data }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implement *business day* addition for `BDateSeries`.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
/// - If the resulting date(s) overflow `NaiveDate` range.
|
||||||
|
/// - `BDateSeries` is guaranteed to remain Monday..Friday after the shift.
|
||||||
|
impl Add<i64> for BDateSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn add(self, rhs: i64) -> Self::Output {
|
||||||
|
self.apply(rhs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implement *business day* subtraction for `BDateSeries`.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
/// - If the resulting date(s) overflow `NaiveDate`.
|
||||||
|
/// - `BDateSeries` is guaranteed to remain Monday..Friday after the shift.
|
||||||
|
impl Sub<i64> for BDateSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn sub(self, rhs: i64) -> Self::Output {
|
||||||
|
self.apply(-rhs)
|
||||||
|
}
|
||||||
|
}
|
||||||
0
src/core/df.rs
Normal file
0
src/core/df.rs
Normal file
3
src/core/mod.rs
Normal file
3
src/core/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod df;
|
||||||
|
pub mod xseries;
|
||||||
|
pub mod dateseries;
|
||||||
223
src/core/xseries.rs
Normal file
223
src/core/xseries.rs
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
use std::ops::{Add, Div, Mul, Sub};
|
||||||
|
|
||||||
|
//
|
||||||
|
// 1) Define a float series: FSeries
|
||||||
|
//
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FSeries {
|
||||||
|
data: Vec<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FSeries {
|
||||||
|
/// Create a new FSeries from a vector of f64 values.
|
||||||
|
pub fn new(data: Vec<f64>) -> Self {
|
||||||
|
Self { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.data.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Element‑wise helper applying an operation between two FSeries.
|
||||||
|
pub fn apply<F>(&self, other: &Self, op: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(f64, f64) -> f64,
|
||||||
|
{
|
||||||
|
assert!(
|
||||||
|
self.len() == other.len(),
|
||||||
|
"FSeries must have the same length to apply operations."
|
||||||
|
);
|
||||||
|
let data = self
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.zip(other.data.iter())
|
||||||
|
.map(|(&a, &b)| op(a, b))
|
||||||
|
.collect();
|
||||||
|
FSeries { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Access to the underlying data
|
||||||
|
pub fn data(&self) -> &[f64] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Macros for float series arithmetic (element‑wise)
|
||||||
|
macro_rules! impl_fseries_bin_op {
|
||||||
|
($trait:ident, $method:ident, $op:tt) => {
|
||||||
|
impl $trait for FSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn $method(self, rhs: Self) -> Self::Output {
|
||||||
|
self.apply(&rhs, |a, b| a $op b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_fseries_bin_op!(Add, add, +);
|
||||||
|
impl_fseries_bin_op!(Sub, sub, -);
|
||||||
|
impl_fseries_bin_op!(Mul, mul, *);
|
||||||
|
impl_fseries_bin_op!(Div, div, /);
|
||||||
|
|
||||||
|
macro_rules! impl_fseries_scalar_op {
|
||||||
|
($trait:ident, $method:ident, $op:tt) => {
|
||||||
|
impl $trait<f64> for FSeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn $method(mut self, scalar: f64) -> Self::Output {
|
||||||
|
for x in self.data.iter_mut() {
|
||||||
|
*x = *x $op scalar;
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_fseries_scalar_op!(Add, add, +);
|
||||||
|
impl_fseries_scalar_op!(Sub, sub, -);
|
||||||
|
impl_fseries_scalar_op!(Mul, mul, *);
|
||||||
|
impl_fseries_scalar_op!(Div, div, /);
|
||||||
|
|
||||||
|
//
|
||||||
|
// 2) Define an integer series: ISeries
|
||||||
|
//
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ISeries {
|
||||||
|
data: Vec<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ISeries {
|
||||||
|
/// Create an ISeries from a vector of i64 values.
|
||||||
|
pub fn new(data: Vec<i64>) -> Self {
|
||||||
|
Self { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.data.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data(&self) -> &[i64] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Element‑wise helper for integer series.
|
||||||
|
pub fn apply<F>(&self, other: &Self, op: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(i64, i64) -> i64,
|
||||||
|
{
|
||||||
|
assert!(
|
||||||
|
self.len() == other.len(),
|
||||||
|
"ISeries must have the same length to apply operations."
|
||||||
|
);
|
||||||
|
let data = self
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.zip(other.data.iter())
|
||||||
|
.map(|(&a, &b)| op(a, b))
|
||||||
|
.collect();
|
||||||
|
ISeries { data }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Macros for integer series arithmetic (element‑wise)
|
||||||
|
macro_rules! impl_iseries_bin_op {
|
||||||
|
($trait:ident, $method:ident, $op:tt) => {
|
||||||
|
impl $trait for ISeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn $method(self, rhs: Self) -> Self::Output {
|
||||||
|
self.apply(&rhs, |a, b| a $op b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_iseries_bin_op!(Add, add, +);
|
||||||
|
impl_iseries_bin_op!(Sub, sub, -);
|
||||||
|
impl_iseries_bin_op!(Mul, mul, *);
|
||||||
|
impl_iseries_bin_op!(Div, div, /); // integer division (floor trunc)
|
||||||
|
|
||||||
|
// Optional scalar operations (for i64)
|
||||||
|
macro_rules! impl_iseries_scalar_op {
|
||||||
|
($trait:ident, $method:ident, $op:tt) => {
|
||||||
|
impl $trait<i64> for ISeries {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
|
fn $method(mut self, scalar: i64) -> Self::Output {
|
||||||
|
for x in self.data.iter_mut() {
|
||||||
|
*x = *x $op scalar;
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_iseries_scalar_op!(Add, add, +);
|
||||||
|
impl_iseries_scalar_op!(Sub, sub, -);
|
||||||
|
impl_iseries_scalar_op!(Mul, mul, *);
|
||||||
|
impl_iseries_scalar_op!(Div, div, /); // floor/trunc division by scalar
|
||||||
|
|
||||||
|
/// A boolean series: BSeries
|
||||||
|
///
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BSeries {
|
||||||
|
data: Vec<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BSeries {
|
||||||
|
pub fn new(data: Vec<bool>) -> Self {
|
||||||
|
Self { data }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.data.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data(&self) -> &[bool] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert an FSeries to ISeries by truncation (floor cast).
|
||||||
|
impl From<FSeries> for ISeries {
|
||||||
|
fn from(fseries: FSeries) -> Self {
|
||||||
|
let data = fseries
|
||||||
|
.data
|
||||||
|
.into_iter()
|
||||||
|
.map(|val| val as i64) // trunc cast
|
||||||
|
.collect();
|
||||||
|
ISeries::new(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implement conversion from ISeries to FSeries by casting to f64.
|
||||||
|
impl From<ISeries> for FSeries {
|
||||||
|
fn from(iseries: ISeries) -> Self {
|
||||||
|
let data = iseries.data.into_iter().map(|val| val as f64).collect();
|
||||||
|
FSeries::new(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert an ISeries to BSeries by checking if each value is non-zero.
|
||||||
|
impl From<ISeries> for BSeries {
|
||||||
|
fn from(iseries: ISeries) -> Self {
|
||||||
|
let data = iseries.data.into_iter().map(|val| val != 0).collect();
|
||||||
|
BSeries::new(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<BSeries> for ISeries {
|
||||||
|
fn from(bseries: BSeries) -> Self {
|
||||||
|
let data = bseries
|
||||||
|
.data
|
||||||
|
.into_iter()
|
||||||
|
.map(|val| if val { 1 } else { 0 })
|
||||||
|
.collect();
|
||||||
|
ISeries::new(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -102,7 +102,7 @@ impl Default for JPMaQSDownloadGetIndicatorArgs {
|
|||||||
/// Struct for downloading data from the JPMaQS data from JPMorgan DataQuery API.
|
/// Struct for downloading data from the JPMaQS data from JPMorgan DataQuery API.
|
||||||
///
|
///
|
||||||
/// ## Example Usage
|
/// ## Example Usage
|
||||||
/// ```rust
|
/// ```ignore
|
||||||
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
|
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
|
||||||
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
|
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
|
||||||
/// use polars::prelude::*;
|
/// use polars::prelude::*;
|
||||||
@@ -140,7 +140,7 @@ impl Default for JPMaQSDownloadGetIndicatorArgs {
|
|||||||
/// Ok(_) => println!("Saved indicators to disk"),
|
/// Ok(_) => println!("Saved indicators to disk"),
|
||||||
/// Err(e) => println!("Error saving indicators: {:?}", e),
|
/// Err(e) => println!("Error saving indicators: {:?}", e),
|
||||||
/// }
|
/// }
|
||||||
///
|
/// ```
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct JPMaQSDownload {
|
pub struct JPMaQSDownload {
|
||||||
requester: DQRequester,
|
requester: DQRequester,
|
||||||
@@ -277,7 +277,7 @@ impl JPMaQSDownload {
|
|||||||
///
|
///
|
||||||
/// Usage:
|
/// Usage:
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```ignore
|
||||||
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
|
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
|
||||||
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
|
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
|
||||||
/// let mut jpamqs_download = JPMaQSDownload::default();
|
/// let mut jpamqs_download = JPMaQSDownload::default();
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
// #![doc = include_str!("../README.md")]
|
// #![doc = include_str!("../README.md")]
|
||||||
|
// uncomment the above line to include the README.md file in the documentation
|
||||||
|
|
||||||
//! # msyrs
|
//! # msyrs
|
||||||
//!
|
//!
|
||||||
@@ -18,6 +19,9 @@
|
|||||||
/// Documentation and type-stubs for the `msyrs` Python API.
|
/// Documentation and type-stubs for the `msyrs` Python API.
|
||||||
pub mod _py;
|
pub mod _py;
|
||||||
|
|
||||||
|
/// Implementation for the `core` module.
|
||||||
|
pub mod core;
|
||||||
|
|
||||||
/// Implementation for the `download` module.
|
/// Implementation for the `download` module.
|
||||||
pub mod download;
|
pub mod download;
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ class panel:
|
|||||||
def linear_composite(*args, **kwargs) -> DataFrame: ...
|
def linear_composite(*args, **kwargs) -> DataFrame: ...
|
||||||
|
|
||||||
class utils:
|
class utils:
|
||||||
__all__ = ["get_bdates_series_default"]
|
__all__ = ["get_bdates_series_default", "get_bdates_series_default_opt"]
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_bdates_series_default(*args, **kwargs) -> Series: ...
|
def get_bdates_series_default_pl(*args, **kwargs) -> Series: ...
|
||||||
|
@staticmethod
|
||||||
|
def get_bdates_series_default_opt(*args, **kwargs) -> Series: ...
|
||||||
|
|||||||
365
src/utils/bdates.rs
Normal file
365
src/utils/bdates.rs
Normal file
@@ -0,0 +1,365 @@
|
|||||||
|
use chrono::{Datelike, Duration, NaiveDate, Weekday};
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum BDateFreq {
|
||||||
|
Daily,
|
||||||
|
WeeklyMonday,
|
||||||
|
MonthStart,
|
||||||
|
QuarterStart,
|
||||||
|
YearStart,
|
||||||
|
MonthEnd,
|
||||||
|
QuarterEnd,
|
||||||
|
WeeklyFriday,
|
||||||
|
YearEnd,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum AggregationType {
|
||||||
|
Start, // Indicates picking the first date in a group.
|
||||||
|
End, // Indicates picking the last date in a group.
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BDateFreq {
|
||||||
|
pub fn from_string(freq: String) -> Result<Self, Box<dyn Error>> {
|
||||||
|
// use from_str to convert the string to a BDateFreq enum
|
||||||
|
Self::from_str(&freq)
|
||||||
|
}
|
||||||
|
pub fn from_str(freq: &str) -> Result<Self, Box<dyn Error>> {
|
||||||
|
match freq {
|
||||||
|
"D" => Ok(BDateFreq::Daily),
|
||||||
|
"W" => Ok(BDateFreq::WeeklyMonday),
|
||||||
|
"M" => Ok(BDateFreq::MonthStart),
|
||||||
|
"Q" => Ok(BDateFreq::QuarterStart),
|
||||||
|
"A" => Ok(BDateFreq::YearStart),
|
||||||
|
"ME" => Ok(BDateFreq::MonthEnd),
|
||||||
|
"QE" => Ok(BDateFreq::QuarterEnd),
|
||||||
|
"WF" => Ok(BDateFreq::WeeklyFriday),
|
||||||
|
"YE" => Ok(BDateFreq::YearEnd),
|
||||||
|
_ => Err("Invalid frequency specified".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn agg_type(&self) -> AggregationType {
|
||||||
|
match self {
|
||||||
|
BDateFreq::Daily
|
||||||
|
| BDateFreq::WeeklyMonday
|
||||||
|
| BDateFreq::MonthStart
|
||||||
|
| BDateFreq::QuarterStart
|
||||||
|
| BDateFreq::YearStart => AggregationType::Start,
|
||||||
|
|
||||||
|
BDateFreq::WeeklyFriday
|
||||||
|
| BDateFreq::MonthEnd
|
||||||
|
| BDateFreq::QuarterEnd
|
||||||
|
| BDateFreq::YearEnd => AggregationType::End,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns only the business dates (Mon-Fri) between start_date and end_date
|
||||||
|
/// that match the desired frequency.
|
||||||
|
pub fn get_bdates_list_with_freq(
|
||||||
|
start_date_str: &str,
|
||||||
|
end_date_str: &str,
|
||||||
|
freq: BDateFreq,
|
||||||
|
) -> Result<Vec<NaiveDate>, Box<dyn Error>> {
|
||||||
|
let start_date = NaiveDate::parse_from_str(start_date_str, "%Y-%m-%d")?;
|
||||||
|
let end_date = NaiveDate::parse_from_str(end_date_str, "%Y-%m-%d")?;
|
||||||
|
|
||||||
|
if start_date > end_date {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut dates = match freq {
|
||||||
|
BDateFreq::Daily => collect_daily(start_date, end_date),
|
||||||
|
|
||||||
|
BDateFreq::WeeklyMonday => collect_weekly(start_date, end_date, Weekday::Mon),
|
||||||
|
BDateFreq::WeeklyFriday => collect_weekly(start_date, end_date, Weekday::Fri),
|
||||||
|
|
||||||
|
BDateFreq::MonthStart => collect_monthly(start_date, end_date, /*start=*/ true),
|
||||||
|
BDateFreq::MonthEnd => collect_monthly(start_date, end_date, /*start=*/ false),
|
||||||
|
|
||||||
|
BDateFreq::QuarterStart => collect_quarterly(start_date, end_date, /*start=*/ true),
|
||||||
|
BDateFreq::QuarterEnd => collect_quarterly(start_date, end_date, /*start=*/ false),
|
||||||
|
|
||||||
|
BDateFreq::YearStart => collect_yearly(start_date, end_date, /*start=*/ true),
|
||||||
|
BDateFreq::YearEnd => collect_yearly(start_date, end_date, /*start=*/ false),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter out any weekend days that might slip in edge cases (e.g. if the
|
||||||
|
// computed "start of month" fell on Sat/Sun).
|
||||||
|
dates.retain(|d| d.weekday() != Weekday::Sat && d.weekday() != Weekday::Sun);
|
||||||
|
|
||||||
|
Ok(dates)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------ Helpers ------------------------------ */
|
||||||
|
|
||||||
|
/// Return all business days, day-by-day.
|
||||||
|
fn collect_daily(start_date: NaiveDate, end_date: NaiveDate) -> Vec<NaiveDate> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
let mut current = start_date;
|
||||||
|
while current <= end_date {
|
||||||
|
if is_weekday(current) {
|
||||||
|
result.push(current);
|
||||||
|
}
|
||||||
|
current = current.succ_opt().unwrap();
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the specified weekday (e.g. Monday, Friday) in each week of the range.
|
||||||
|
fn collect_weekly(
|
||||||
|
start_date: NaiveDate,
|
||||||
|
end_date: NaiveDate,
|
||||||
|
target_weekday: Weekday,
|
||||||
|
) -> Vec<NaiveDate> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
|
||||||
|
// Find the first `target_weekday` on or after `start_date`.
|
||||||
|
// If `start_date` is already e.g. Monday, we can use it as is.
|
||||||
|
// Otherwise, jump ahead until we get that weekday.
|
||||||
|
let mut current = move_to_weekday_on_or_after(start_date, target_weekday);
|
||||||
|
|
||||||
|
// Step in 7-day increments (full weeks).
|
||||||
|
while current <= end_date {
|
||||||
|
result.push(current);
|
||||||
|
current = current + Duration::days(7);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return either first or last business day in each month of the range.
|
||||||
|
fn collect_monthly(
|
||||||
|
start_date: NaiveDate,
|
||||||
|
end_date: NaiveDate,
|
||||||
|
want_first_day: bool,
|
||||||
|
) -> Vec<NaiveDate> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
|
||||||
|
// We'll iterate month by month, from (start_year, start_month) up to
|
||||||
|
// (end_year, end_month).
|
||||||
|
let mut year = start_date.year();
|
||||||
|
let mut month = start_date.month();
|
||||||
|
|
||||||
|
// A small helper that updates year/month by +1 month.
|
||||||
|
let next_month = |(yr, mo): (i32, u32)| -> (i32, u32) {
|
||||||
|
if mo == 12 {
|
||||||
|
(yr + 1, 1)
|
||||||
|
} else {
|
||||||
|
(yr, mo + 1)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Move `(year, month)` backward if necessary so that `(year, month)`
|
||||||
|
// definitely covers the entire period from `start_date` onward.
|
||||||
|
// Actually, it’s simpler to start from the actual (year, month) of start_date
|
||||||
|
// and go up. We'll just skip if the computed "day" < start_date.
|
||||||
|
|
||||||
|
// Continue while we haven't passed (end_year, end_month).
|
||||||
|
while year < end_date.year() || (year == end_date.year() && month <= end_date.month()) {
|
||||||
|
// Compute the date that represents either first or last business day
|
||||||
|
// for this (year, month).
|
||||||
|
let candidate = if want_first_day {
|
||||||
|
first_business_day_of_month(year, month)
|
||||||
|
} else {
|
||||||
|
last_business_day_of_month(year, month)
|
||||||
|
};
|
||||||
|
if candidate >= start_date && candidate <= end_date {
|
||||||
|
result.push(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move to the next month.
|
||||||
|
let (ny, nm) = next_month((year, month));
|
||||||
|
year = ny;
|
||||||
|
month = nm;
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return either the first or last business day in each quarter of the range.
|
||||||
|
fn collect_quarterly(
|
||||||
|
start_date: NaiveDate,
|
||||||
|
end_date: NaiveDate,
|
||||||
|
want_first_day: bool,
|
||||||
|
) -> Vec<NaiveDate> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
|
||||||
|
// We'll figure out which quarter `start_date` is in, then jump quarter-by-quarter.
|
||||||
|
// Quarters are: Q1 = months 1–3, Q2 = 4–6, Q3 = 7–9, Q4 = 10–12.
|
||||||
|
// Start by computing the (year, quarter_index) for start_date.
|
||||||
|
let mut year = start_date.year();
|
||||||
|
let mut q = month_to_quarter(start_date.month());
|
||||||
|
|
||||||
|
while quarter_to_first_date(year, q) > end_date {
|
||||||
|
// If even the earliest day in that quarter is > end_date, we’re done.
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move backward if the quarter’s last day < start_date, etc.
|
||||||
|
// But simpler: we’ll do a loop that increments quarter by quarter, and
|
||||||
|
// pick the appropriate date each time. We break when we pass end_date.
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// For the current year+quarter, compute the date that’s either the first or last
|
||||||
|
// business day of that quarter:
|
||||||
|
let candidate = if want_first_day {
|
||||||
|
first_business_day_of_quarter(year, q)
|
||||||
|
} else {
|
||||||
|
last_business_day_of_quarter(year, q)
|
||||||
|
};
|
||||||
|
|
||||||
|
if candidate > end_date {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if candidate >= start_date {
|
||||||
|
result.push(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move to next quarter.
|
||||||
|
if q == 4 {
|
||||||
|
year += 1;
|
||||||
|
q = 1;
|
||||||
|
} else {
|
||||||
|
q += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return either the first or last business day in each year of the range.
|
||||||
|
fn collect_yearly(
|
||||||
|
start_date: NaiveDate,
|
||||||
|
end_date: NaiveDate,
|
||||||
|
want_first_day: bool,
|
||||||
|
) -> Vec<NaiveDate> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
let mut year = start_date.year();
|
||||||
|
|
||||||
|
// Step year-by-year from `start_date.year()` up to `end_date.year()`.
|
||||||
|
while year <= end_date.year() {
|
||||||
|
let candidate = if want_first_day {
|
||||||
|
first_business_day_of_year(year)
|
||||||
|
} else {
|
||||||
|
last_business_day_of_year(year)
|
||||||
|
};
|
||||||
|
if candidate >= start_date && candidate <= end_date {
|
||||||
|
result.push(candidate);
|
||||||
|
}
|
||||||
|
year += 1;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------- Low-Level Utility Functions ---------------------- */
|
||||||
|
|
||||||
|
/// Is this a weekday (Mon-Fri)?
|
||||||
|
fn is_weekday(date: NaiveDate) -> bool {
|
||||||
|
match date.weekday() {
|
||||||
|
Weekday::Sat | Weekday::Sun => false,
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Given a date and a `target_weekday`, returns the date that is the first
|
||||||
|
/// `target_weekday` on or after the given date.
|
||||||
|
fn move_to_weekday_on_or_after(date: NaiveDate, target: Weekday) -> NaiveDate {
|
||||||
|
let mut current = date;
|
||||||
|
while current.weekday() != target {
|
||||||
|
current = current.succ_opt().unwrap();
|
||||||
|
}
|
||||||
|
current
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the earliest business day of (year, month).
|
||||||
|
fn first_business_day_of_month(year: i32, month: u32) -> NaiveDate {
|
||||||
|
// Start with the 1st of the month.
|
||||||
|
let mut d = NaiveDate::from_ymd_opt(year, month, 1).expect("invalid year-month");
|
||||||
|
// If it’s Sat/Sun, move forward until we get a weekday.
|
||||||
|
while !is_weekday(d) {
|
||||||
|
d = d.succ_opt().unwrap();
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the latest business day of (year, month).
|
||||||
|
fn last_business_day_of_month(year: i32, month: u32) -> NaiveDate {
|
||||||
|
let last_dom = days_in_month(year, month);
|
||||||
|
let mut d = NaiveDate::from_ymd_opt(year, month, last_dom).expect("invalid year-month");
|
||||||
|
// If it’s Sat/Sun, move backward until we get a weekday.
|
||||||
|
while !is_weekday(d) {
|
||||||
|
d = d.pred_opt().unwrap();
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of days in a month (not considering leap years *beyond* chrono's normal handling).
|
||||||
|
fn days_in_month(year: i32, month: u32) -> u32 {
|
||||||
|
// Chrono can handle this if we do a little trick:
|
||||||
|
// Construct the 1st of the next month, then subtract 1 day.
|
||||||
|
// For example:
|
||||||
|
// if month == 12 => next = (year+1, 1, 1)
|
||||||
|
// else => next = (year, month+1, 1)
|
||||||
|
let (ny, nm) = if month == 12 {
|
||||||
|
(year + 1, 1)
|
||||||
|
} else {
|
||||||
|
(year, month + 1)
|
||||||
|
};
|
||||||
|
let first_of_next = NaiveDate::from_ymd_opt(ny, nm, 1).unwrap();
|
||||||
|
let last_of_this = first_of_next.pred_opt().unwrap();
|
||||||
|
last_of_this.day()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert a month (1..12) to a quarter (1..4).
|
||||||
|
fn month_to_quarter(m: u32) -> u32 {
|
||||||
|
(m - 1) / 3 + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns 1st day of a given (year, quarter).
|
||||||
|
fn quarter_to_first_date(year: i32, quarter: u32) -> NaiveDate {
|
||||||
|
let month = match quarter {
|
||||||
|
1 => 1,
|
||||||
|
2 => 4,
|
||||||
|
3 => 7,
|
||||||
|
4 => 10,
|
||||||
|
_ => panic!("invalid quarter"),
|
||||||
|
};
|
||||||
|
NaiveDate::from_ymd_opt(year, month, 1).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the earliest business day in (year, quarter).
|
||||||
|
fn first_business_day_of_quarter(year: i32, quarter: u32) -> NaiveDate {
|
||||||
|
let mut d = quarter_to_first_date(year, quarter);
|
||||||
|
while !is_weekday(d) {
|
||||||
|
d = d.succ_opt().unwrap();
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the last business day in (year, quarter).
|
||||||
|
fn last_business_day_of_quarter(year: i32, quarter: u32) -> NaiveDate {
|
||||||
|
// The last month in the quarter is quarter_to_first_date(...) + 2 months
|
||||||
|
// Then we find the last day of that month.
|
||||||
|
let start = quarter_to_first_date(year, quarter);
|
||||||
|
let last_month = start.month() + 2; // e.g. Q1 => month=1 => +2=3 => March
|
||||||
|
last_business_day_of_month(year, last_month)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns Jan 1st of a given year (adjust if weekend).
|
||||||
|
fn first_business_day_of_year(year: i32) -> NaiveDate {
|
||||||
|
let mut d = NaiveDate::from_ymd_opt(year, 1, 1).unwrap();
|
||||||
|
while !is_weekday(d) {
|
||||||
|
d = d.succ_opt().unwrap();
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns Dec 31st of a given year (adjust if weekend).
|
||||||
|
fn last_business_day_of_year(year: i32) -> NaiveDate {
|
||||||
|
let mut d = NaiveDate::from_ymd_opt(year, 12, 31).unwrap();
|
||||||
|
while !is_weekday(d) {
|
||||||
|
d = d.pred_opt().unwrap();
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use crate::utils::bdates;
|
||||||
|
use crate::utils::bdates::BDateFreq;
|
||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use chrono::{Datelike, Weekday};
|
use chrono::{Datelike, Weekday};
|
||||||
use polars::prelude::*;
|
use polars::prelude::*;
|
||||||
@@ -57,57 +59,6 @@ pub fn get_bdates_list(
|
|||||||
Ok(business_days)
|
Ok(business_days)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub enum BDateFreq {
|
|
||||||
Daily,
|
|
||||||
WeeklyMonday,
|
|
||||||
MonthStart,
|
|
||||||
QuarterStart,
|
|
||||||
YearStart,
|
|
||||||
MonthEnd,
|
|
||||||
QuarterEnd,
|
|
||||||
WeeklyFriday,
|
|
||||||
YearEnd,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BDateFreq {
|
|
||||||
pub fn from_str(freq: &str) -> Result<Self, Box<dyn Error>> {
|
|
||||||
match freq {
|
|
||||||
"D" => Ok(BDateFreq::Daily),
|
|
||||||
"W" => Ok(BDateFreq::WeeklyMonday),
|
|
||||||
"M" => Ok(BDateFreq::MonthStart),
|
|
||||||
"Q" => Ok(BDateFreq::QuarterStart),
|
|
||||||
"A" => Ok(BDateFreq::YearStart),
|
|
||||||
"ME" => Ok(BDateFreq::MonthEnd),
|
|
||||||
"QE" => Ok(BDateFreq::QuarterEnd),
|
|
||||||
"WF" => Ok(BDateFreq::WeeklyFriday),
|
|
||||||
"YE" => Ok(BDateFreq::YearEnd),
|
|
||||||
_ => Err("Invalid frequency specified".into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn agg_type(&self) -> AggregationType {
|
|
||||||
match self {
|
|
||||||
BDateFreq::Daily
|
|
||||||
| BDateFreq::WeeklyMonday
|
|
||||||
| BDateFreq::MonthStart
|
|
||||||
| BDateFreq::QuarterStart
|
|
||||||
| BDateFreq::YearStart => AggregationType::Start,
|
|
||||||
BDateFreq::WeeklyFriday
|
|
||||||
| BDateFreq::MonthEnd
|
|
||||||
| BDateFreq::QuarterEnd
|
|
||||||
| BDateFreq::YearEnd => AggregationType::End,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub enum AggregationType {
|
|
||||||
Start, // Indicates picking the first date in a group.
|
|
||||||
End, // Indicates picking the last date in a group.
|
|
||||||
}
|
|
||||||
|
|
||||||
// Map a BDateFreq to an AggregationType.
|
|
||||||
fn compute_group_key(d: NaiveDate, freq: BDateFreq) -> String {
|
fn compute_group_key(d: NaiveDate, freq: BDateFreq) -> String {
|
||||||
match freq {
|
match freq {
|
||||||
// For Daily, each date is its own group.
|
// For Daily, each date is its own group.
|
||||||
@@ -130,19 +81,32 @@ fn compute_group_key(d: NaiveDate, freq: BDateFreq) -> String {
|
|||||||
BDateFreq::YearStart | BDateFreq::YearEnd => format!("{}", d.year()),
|
BDateFreq::YearStart | BDateFreq::YearEnd => format!("{}", d.year()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pub fn get_bdates_series_default_opt(
|
||||||
pub fn get_bdates_series_default(
|
|
||||||
start_date: String,
|
start_date: String,
|
||||||
end_date: String,
|
end_date: String,
|
||||||
freq: Option<String>,
|
freq: Option<String>,
|
||||||
) -> Result<Series, Box<dyn Error>> {
|
) -> Result<Series, Box<dyn Error>> {
|
||||||
let freq = freq.unwrap_or_else(|| "D".to_string());
|
let freq = freq.unwrap_or_else(|| "D".to_string());
|
||||||
let freq = BDateFreq::from_str(&freq)?;
|
let freq = BDateFreq::from_str(&freq)?;
|
||||||
get_bdates_series(start_date, end_date, freq)
|
let series = Series::new(
|
||||||
|
"bdates".into(),
|
||||||
|
bdates::get_bdates_list_with_freq(&start_date, &end_date, freq)?,
|
||||||
|
);
|
||||||
|
Ok(series)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_bdates_series_default_pl(
|
||||||
|
start_date: String,
|
||||||
|
end_date: String,
|
||||||
|
freq: Option<String>,
|
||||||
|
) -> Result<Series, Box<dyn Error>> {
|
||||||
|
let freq = freq.unwrap_or_else(|| "D".to_string());
|
||||||
|
let freq = BDateFreq::from_str(&freq)?;
|
||||||
|
get_bdates_series_pl(start_date, end_date, freq)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the business dates between two dates as a Series.
|
/// Get the business dates between two dates as a Series.
|
||||||
pub fn get_bdates_series(
|
pub fn get_bdates_series_pl(
|
||||||
start_date: String,
|
start_date: String,
|
||||||
end_date: String,
|
end_date: String,
|
||||||
freq: BDateFreq,
|
freq: BDateFreq,
|
||||||
@@ -159,8 +123,8 @@ pub fn get_bdates_series(
|
|||||||
])?;
|
])?;
|
||||||
let gb = df.lazy().group_by(["group"]);
|
let gb = df.lazy().group_by(["group"]);
|
||||||
let aggx = match freq.agg_type() {
|
let aggx = match freq.agg_type() {
|
||||||
AggregationType::Start => gb.agg([col("bdates").first()]),
|
bdates::AggregationType::Start => gb.agg([col("bdates").first()]),
|
||||||
AggregationType::End => gb.agg([col("bdates").last()]),
|
bdates::AggregationType::End => gb.agg([col("bdates").last()]),
|
||||||
};
|
};
|
||||||
let result = aggx.collect()?;
|
let result = aggx.collect()?;
|
||||||
let result = result
|
let result = result
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod qdf;
|
pub mod bdates;
|
||||||
pub mod misc;
|
|
||||||
pub mod dateutils;
|
pub mod dateutils;
|
||||||
|
pub mod misc;
|
||||||
|
pub mod qdf;
|
||||||
|
|||||||
Reference in New Issue
Block a user