NexusTrade guides

Backtest a portfolio in Python

Build a typed portfolio, submit one historical backtest, and read the completed result using the NexusTrade Python SDK.

Install and authenticate

Install nexustrade with pip. Export NEXUSTRADE_API_KEY through your runtime secret configuration. The SDK discovers that variable; keep it out of source files. A registered key needs write to submit and read to retrieve operations.

shell
pip install nexustrade
# Configure NEXUSTRADE_API_KEY in your runtime environment.

Create a portfolio and submit the backtest

Save the complete Python example in a script and run it in the environment where you installed nexustrade and configured the API key. This example buys 100 SPY shares whenever the strategy evaluates true. The dates and sizing are example configuration, not a reported return. Authoring a book locally performs no trades. Running create_backtest submits compute and may consume credits.

python
from nexustrade import NexusTradeClient, always, backtest, buy, portfolio, stock_asset, strategy

client = NexusTradeClient()

book = portfolio("Example", [
    strategy("Buy SPY", always(), buy(stock_asset("SPY"), 100)),
])

operation = client.create_backtest(
    backtest(book, start_date="2024-01-01", end_date="2024-12-31"),
    idempotency_key="example-v1",
)
result = client.wait_for_backtest(operation["id"])
print(result["result"])

Wait for the result

create_backtest returns an operation immediately. wait_for_backtest polls that operation rather than submitting a second job. Preserve the idempotency key while retrying the same request. Changing the payload requires a new key.

Successful completion returns the operation's result. The wait helper raises on failed or cancelled operations by default. If waiting times out, retrieve the operation with client.get_backtest using the saved ID or resume waiting on that ID; a timeout does not cancel the job. Inspect terminal status, result statistics and warnings. Historical backtest fills are modeled; they are not paper or live performance. If collateral statistics are missing, they were not recorded. They do not indicate zero risk.

Continue exploring