feat(dashboard): chart performance on one percent axis
The comparison plotted both books in dollars and SPY on a hidden rescaled axis, stretched so its biggest move matched the books' biggest move. SPY's height therefore said nothing about which was ahead, and the stat cells showed R next to SPY's percent, which do not compare. Everything is now percent of the shadow book's equity: - shadow: actual P&L over equity at window start (start equity plus P&L realized before a pinned performance_start_date) - your picks: re-sized at the shadow book's rule (risk_pct, 20% notional cap), so the gap between books is selection only - SPY: buy & hold on the same axis A strategy-vs-SPY verdict measures SPY from the shadow book's first trade, so manual trades opening earlier no longer charge the strategy for SPY's run-up before it existed. R stats stay underneath for book-vs-book reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c48eb20c5
commit
4876f9ffdd
4 files changed
+405
-87
No files matched your search
@@ -68,6 +68,131 @@ class TestBookStats:
|
||||
assert stats["total_r"] == pytest.approx(4.0)
|
||||
|
||||
|
||||
class TestStrategySizedPercent:
|
||||
"""Both books and SPY share one unit — percent of equity — on the chart."""
|
||||
|
||||
def test_one_r_is_risk_pct_of_equity(self):
|
||||
# Entry 100, stop 90 → 10 of risk; 1% risk → 0.001 shares per $ equity
|
||||
# (10% notional, under the 20% cap). Exit 120 = +2R = +2% of equity.
|
||||
trade = _trade(book=MANUAL_BOOK, entry=100.0, stop=90.0, close=120.0)
|
||||
assert pts.strategy_sized_fraction(trade, 1.0, 0.20) == pytest.approx(0.001)
|
||||
days = [trade.closed_at.date()]
|
||||
assert pts._cumulative_sized_pct([trade], {}, days, 1.0, 0.20) == [2.0]
|
||||
|
||||
def test_notional_cap_shrinks_tight_stop_trades(self):
|
||||
# Stop 1 away would need 100% of equity in notional for 1% risk; the
|
||||
# 20% cap leaves 0.2% at risk, so +1R is only +0.2% of equity.
|
||||
trade = _trade(book=MANUAL_BOOK, entry=100.0, stop=99.0, close=101.0)
|
||||
days = [trade.closed_at.date()]
|
||||
assert pts._cumulative_sized_pct([trade], {}, days, 1.0, 0.20) == [0.2]
|
||||
|
||||
def test_hand_sized_shares_do_not_matter(self):
|
||||
small = _trade(book=MANUAL_BOOK, entry=100.0, stop=90.0, close=120.0, shares=1)
|
||||
large = _trade(book=MANUAL_BOOK, entry=100.0, stop=90.0, close=120.0, shares=5000)
|
||||
days = [small.closed_at.date()]
|
||||
assert pts._cumulative_sized_pct(
|
||||
[small], {}, days, 1.0, 0.20
|
||||
) == pts._cumulative_sized_pct([large], {}, days, 1.0, 0.20)
|
||||
|
||||
|
||||
class TestPerformanceSummaryPercent:
|
||||
@pytest.fixture
|
||||
async def session(self):
|
||||
from tests.conftest import _test_session_factory
|
||||
|
||||
async with _test_session_factory() as session:
|
||||
yield session
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shadow_percent_is_measured_on_equity_at_window_start(self, session):
|
||||
"""A pinned start date moves the base: P&L realized before it is equity."""
|
||||
from app.models.benchmark_price import BenchmarkPrice
|
||||
from app.models.ohlcv import OHLCVRecord
|
||||
from app.models.paper_trade import PaperTrade
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.user import User
|
||||
|
||||
today = datetime.now(timezone.utc).date()
|
||||
|
||||
def at(d):
|
||||
return datetime(d.year, d.month, d.day, 20, tzinfo=timezone.utc)
|
||||
|
||||
session.add(User(id=1, username="u", password_hash="x", role="user", has_access=True))
|
||||
ticker = Ticker(symbol="AAA")
|
||||
session.add(ticker)
|
||||
await session.flush()
|
||||
session.add(
|
||||
OHLCVRecord(ticker_id=ticker.id, date=today, open=110, high=110, low=110,
|
||||
close=110, volume=1)
|
||||
)
|
||||
for offset, close in ((10, 390.0), (3, 400.0), (0, 412.0)):
|
||||
session.add(BenchmarkPrice(symbol="SPY", date=today - timedelta(days=offset),
|
||||
close=close))
|
||||
common = dict(user_id=1, ticker_id=ticker.id, direction="long", entry_price=100.0,
|
||||
stop_loss=90.0, target=150.0, fill_mode="near_close")
|
||||
# Before the window: +$5,000 realized, so the window's base is $105k.
|
||||
session.add(PaperTrade(**common, book=SHADOW_BOOK, shares=100, status="closed",
|
||||
close_price=150.0, opened_at=at(today - timedelta(days=10)),
|
||||
closed_at=at(today - timedelta(days=8))))
|
||||
# In the window: +$1,050 on 105 shares = +1.0% of $105k.
|
||||
session.add(PaperTrade(**common, book=SHADOW_BOOK, shares=105, status="open",
|
||||
opened_at=at(today - timedelta(days=3))))
|
||||
# Hand-sized manual trade, +1R → +1.0% at strategy sizing whatever its shares.
|
||||
session.add(PaperTrade(**common, book=MANUAL_BOOK, shares=7, status="open",
|
||||
opened_at=at(today - timedelta(days=3))))
|
||||
await session.commit()
|
||||
await pts.settings_store.upsert_setting(
|
||||
session, pts.KEY_PERFORMANCE_START, (today - timedelta(days=5)).isoformat()
|
||||
)
|
||||
|
||||
summary = await pts.performance_summary(session, user_id=1)
|
||||
|
||||
assert summary["equity_base"] == pytest.approx(105_000.0)
|
||||
assert summary["risk_pct"] == pytest.approx(1.0)
|
||||
last = summary["series"][-1]
|
||||
assert last["shadow_pnl"] == pytest.approx(1050.0)
|
||||
assert last["shadow_pct"] == pytest.approx(1.0)
|
||||
assert last["manual_pct"] == pytest.approx(1.0)
|
||||
assert last["spy_pct"] == pytest.approx(3.0)
|
||||
assert summary["stats"]["shadow"]["pct"] == pytest.approx(1.0)
|
||||
assert summary["stats"]["manual"]["pct"] == pytest.approx(1.0)
|
||||
assert summary["stats"]["shadow"]["spy_pct"] == pytest.approx(3.0)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_strategy_vs_spy_starts_at_the_first_shadow_trade(self, session):
|
||||
"""Manual trades opening first must not charge the strategy for SPY's run-up."""
|
||||
from app.models.benchmark_price import BenchmarkPrice
|
||||
from app.models.paper_trade import PaperTrade
|
||||
from app.models.ticker import Ticker
|
||||
from app.models.user import User
|
||||
|
||||
today = datetime.now(timezone.utc).date()
|
||||
|
||||
def at(d):
|
||||
return datetime(d.year, d.month, d.day, 20, tzinfo=timezone.utc)
|
||||
|
||||
session.add(User(id=1, username="u", password_hash="x", role="user", has_access=True))
|
||||
ticker = Ticker(symbol="AAA")
|
||||
session.add(ticker)
|
||||
await session.flush()
|
||||
for offset, close in ((6, 400.0), (2, 420.0), (0, 441.0)):
|
||||
session.add(BenchmarkPrice(symbol="SPY", date=today - timedelta(days=offset),
|
||||
close=close))
|
||||
common = dict(user_id=1, ticker_id=ticker.id, direction="long", entry_price=100.0,
|
||||
stop_loss=90.0, target=150.0, fill_mode="near_close", shares=10,
|
||||
status="open")
|
||||
session.add(PaperTrade(**common, book=MANUAL_BOOK, opened_at=at(today - timedelta(days=6))))
|
||||
session.add(PaperTrade(**common, book=SHADOW_BOOK, opened_at=at(today - timedelta(days=2))))
|
||||
await session.commit()
|
||||
|
||||
summary = await pts.performance_summary(session, user_id=1)
|
||||
|
||||
# Full window 400 → 441 = +10.25%; the strategy's own window 420 → 441 = +5%.
|
||||
assert summary["stats"]["spy"]["pct"] == pytest.approx(10.25)
|
||||
assert summary["stats"]["shadow"]["spy_pct"] == pytest.approx(5.0)
|
||||
assert summary["stats"]["shadow"]["since"] == (today - timedelta(days=2)).isoformat()
|
||||
|
||||
|
||||
class TestPerformanceStartDate:
|
||||
@pytest.fixture
|
||||
async def session(self):
|
||||
|
||||
Reference in new issue
Block a user