82 lines
2.2 KiB
Python
82 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
import pandas as pd
|
|
|
|
from web_core.analytics import simulate_trend_trades
|
|
from web_core.constants import TREND_BEAR, TREND_BULL, TREND_NEUTRAL
|
|
|
|
|
|
def test_simulate_trend_trades_returns_empty_when_insufficient_rows() -> None:
|
|
idx = pd.date_range("2025-01-01", periods=3, freq="D")
|
|
df = pd.DataFrame(
|
|
{
|
|
"Close": [100.0, 101.0, 102.0],
|
|
"trend_state": [TREND_NEUTRAL, TREND_BULL, TREND_BULL],
|
|
},
|
|
index=idx,
|
|
)
|
|
|
|
out = simulate_trend_trades(df)
|
|
|
|
assert out.empty
|
|
|
|
|
|
def test_simulate_trend_trades_closes_trade_on_opposite_signal() -> None:
|
|
idx = pd.date_range("2025-01-01", periods=7, freq="D")
|
|
df = pd.DataFrame(
|
|
{
|
|
"Close": [95.0, 98.0, 100.0, 102.0, 104.0, 110.0, 108.0],
|
|
"trend_state": [
|
|
TREND_NEUTRAL,
|
|
TREND_NEUTRAL,
|
|
TREND_BULL,
|
|
TREND_BULL,
|
|
TREND_BULL,
|
|
TREND_BEAR,
|
|
TREND_BEAR,
|
|
],
|
|
},
|
|
index=idx,
|
|
)
|
|
|
|
out = simulate_trend_trades(df)
|
|
|
|
assert len(out) == 1
|
|
trade = out.iloc[0]
|
|
assert trade["direction"] == "LONG"
|
|
assert trade["entry_timestamp"] == idx[2]
|
|
assert trade["exit_timestamp"] == idx[5]
|
|
assert trade["bars_held"] == 3
|
|
assert trade["pnl_pct"] == 10.0
|
|
assert trade["outcome"] == "Win"
|
|
|
|
|
|
def test_simulate_trend_trades_handles_multiple_flips_and_max_examples() -> None:
|
|
idx = pd.date_range("2025-01-01", periods=7, freq="D")
|
|
df = pd.DataFrame(
|
|
{
|
|
"Close": [90.0, 100.0, 103.0, 95.0, 92.0, 80.0, 82.0],
|
|
"trend_state": [
|
|
TREND_NEUTRAL,
|
|
TREND_BULL,
|
|
TREND_BULL,
|
|
TREND_BEAR,
|
|
TREND_BEAR,
|
|
TREND_BULL,
|
|
TREND_BULL,
|
|
],
|
|
},
|
|
index=idx,
|
|
)
|
|
|
|
out = simulate_trend_trades(df, max_examples=1)
|
|
|
|
assert len(out) == 1
|
|
trade = out.iloc[0]
|
|
assert trade["direction"] == "SHORT"
|
|
assert trade["entry_timestamp"] == idx[3]
|
|
assert trade["exit_timestamp"] == idx[5]
|
|
assert trade["bars_held"] == 2
|
|
assert trade["pnl_pct"] == 15.79
|
|
assert trade["outcome"] == "Win"
|