(
df: pl.DataFrame,
*,
dedupe_keep: str = "last",
return_report: bool = False,
)
| 168 | .get_column("spacing") |
| 169 | .drop_nulls() |
| 170 | ) |
| 171 | spacings = spacings.filter(spacings > 0) |
| 172 | if spacings.len() == 0: |
| 173 | return None |
| 174 | counts = spacings.value_counts(name="n") |
| 175 | top = counts.filter(pl.col("n") == pl.col("n").max()) |
| 176 | return int(top.get_column("spacing").min()) # type: ignore[arg-type] |
| 177 | |
| 178 | |
| 179 | def _gap_count(sorted_df: pl.DataFrame, interval_us: int | None) -> int: |
| 180 | """Gaps between consecutive bars of one symbol, given the inferred bar spacing. |
| 181 | |
| 182 | Daily data (spacing within an hour of one day, to absorb DST shifts): a gap is a skipped |
| 183 | weekday, i.e. at least one Monday-to-Friday date strictly between the two bars' dates, |
| 184 | so weekends are not gaps (exchange holidays still are). Any other spacing: a gap is a |
| 185 | spacing greater than the inferred one. |
| 186 | """ |
| 187 | if interval_us is None: |
| 188 | return 0 |
| 189 | same = pl.col("symbol") == pl.col("symbol").shift(1) |
| 190 | if abs(interval_us - _DAY_US) <= _HOUR_US: |
| 191 | prev_date = pl.col("ts").shift(1).dt.date() |
| 192 | cur_date = pl.col("ts").dt.date() |
| 193 | gap = same & ( |
| 194 | pl.business_day_count(prev_date + pl.duration(days=1), cur_date).fill_null(0) > 0 |
| 195 | ) |
| 196 | else: |
| 197 | gap = same & ((pl.col("ts_us") - pl.col("ts_us").shift(1)) > interval_us) |
| 198 | return int(sorted_df.select(gap.fill_null(False).cast(pl.UInt32).sum()).item()) |
| 199 | |
| 200 | |
| 201 | def _build_quality_report( |
| 202 | sorted_df: pl.DataFrame, rows_removed_by_deduplication: int, null_counts: dict[str, int] |
| 203 | ) -> dict[str, Any]: |
| 204 | if sorted_df.height == 0: |
| 205 | return { |
| 206 | "row_count": 0, |
| 207 | "symbol_count": 0, |
| 208 | "duplicate_key_count": 0, |
| 209 | "gap_interval_count": 0, |
| 210 | "inferred_interval_us": None, |
| 211 | "ts_min": None, |
| 212 | "ts_max": None, |
| 213 | "rows_removed_by_deduplication": rows_removed_by_deduplication, |
| 214 | "null_counts": dict(null_counts), |
no test coverage detected