# NexusTrade Python SDK 1.42.0
import nexustrade as nt


def create_strategy():
    asset = nt.stock_asset("AAPL")
    entry = nt.Price(asset) > nt.SMA(asset, 50, "Day")
    exit_signal = nt.Price(asset) <= nt.SMA(asset, 50, "Day")
    return nt.portfolio("Technical indicator research", [
        nt.strategy("Enter", entry & (nt.PositionValue(asset) == nt.Value(0)),
                    nt.buy(asset, 10, "percent of buying power")),
        nt.strategy("Exit", exit_signal & (nt.PositionValue(asset) > nt.Value(0)),
                    nt.sell(asset, 100, "percent of current positions")),
    ], initial_value=10000, alerts_enabled=False, dividend_policy="cash")


def test_period(start_date, end_date, request_key, client=None):
    client = client or nt.NexusTradeClient()
    operation = client.create_backtest(nt.backtest(
        create_strategy(), start_date=start_date, end_date=end_date,
        interval="Day", baseline_symbol="SPY", initial_value=10000,
        dividend_policy="cash", generate_events=True,
        fee_config={"Stock": {"type": "percent", "amount": 0.1}},
    ), idempotency_key=request_key)
    return client.wait_for_backtest(operation["id"])

# create_strategy() builds locally. test_period(...) submits a test.
# Use a different request key for each changed period or candidate.
