drift-quant / tests /test_portfolio_allocator.py
deveshc23
feat: Add Free Gradio Space support, Git LFS tracking for data artifacts, and Quant Allocator
3e33e2e
Raw History Blame Contribute Delete
2.1 kB
"""Unit tests for quantitative portfolio allocator and weighting models."""
from drift_quant.portfolio import AllocationModel, PortfolioAllocator
def test_portfolio_allocator_models() -> None:
sector_map = {
"RELIANCE": "Energy",
"TCS": "IT",
"HDFCBANK": "Banking",
"INFY": "IT",
}
allocator = PortfolioAllocator(sector_map)
# Simulated daily bars
bars = {
"RELIANCE": [
{"timestamp": f"2024-01-0{i} 15:30:00", "close": 100.0 + i * 1.5} for i in range(1, 8)
],
"TCS": [
{"timestamp": f"2024-01-0{i} 15:30:00", "close": 200.0 + i * 0.8} for i in range(1, 8)
],
"HDFCBANK": [
{"timestamp": f"2024-01-0{i} 15:30:00", "close": 150.0 + i * 2.1} for i in range(1, 8)
],
"INFY": [
{"timestamp": f"2024-01-0{i} 15:30:00", "close": 80.0 + i * 0.5} for i in range(1, 8)
],
}
# Test Equal Weight
res_eq = allocator.allocate(AllocationModel.EQUAL_WEIGHT, bars)
assert res_eq.constituents_count == 4
for a in res_eq.allocations:
assert round(a.weight, 2) == 0.25
# Test Inverse Volatility
res_iv = allocator.allocate(AllocationModel.INVERSE_VOLATILITY, bars)
assert res_iv.constituents_count == 4
assert round(sum(a.weight for a in res_iv.allocations), 4) == 1.0
# Test Risk Parity
res_rp = allocator.allocate(AllocationModel.RISK_PARITY, bars)
assert res_rp.constituents_count == 4
assert round(sum(a.weight for a in res_rp.allocations), 4) == 1.0
assert res_rp.portfolio_volatility > 0.0
# Test Multi-Factor Momentum
res_mf = allocator.allocate(AllocationModel.MULTI_FACTOR_MOMENTUM, bars)
assert res_mf.constituents_count == 4
assert round(sum(a.weight for a in res_mf.allocations), 4) == 1.0
assert res_mf.effective_n > 1.0
def test_portfolio_allocator_empty() -> None:
allocator = PortfolioAllocator()
res = allocator.allocate(AllocationModel.EQUAL_WEIGHT, {})
assert res.constituents_count == 0
assert res.portfolio_volatility == 0.0