|
10 | 10 | - Academic formula correctness |
11 | 11 | """ |
12 | 12 |
|
| 13 | +from io import StringIO |
| 14 | + |
13 | 15 | import numpy as np |
14 | 16 | import polars as pl |
15 | 17 | import pytest |
@@ -424,14 +426,41 @@ def test_roll_spread_matches_window_covariance(): |
424 | 426 | if np.isnan(window_changes).any() or np.isnan(window_lagged).any(): |
425 | 427 | assert np.isnan(result[index]) |
426 | 428 | continue |
427 | | - covariance = float( |
428 | | - np.mean(window_changes * window_lagged) |
429 | | - - np.mean(window_changes) * np.mean(window_lagged) |
430 | | - ) |
| 429 | + covariance = float(np.cov(window_changes, window_lagged, ddof=0)[0, 1]) |
431 | 430 | expected = 2.0 * np.sqrt(max(-covariance, 0.0)) |
432 | 431 | assert result[index] == pytest.approx(expected) |
433 | 432 |
|
434 | 433 |
|
| 434 | +@pytest.mark.parametrize("missing", ["", "NaN"]) |
| 435 | +@pytest.mark.parametrize("period", [1, 2, 4, 7]) |
| 436 | +@pytest.mark.parametrize("lazy", [False, True]) |
| 437 | +def test_roll_spread_missing_csv_prices_do_not_report_zero(missing, period, lazy): |
| 438 | + prices = [100.0 + i % 2 if i < 20 else 100.0 + (i - 19) ** 2 / 16 for i in range(30)] |
| 439 | + rows = [f"2024-01-02T14:{30 + i:02d}:00Z,{price}" for i, price in enumerate(prices)] |
| 440 | + rows[8] = f"2024-01-02T14:38:00Z,{missing}" |
| 441 | + frame = pl.read_csv( |
| 442 | + StringIO("timestamp,close\n" + "\n".join(rows)), |
| 443 | + schema_overrides={"close": pl.Float64}, |
| 444 | + try_parse_dates=True, |
| 445 | + ) |
| 446 | + changes = np.diff(frame["close"].to_numpy(), prepend=np.nan) |
| 447 | + lagged = np.roll(changes, 1) |
| 448 | + lagged[0] = np.nan |
| 449 | + expected = np.full(frame.height, np.nan) |
| 450 | + for index in range(period + 1, frame.height): |
| 451 | + current = changes[index - period + 1 : index + 1] |
| 452 | + previous = lagged[index - period + 1 : index + 1] |
| 453 | + if np.isfinite(current).all() and np.isfinite(previous).all(): |
| 454 | + covariance = np.cov(current, previous, ddof=0)[0, 1] |
| 455 | + expected[index] = 2 * np.sqrt(max(-covariance, 0)) |
| 456 | + source = frame.lazy() if lazy else frame |
| 457 | + selected = source.select(roll_spread_estimator("close", period=period)) |
| 458 | + result = selected.collect() if lazy else selected |
| 459 | + np.testing.assert_allclose( |
| 460 | + result.to_series().to_numpy(), expected, equal_nan=True, rtol=1e-12, atol=1e-12 |
| 461 | + ) |
| 462 | + |
| 463 | + |
435 | 464 | def test_tick_rule_basic_functionality(sample_microstructure_data): |
436 | 465 | """Test effective tick rule basic calculation.""" |
437 | 466 | result = sample_microstructure_data.with_columns( |
|
0 commit comments