StructureX

Home › Guides › Trading bots & code

Python for trading beginners: your first 20 lines of code

You don't need a computer science degree to use Python for trading. You need a price file, one free library and about 20 lines. Each one is explained below.

Beginner guide · 9-minute read · Updated 2026-10-21

What you'll build

By the end of this page you'll have a small Python script that:

  1. Loads a file of daily prices.
  2. Adds a 20-candle moving average.
  3. Marks the places price turned around.
  4. Works out a trade size from a stop.

No orders, no money, no broker. Just reading a chart with code. That's the right first step.

Step 1: Install Python and pandas

  1. Download Python 3 from python.org and install it. On Windows, tick the box that adds Python to PATH.
  2. Open a terminal (Command Prompt on Windows, Terminal on Mac).
  3. Type pip install pandas and press Enter.

pandas is a free library for tables of data. A price chart is just a table: one row per candle, with columns for date, open, high, low and close.

You'll write code in a plain text file ending in .py, then run it with python yourfile.py. A free editor such as VS Code makes this easier.

Step 2: Get a price file

You need a CSV file (a simple spreadsheet file) with these columns: date, open, high, low, close.

Many charting platforms and brokers let you export candles. Save the file as prices.csv in the same folder as your script.

Open it in a spreadsheet first. Check the dates run oldest to newest and there are no empty rows. Bad data gives wrong answers, and code won't warn you.

Step 3: Load it and add an average

Example code for learning — test it on paper first; it is not a ready-made trading system.

import pandas as pd
df = pd.read_csv("prices.csv", parse_dates=["date"])
df["sma20"] = df["close"].rolling(20).mean()
df["above"] = df["close"] > df["sma20"]
print(df[["date", "close", "sma20", "above"]].tail(3))

Line by line:

The first 19 rows show NaN ("not a number") for the average. That's correct — there aren't 20 candles yet to average.

Step 4: Mark the turning points

Our method starts with the last places price turned around. In code, a simple version is: a candle whose high is the highest of the 2 candles before it and the 2 after it.

n = 2
window = 2 * n + 1
df["turn_high"] = df["high"] == df["high"].rolling(window, center=True).max()
df["turn_low"] = df["low"] == df["low"].rolling(window, center=True).min()
print(df[df["turn_high"]][["date", "high"]].tail(3))

In plain words:

Now the important part.

The look-ahead trap

center=True looks at 2 candles in the future. That's fine for marking an old chart. It's a disaster in a test.

On the day a turning point forms, you can't know it yet. You only know 2 candles later. A test that uses it on the same day is cheating — that's called look-ahead bias, and it makes results look far better than real life.

The fix is one line. It moves each mark 2 rows later, to the day you'd actually know:

df["turn_high_known"] = df["turn_high"].shift(n, fill_value=False)

Use the _known column in anything that decides a trade. Make this a habit: for every column, ask "on this row's date, could I have known this?"

Step 5: Size a trade from the stop

Size comes from the stop, not from a feeling. Here's that rule as a function:

def position_size(account, risk_pct, entry, stop):
    risk_money = account * risk_pct / 100
    risk_per_share = abs(entry - stop)
    if risk_per_share == 0:
        return 0
    return int(risk_money // risk_per_share)
print(position_size(10_000, 1, 50.00, 48.00))   # prints 50

Line by line:

A math example, not a promise. Losses can be bigger than planned if price jumps past the stop. This is the same math as our position size calculator — check your function against it.

What to build next

You now have the pieces every trading script uses: load data, add a column, avoid look-ahead, size from the stop.

Next steps, in order:

  1. Backtest a rule on past data with pandas. See how to backtest in Python.
  2. Try a classic example, such as a moving average crossover bot.
  3. Connect to a paper account, never real money first. See Alpaca API basics or paper trading a bot.
  4. Add risk controls before any live order: a daily loss limit, a kill switch, error handling and a log of every order. See trading bot risk controls.

Code doesn't make a rule good. It makes it exact. If the rule loses on a chart by hand, it will lose in Python too — just faster and more consistently.

Common beginner mistakes

Try it today: run Step 4 on a chart you know, then open the same chart and check 3 of the marked turning points by eye. If the code and your eyes disagree, find out why.

Questions

Is Python good for trading?

Yes, for most retail uses. It's readable, free, and has pandas for price data plus libraries for many brokers and exchanges. It's not the fastest language, but speed rarely matters for beginners.

How long does it take to learn Python for trading?

The basics on this page take a day or two. Writing your own honest backtest takes a few weeks of practice. Building a bot that runs safely takes longer — mostly testing.

What Python libraries are used for trading?

pandas for price tables is the core. Broker libraries such as alpaca-py, ib_async and ccxt connect to brokers and exchanges. Start with pandas alone.

Do I need to know math to use Python for trading?

Basic arithmetic covers most of it: averages, percentages and the gap between entry and stop. The harder part is logic — making sure every rule only uses information you'd have had at the time.

Want the next step? We'll walk you through it.

Four free lessons by email, one every few days — each with a 10-minute exercise on a real chart.

Send Me the Free Lessons 4 short emails · No spam · Unsubscribe anytime

Or see the whole method, step by step:

See What’s Inside the Course Try everything free first. Decide when you're ready. · Open the free chart tool (works in the TradingView phone app)

One chart idea a day, in plain English. Follow along:

Follow on XFollow on TradingView