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.
What you'll build
By the end of this page you'll have a small Python script that:
- Loads a file of daily prices.
- Adds a 20-candle moving average.
- Marks the places price turned around.
- 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
- Download Python 3 from python.org and install it. On Windows, tick the box that adds Python to PATH.
- Open a terminal (Command Prompt on Windows, Terminal on Mac).
- 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:
- import pandas as pd loads the library and gives it a short name.
- pd.read_csv reads your file into a table called df (short for "data frame"). parse_dates turns the date column into real dates.
- rolling(20).mean() works out the average close of the last 20 candles, for every row. That's a 20-period simple Moving average.
- df["above"] is a new column: True when the close is above the average, False when not.
- print(... .tail(3)) shows the last 3 rows.
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:
- window is 5 candles: 2 before, the candle itself, 2 after.
- center=True puts the candle in the middle of that window.
- A candle is a turn_high if its high equals the highest high in its window. Same idea for lows.
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:
- def creates a reusable function with 4 inputs.
- risk_money is the most you'd lose if the stop is hit: 1% of 10,000 = 100.
- risk_per_share is the gap between entry and stop: 2.00.
- if ... == 0 avoids dividing by zero if entry and stop are the same.
- int(risk_money // risk_per_share) gives whole shares: 100 ÷ 2 = 50 shares.
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:
- Backtest a rule on past data with pandas. See how to backtest in Python.
- Try a classic example, such as a moving average crossover bot.
- Connect to a paper account, never real money first. See Alpaca API basics or paper trading a bot.
- 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
- Using the close to decide and the same candle's open to buy. That's look-ahead. Shift your signals.
- Not checking the data. Missing days and wrong time zones break everything quietly.
- Copying code you don't understand. Change one thing at a time and print the result.
- Forgetting costs. Commission, Spread and Slippage belong in every test.
- Putting API keys in your script. When you connect to a broker later, keep keys in environment variables. See API key security.
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 anytimeOr 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: