How to write a trading algorithm with AI: from plain English to Python

Describe a trading idea in plain English and get a working Python algorithm, backtested on LEAN. What to ask the AI assistant, and how to check what it writes.

  • AI assistant
  • Python
  • Tutorial
How to write a trading algorithm with AI: cover with the MarketsCoder pixel robot

Most trading ideas start as a sentence: “buy the S&P 500 when it's above its 200-day average and step aside when it isn't”. Turning that sentence into code used to be the hard part. On MarketsCoder, the AI assistant does it with you: you describe the idea, it writes a Python algorithm for the open-source LEAN engine, runs a backtest, and tells you what happened.

This guide shows how to get a good first version, and, just as important, how to check it before you trust it.

The assistant's loop: describe an idea, the assistant writes Python, it runs a backtest, you read the report together, then refine
The assistant works in a loop with you: describe, write, backtest, read, refine. Every change is in your code, where you can see it.

1. Describe the idea precisely

The assistant can fill gaps, but it can't read your mind. The more of these you say, the closer the first version will be:

  • What to trade: a ticker, a list, or a rule (“the 20 largest US stocks”).
  • When to enter and exit: the condition, measured on what data and at what resolution.
  • How much: all in, an equal weight across holdings, or a fixed amount.
  • Dates and cash: the test period and starting capital.

A good first request reads like this:

Write a strategy that holds SPY when its close is above the 200-day simple moving
average, and holds cash otherwise. Daily data, 2010 to 2021, $100,000 starting cash.
Check the signal once a day after the close. Then run a backtest.

2. Read the code it writes

The assistant writes into your project's main.py, so the code is yours, in plain Python. For the request above it will look something like this:

from AlgorithmImports import *


class TrendFilter(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2010, 1, 1)
        self.set_end_date(2021, 1, 1)
        self.set_cash(100000)
        self.spy = self.add_equity("SPY", Resolution.DAILY).symbol
        self.trend = self.sma(self.spy, 200, Resolution.DAILY)
        self.set_warm_up(200, Resolution.DAILY)

    def on_data(self, slice):
        if self.is_warming_up or not self.trend.is_ready:
            return
        price = self.securities[self.spy].price
        if price > self.trend.current.value:
            self.set_holdings(self.spy, 1)
        else:
            self.liquidate(self.spy)

Before running anything, check three things:

  • Does it do what you said? Compare each rule in your sentence with a line of code.
  • Does it warm up? A 200-day average needs 200 days of data before the first decision.
  • Could it see the future? Signals should use data available at the decision, not after. Our guide to look-ahead bias lists where it hides.

If anything is unclear, ask: “explain line 14” or “why do you liquidate instead of selling?”. The assistant explains its own code, and yours.

3. Backtest, then read the report together

The assistant can run the backtest itself and read the report: returns against the benchmark, the deepest drawdown, the number of trades, fees. Ask it what stands out, and ask the uncomfortable questions too: “how much of the return came from one year?”, “what happened in 2020?”. Our backtesting walkthrough explains each number.

4. Refine one thing at a time

Change one rule per round, so you know what each change did: “add a 2% trailing stop”, “use weekly instead of daily checks”, “try QQQ as well”. Keep in mind that every tweak judged on the same dates makes the result a little less trustworthy, which is overfitting.

What the assistant can do

  • Write a strategy from a description, or from one of the dataset examples.
  • Explain code, line by line, and add comments.
  • Fix errors when a backtest fails, reading the logs to find why.
  • Run backtests and summarise their reports.
  • Load data you uploaded and use it in the strategy.

It runs on Claude by Anthropic and is billed by the tokens each answer uses, from your balance, with no subscription. See pricing for the rates.

Frequently asked questions

Can AI write a trading algorithm for me?

Yes. On MarketsCoder you describe the idea in plain English and the AI assistant writes it as a Python algorithm on the LEAN engine, runs a backtest and explains the result. You can read and change every line.

Do I need to know Python to use the AI assistant?

No, but it helps you check the work. Ask the assistant to explain any line, or to add comments. Many people learn Python this way, by changing working examples.

Which AI model does the assistant use?

Claude, by Anthropic. It has tools to read and edit your project's files, run backtests and read their reports.

What does the AI assistant cost?

It's billed by the tokens each answer uses, from your prepaid balance, plus any backtests it runs. There's no subscription.

Share on XLinkedIn

Test your own idea on point-in-time data.

Write a strategy in Python or describe it to the AI assistant, and see a full backtest report in minutes.

Get started