TL;DR
Research in Python is the same loop as research in a chat, written down as code you can rerun: look at the data, turn the idea into a function of its settings, test a grid of settings on years you are allowed to study, then freeze the best one and test it on years it never saw.
I ran that loop with the nexustrade Python SDK 5.2.0 on a momentum idea: hold the S&P 500 stocks with the highest 14-day RSI among those above their trend line, rebalanced monthly. The best of nine settings made +44.4% from 2016 to 2022 while SPY made +114.7%. Frozen and run on 2023 through October 2026 it made +45.3% against SPY's +106.0%. Every block of code and output below is from that run.
What the script found
Best development setting: 100-day trend filter, 10 names. Results from the run below.
The momentum book also fell less in the unseen years (18.5% worst drawdown against SPY's 20.3%), but it lost to holding the index in both periods.
Install the SDK and set your key
python3 -m pip install "nexustrade[stats]==5.2.0"
export NEXUSTRADE_API_KEY="your key from nexustrade.io/developers"The client reads NEXUSTRADE_API_KEY from the environment or a .env file.
Look at today's data before writing rules
# 1. Look at today's data before writing any rules.
screen = nt.nl.screen_stocks(
"S&P 500 stocks trading above their 200-day moving average with the highest 14-day RSI",
client=client,
)
print(screen.outcome, screen.row_count, "rows as of", screen.as_of_date)
print(screen.to_pandas().head(10).to_string())
# printed:
ROWS 25 rows as of 2026-11-13
ticker session_date latest_price sma_200 rsi_14 pct_above_sma_200
0 CLX 2026-11-13 109.46 99.30755 82.554121 10.223241
1 BRK-B 2026-11-13 592.94 500.43400 80.908013 18.485155
2 EW 2026-11-13 107.15 86.33490 80.276126 24.109717
3 VLTO 2026-11-13 118.25 93.78890 79.801128 26.081018
4 CAH 2026-11-13 281.10 225.10370 78.826675 24.875779
5 AIZ 2026-11-13 322.11 258.32905 77.439208 24.689809
6 MSI 2026-11-13 531.20 445.39770 77.229569 19.264199
7 COST 2026-11-13 1106.21 975.68450 76.037486 13.377839
8 STE 2026-11-13 264.32 224.13430 75.686871 17.929295
9 BDX 2026-11-13 218.03 170.03220 75.583961 28.228653The screen takes a plain-English question and returns rows, so you can see which stocks the rule would pick today before you backtest it.
Make the idea a function of its settings
# 2. One function turns a hypothesis's settings into a portfolio.
def momentum(trend_days, top_n):
return nt.portfolio(f"Momentum SMA{trend_days} top{top_n}", [
nt.strategy(
"Monthly rotation into strength",
nt.DaysSinceStrategyFired() >= nt.Value(28),
nt.dynamic_rebalance(
universe_config=nt.universe("SP500"),
pipeline=[
nt.filter(nt.Price(nt.CANDIDATE) > nt.SMA(nt.CANDIDATE, trend_days, "TradingDay")),
nt.select_top(nt.RSI(nt.CANDIDATE, 14), top_n),
],
weight_indicator=nt.Value(1),
limit=top_n,
deployment_percent=nt.Value(100),
),
),
], initial_value=10_000)
The trend length and basket size are arguments, so every variant is one call. The builders are the same rules the NexusTrade engine runs; there is no translation step.
Backtest nine variants in one request
DEV = {"start_date": "2016-01-01", "end_date": "2022-12-31", "baseline_symbol": "SPY"}
TEST = {"start_date": "2023-01-01", "end_date": "2026-10-31", "baseline_symbol": "SPY"}
# 3. Nine variants, one request, on the development years only (2016-2022).
grid = [(trend, n) for trend in (50, 100, 200) for n in (5, 10, 20)]
done = client.wait_for_backtests(client.create_backtests(
[nt.backtest(momentum(t, n), **DEV) for t, n in grid],
idempotency_key="explore-momentum-dev-v3",
))
print("SPY 2016-2022:", round(done[0]["result"]["baselineStatistics"]["percentChange"], 2), "%")
def row(settings, finished):
stats = finished["result"]["statistics"]
return {"trend_days": settings[0], "top_n": settings[1],
**{k: round(stats[k], 2) for k in ("percentChange", "sharpeRatio", "maxDrawdown")}}
dev = pd.DataFrame([row(s, d) for s, d in zip(grid, done)]).sort_values("sharpeRatio", ascending=False)
print(dev.to_string(index=False))
# printed:
SPY 2016-2022: 114.7 %
trend_days top_n percentChange sharpeRatio maxDrawdown
100 10 44.41 0.38 41.06
100 20 36.58 0.34 41.18
50 10 33.87 0.32 40.62
200 20 33.26 0.32 39.61
50 20 28.88 0.29 40.05
200 10 30.05 0.29 41.00
100 5 14.60 0.19 44.69
50 5 4.95 0.12 44.53
200 5 -3.23 0.06 39.40create_backtests submits the batch and returns at once; wait_for_backtests polls until all nine finish. Each result carries the SPY benchmark in baselineStatistics. Five-name baskets were the worst at every trend length.
Freeze the winner and test years it never saw
# 4. Freeze the best development setting and test it on years the search never saw.
best = dev.iloc[0]
test_op = client.create_backtest(
nt.backtest(momentum(int(best.trend_days), int(best.top_n)), **TEST),
idempotency_key="explore-momentum-test-v3",
)
test = client.wait_for_backtest(test_op["id"])["result"]
for label, stats in (("frozen momentum", test["statistics"]), ("SPY", test["baselineStatistics"])):
print(f"2023-2026 {label}:", {k: round(stats[k], 2) for k in ("percentChange", "sharpeRatio", "maxDrawdown")})
# printed:
2023-2026 frozen momentum: {'percentChange': 45.31, 'sharpeRatio': 0.39, 'maxDrawdown': 18.47}
2023-2026 SPY: {'percentChange': 105.98, 'sharpeRatio': 1.02, 'maxDrawdown': 20.34}Picking by Sharpe on the development years and testing once on later years is the minimum. A walk-forward study repeats that on rolling windows; the same experiment run through Aurora, with the sweep and walk-forward steps, is in how to create a custom quant experiment.
The whole script
research.py (75 lines)
"""Trend-filtered momentum research with the NexusTrade Python SDK (the code shown on the page).
Question: among S&P 500 stocks above their trend line, does holding the strongest names
(highest 14-day RSI), rebalanced monthly, beat SPY? And which trend length and basket size?
Run: NEXUSTRADE_API_KEY=... python research.py (writes receipts/ beside this file)
"""
import json
from pathlib import Path
import pandas as pd
import nexustrade as nt
client = nt.NexusTradeClient()
OUT = Path(__file__).resolve().parent / "receipts"
OUT.mkdir(exist_ok=True)
# 1. Look at today's data before writing any rules.
screen = nt.nl.screen_stocks(
"S&P 500 stocks trading above their 200-day moving average with the highest 14-day RSI",
client=client,
)
print(screen.outcome, screen.row_count, "rows as of", screen.as_of_date)
print(screen.to_pandas().head(10).to_string())
(OUT / "screen.json").write_text(json.dumps({
"id": screen.id, "outcome": screen.outcome, "as_of": screen.as_of_date,
"row_count": screen.row_count, "rows": screen.rows,
}, indent=1, default=str))
# 2. One function turns a hypothesis's settings into a portfolio.
def momentum(trend_days, top_n):
return nt.portfolio(f"Momentum SMA{trend_days} top{top_n}", [
nt.strategy(
"Monthly rotation into strength",
nt.DaysSinceStrategyFired() >= nt.Value(28),
nt.dynamic_rebalance(
universe_config=nt.universe("SP500"),
pipeline=[
nt.filter(nt.Price(nt.CANDIDATE) > nt.SMA(nt.CANDIDATE, trend_days, "TradingDay")),
nt.select_top(nt.RSI(nt.CANDIDATE, 14), top_n),
],
weight_indicator=nt.Value(1),
limit=top_n,
deployment_percent=nt.Value(100),
),
),
], initial_value=10_000)
DEV = {"start_date": "2016-01-01", "end_date": "2022-12-31", "baseline_symbol": "SPY"}
TEST = {"start_date": "2023-01-01", "end_date": "2026-10-31", "baseline_symbol": "SPY"}
# 3. Nine variants, one request, on the development years only (2016-2022).
grid = [(trend, n) for trend in (50, 100, 200) for n in (5, 10, 20)]
done = client.wait_for_backtests(client.create_backtests(
[nt.backtest(momentum(t, n), **DEV) for t, n in grid],
idempotency_key="explore-momentum-dev-v3",
))
print("SPY 2016-2022:", round(done[0]["result"]["baselineStatistics"]["percentChange"], 2), "%")
def row(settings, finished):
stats = finished["result"]["statistics"]
return {"trend_days": settings[0], "top_n": settings[1],
**{k: round(stats[k], 2) for k in ("percentChange", "sharpeRatio", "maxDrawdown")}}
dev = pd.DataFrame([row(s, d) for s, d in zip(grid, done)]).sort_values("sharpeRatio", ascending=False)
print(dev.to_string(index=False))
(OUT / "dev.json").write_text(json.dumps(done, indent=1, default=str))
# 4. Freeze the best development setting and test it on years the search never saw.
best = dev.iloc[0]
test_op = client.create_backtest(
nt.backtest(momentum(int(best.trend_days), int(best.top_n)), **TEST),
idempotency_key="explore-momentum-test-v3",
)
test = client.wait_for_backtest(test_op["id"])["result"]
for label, stats in (("frozen momentum", test["statistics"]), ("SPY", test["baselineStatistics"])):
print(f"2023-2026 {label}:", {k: round(stats[k], 2) for k in ("percentChange", "sharpeRatio", "maxDrawdown")})
(OUT / "test.json").write_text(json.dumps(test, indent=1, default=str))
How this was measured
Settings and limits
nexustrade 5.2.0 from PyPI, daily bars, $10,000 per backtest, platform default fees, SPY as the benchmark. The rule rebalances when 28 calendar days have passed since it last fired.
No comments yet.