Add offline workflow and coverage tests

This commit is contained in:
Yuxuan Yan
2026-06-16 17:37:16 +08:00
parent 8d908477e2
commit 31baa18ce5
16 changed files with 2104 additions and 9 deletions
+190
View File
@@ -306,6 +306,47 @@ def test_construct_positions_schema():
assert pos["position_shares"].dtype == np.int64
def test_construct_positions_empty_weights_returns_schema():
data = _make_data(n_days=3)
empty_weights = pd.DataFrame(columns=["symbol_id", "date", "combo_name", "weight"])
pos = construct_positions(
empty_weights,
data,
booksize=1e6,
portfolio_name="empty",
)
assert list(pos.columns) == POSITION_COLUMNS
assert pos.empty
def test_construct_positions_ignores_absent_or_bad_prices():
dates = pd.to_datetime(["2024-01-01", "2024-01-02"])
data = pd.DataFrame([
{"symbol_id": "sh600000", "date": dates[0], "close": np.nan, "isST": 0},
{"symbol_id": "sz000001", "date": dates[0], "close": 20.0, "isST": 0},
{"symbol_id": "sh600000", "date": dates[1], "close": 10.0, "isST": 0},
{"symbol_id": "sz000001", "date": dates[1], "close": 20.0, "isST": 0},
])
weights = pd.DataFrame({
"symbol_id": ["sh600000", "sz000001", "sh600000", "sz000001"],
"date": [dates[0], dates[0], dates[1], dates[1]],
"combo_name": ["combo"] * 4,
"weight": [1.0, -1.0, 1.0, -1.0],
})
pos = construct_positions(weights, data, booksize=10000.0, portfolio_name="bad_price")
bad_price_rows = pos[
(pos["date"] == dates[0])
& (pos["symbol_id"] == "sh600000")
]
assert bad_price_rows.empty or (bad_price_rows["target_weight"] == 0.0).all()
assert np.isfinite(pos["target_value"]).all()
assert np.isfinite(pos["position_value"]).all()
def test_construct_positions_threads_state_and_closes_absent():
data = _make_data()
weights = _make_weights(data)
@@ -321,6 +362,34 @@ def test_construct_positions_threads_state_and_closes_absent():
assert final.empty or (final["position_shares"] == 0).all()
def test_construct_positions_closes_absent_short_position():
dates = pd.to_datetime(["2024-01-02", "2024-01-03"])
data = pd.DataFrame([
{"symbol_id": sym, "date": d, "close": price, "isST": 0}
for d in dates
for sym, price in (("sh600000", 10.0), ("sz000001", 20.0))
])
weights = pd.DataFrame({
"symbol_id": ["sh600000", "sz000001", "sz000001"],
"date": [dates[0], dates[0], dates[1]],
"combo_name": ["combo", "combo", "combo"],
"weight": [-1.0, 1.0, 1.0],
})
pos = construct_positions(weights, data, booksize=20000.0, portfolio_name="absent_short")
first_day_short = pos[
(pos["date"] == dates[0])
& (pos["symbol_id"] == "sh600000")
]
final_day_short = pos[
(pos["date"] == dates[1])
& (pos["symbol_id"] == "sh600000")
]
assert (first_day_short["position_shares"] < 0).all()
assert final_day_short.empty or (final_day_short["position_shares"] == 0).all()
def test_construct_positions_carries_book_on_zero_gross(caplog):
dates = pd.to_datetime(["2024-01-01", "2024-01-02"])
symbols = ["sh600000", "sz000001"]
@@ -392,6 +461,42 @@ def test_volume_cap_uses_traded_value():
assert low[0] == -10000.0
def test_constraints_compose_repeatably_regardless_of_order():
n = 1
sl = _slice(
n,
tradestatus=np.array([0.0]),
limit_status=np.array([LimitStatus.UP_LIMIT.value], dtype=np.int8),
amount=np.array([1_000.0]),
price=np.array([10.0]),
)
ctx = TradeContext(np.zeros(n, np.int64), np.array([500]), sl, 1e6)
first_order = ReferenceSimulator(
constraints=[
SuspensionConstraint(),
PriceLimitConstraint(),
VolumeCapConstraint(max_frac=0.1),
],
cost_bps=10,
).fill(ctx)
reversed_order = ReferenceSimulator(
constraints=[
VolumeCapConstraint(max_frac=0.1),
PriceLimitConstraint(),
SuspensionConstraint(),
],
cost_bps=10,
).fill(ctx)
assert first_order.traded_shares.tolist() == [0]
assert first_order.realized_shares.tolist() == [0]
assert first_order.blocked.tolist() == [1]
assert np.array_equal(first_order.traded_shares, reversed_order.traded_shares)
assert np.array_equal(first_order.realized_shares, reversed_order.realized_shares)
assert np.array_equal(first_order.blocked, reversed_order.blocked)
assert np.array_equal(first_order.cost, reversed_order.cost)
# --- ReferenceSimulator ------------------------------------------------------
def test_simulator_next_open_and_blocked_buy_holds_prev():
@@ -474,6 +579,91 @@ def test_simulator_cost_only_on_nonzero_realized_trades():
assert np.isclose(res.cost[1], 50 * 20 * 10 / 1e4)
def test_simulator_short_to_long_flip_trades_full_delta():
dates = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"])
positions = pd.DataFrame({
"symbol_id": ["sh600000", "sh600000"],
"date": [dates[0], dates[1]],
"portfolio_name": ["flip", "flip"],
"target_weight": [-1.0, 1.0],
"target_value": [-1000.0, 1000.0],
"target_shares": [-100.0, 100.0],
"position_shares": [-100, 100],
"position_value": [-1000.0, 1000.0],
"price": [10.0, 10.0],
})
data = pd.DataFrame({
"symbol_id": ["sh600000"] * 3,
"date": dates,
"open": [10.0, 10.0, 10.0],
"close": [10.0, 10.0, 10.0],
"preclose": [10.0, 10.0, 10.0],
"amount": [1e9, 1e9, 1e9],
"tradestatus": [1, 1, 1],
"isST": [0, 0, 0],
})
fills, _ = ReferenceSimulator().run(positions, data)
by_date = fills.set_index("date")
assert by_date.loc[dates[1], "traded_shares"] == -100
assert by_date.loc[dates[1], "realized_shares"] == -100
assert by_date.loc[dates[2], "prev_shares"] == -100
assert by_date.loc[dates[2], "traded_shares"] == 200
assert by_date.loc[dates[2], "realized_shares"] == 100
def test_simulator_volume_cap_partially_fills_sell():
sl = _slice(1, amount=np.array([10_000.0]), price=np.array([10.0]))
ctx = TradeContext(
np.array([1000], np.int64),
np.array([0], np.int64),
sl,
1_000_000.0,
)
result = ReferenceSimulator(
constraints=[VolumeCapConstraint(max_frac=0.10)]
).fill(ctx)
assert result.traded_shares.tolist() == [-100]
assert result.realized_shares.tolist() == [900]
assert result.blocked.tolist() == [1]
def test_simulator_missing_next_open_has_zero_cost_and_turnover():
dates = pd.to_datetime(["2024-01-01", "2024-01-02"])
positions = pd.DataFrame({
"symbol_id": ["sh600000"],
"date": [dates[0]],
"portfolio_name": ["missing_open"],
"target_weight": [1.0],
"target_value": [1000.0],
"target_shares": [100.0],
"position_shares": [100],
"position_value": [1000.0],
"price": [10.0],
})
data = pd.DataFrame({
"symbol_id": ["sh600000", "sh600000"],
"date": dates,
"open": [10.0, np.nan],
"close": [10.0, 10.0],
"preclose": [10.0, 10.0],
"amount": [1e9, 1e9],
"tradestatus": [1, 1],
"isST": [0, 0],
})
fills, pnl = ReferenceSimulator(cost_bps=10, slippage_bps=5).run(positions, data)
assert fills["traded_shares"].iloc[0] == 100
assert fills["trade_cost"].iloc[0] == 0.0
assert pnl["cost"].iloc[0] == 0.0
assert pnl["turnover"].iloc[0] == 0.0
assert pnl["gross_exposure"].iloc[0] == 1000.0
def test_simple_cost_model_adds_cost_and_slippage_without_price_adjustment():
model = SimpleProportionalCostModel(cost_bps=10, slippage_bps=5)