Python for Traders
Python from zero for market data: setup, types, f-strings and strings, lists, dicts, loops and functions, modules, venv, errors, files, JSON and dates, NumPy and pandas, cleaning, resampling and charts, symbols, timings, APIs, quotes, WebSockets and returns.
00Python for traders: atlas and routes
Python from zero with market data: the language basics, core data structures, files and robust code, NumPy and pandas, and Indian and US market data. Condensed from OpenAlgo's free Open Varsity course. Educational, not investment advice.
Python for traders topic atlas#
How to use this sheet#
- New to code: getting started and core programming, typing every example yourself.
- Know Python, new to data: jump to NumPy and pandas.
- Ready to touch markets: symbols, timings, OHLCV and returns, then the Algo Trading sheet.
- All code on this sheet is our own short example in the course's spirit, not copied from it.
The trader's data pipeline#
flowchart TD F["Fetch: yfinance or a broker API"] --> S["Save to CSV"] S --> L["Load with a date index"] L --> C["Clean: gaps, types, duplicates"] C --> X["Features: returns, averages, ranges"] X --> G["Signal: 0 or 1 position"] G --> K["Scorecard: return, win rate, drawdown"]
Every module of the course feeds one step: the language basics, files and JSON, pandas, then market data.
Check yourself 2 questions
What comes right after fetching data in the pipeline?
Show answer
Save it to CSV, then work offline from the file.
What form does the signal take before scoring?
Show answer
A 0 or 1 position series.
Takeaway Fetch, save, load with a date index, clean, build features, make a 0/1 signal, then score it.
Why Python for finance#
- Pure Python is slow at big loops: it handles one value per step.
- Libraries are fast because a readable Python layer sits on a compiled core: NumPy and pandas (C), TA-Lib (C), TensorFlow (C++), OpenAlgo and OpenGreeks (Rust). "Python is the steering wheel; C and Rust are the engine."
- Summing the squares of 5 million numbers: a plain loop took about 468 ms, NumPy about 15 ms, roughly 30× faster for the identical answer.
- pandas was created in 2008 at a hedge fund (AQR); its name comes from "panel data". Banks, quant funds and Indian prop desks run research and automation in Python.
Check yourself 2 questions
Why is pure Python slow at big loops?
Show answer
It handles one value per step; vectorised libraries hand the loop to compiled code.
What languages power NumPy and pandas underneath?
Show answer
C.
Takeaway Python is the steering wheel and C or Rust the engine: libraries are fast because a readable layer sits on a compiled core.
01Getting started: setup, variables, types, operators and strings
OpenAlgo Open Varsity · Python for Traders · chapters 1–8 (installing, VS Code and Jupyter, variables, numbers and types, operators, f-strings, strings)
Install and set up#
| Task | Command |
|---|---|
| Check Python (any 3.x) | python --version (or python3 on some Mac/Linux) |
| Check pip | pip --version (or python -m pip) |
| Install a library from PyPI | pip install pandas |
| Run a script | python hello.py |
- Install from python.org; on Windows tick Add python.exe to PATH or the terminal won't find it.
- Edit in VS Code with the Python extension; open a folder, not a single file.
- "Permission denied" on installs: use a virtual environment rather than admin rights.
Check yourself 2 questions
Command to install pandas?
Show answer
pip install pandas.Why tick 'Add python.exe to PATH' on Windows?
Show answer
Otherwise the terminal won't find Python.
Takeaway Check python and pip versions, install from PyPI with pip, run scripts from the terminal; on Windows add Python to PATH.
Scripts vs notebooks#
| Script (.py) | Notebook (.ipynb) | |
|---|---|---|
| Best for | Reusable, automated runs | Exploring and learning |
| Runs | Top to bottom | Cell by cell |
| Output | Terminal; needs print() | Inline; a cell's last line shows itself |
The Python inside is identical. Explore in a notebook, then move what works into a script you can schedule.
Check yourself 2 questions
What does a notebook show without print()?
Show answer
A cell's last expression, displayed inline.
Which suits automated, repeatable runs?
Show answer
A .py script.
Takeaway Explore in a notebook, then move what works into a script you can schedule.
Variables and comments#
symbol = "RELIANCE" # str quantity = 50 # int buy_price = 1300.00 # float ltp = 1313.60 invested = quantity * buy_price # 65000.0 profit = (ltp - buy_price) * quantity # 680.0 stop_loss = buy_price * 0.98 # exit 2% below entry: say WHY
=assigns ("gets"); equality is==.- Reassigning keeps only the newest value; use a list to keep history.
- Names: letters, digits and underscores, no leading digit, in
snake_case.invested = quantity * buy_pricebeatsx = 50 * 1300.
Check yourself 2 questions
What's the difference between = and ==?
Show answer
= assigns a value; == tests equality.
What should a good comment explain?
Show answer
Why, not what: for example, why the stop is 2% below entry.
Takeaway = assigns, == compares; reassigning keeps only the newest value; comments should say why.
Numbers and types#
| Type | Example | Use |
|---|---|---|
| int | 50 | Shares, lots (no size limit) |
| float | 1313.60 | Prices, returns |
| str | "RELIANCE" | Symbols, labels |
| bool | True | Flags |
100 / 4is25.0, a float.0.1 + 0.2is0.30000000000000004: floats are binary approximations, so round for display and useDecimalfor exact accounting.- Keyboard, file and web input arrives as text:
"50" * 3is"505050"; convert withint()orfloat()first. - Falsy:
0,"", empty containers,None; almost everything else is truthy.
Check yourself 2 questions
What does 0.1 + 0.2 give in Python, and why?
Show answer
0.30000000000000004, because floats are binary approximations.
What type does input() return?
Show answer
Always a string.
Takeaway int, float, str and bool; floats are binary approximations, and input from keyboard, files or the web arrives as text.
Operators and P&L maths#
| Operator | Meaning | Example |
|---|---|---|
// | Floor division | 100000 // 65680 → 1 whole lot |
% | Remainder | 100000 % 65680 → 34320 cash left |
** | Power | (1.01 ** 5 - 1) * 100 ≈ 5.10% (1% a day for 5 days) |
== != > < | Comparisons → True/False | price > sma |
and or not | Combine conditions | support < price < resistance |
// truncates (1.52 lots → 1), and * binds before +: parenthesise anything not obvious.
Check yourself 2 questions
₹1,00,000 and a ₹65,680 lot: how many lots and what's left?
Show answer
100000 // 65680 = 1 lot; 100000 % 65680 = ₹34,320 left.
1% a day for 5 days compounds to what?
Show answer
About 5.10% ((1.01 ** 5 − 1) × 100).
Takeaway // gives whole lots, % gives the remainder, ** compounds; comparisons return True or False.
Printing money: f-string formats#
| Spec | Output | Use |
|---|---|---|
{v:,.2f} | 65,680.00 | Money with commas |
{v:+.2f} | +13.60 | Signed change |
{r:.2%} | 1.05% | Returns (multiplies by 100) |
{s:<10} / {v:>10.2f} | aligned columns | Labels left, numbers right |
{n:05d} | 00042 | Zero-padded IDs |
{d:%d %b %Y} | 25 Jun 2026 | Dates |
{x=} | x=1313.6 | Quick debugging |
input() always returns a string: qty = int(input("Shares? ")). Forgetting the f prefix prints the braces literally.
Check yourself 2 questions
Which format spec prints 65,680.00?
Show answer
{v:,.2f}.
What does {r:.2%} do to 0.0105?
Show answer
Prints 1.05%; it multiplies by 100.
Takeaway {v:,.2f} for money, {r:.2%} for returns, {x=} for quick debugging.
Strings: symbols, dates and messy text#
s = "RELIANCE" s[0], s[-1], s[:3] # 'R', 'E', 'REL' d = "2026-06-25" d[:4], d[5:7], d[8:] # '2026', '06', '25' clean = " reliance ".strip().upper() # capture the result! "NSE:RELIANCE".replace("NSE", "BSE") # 'BSE:RELIANCE' syms = "RELIANCE,TCS,INFY".split(",") # list of 3 " | ".join(syms) # 'RELIANCE | TCS | INFY' yahoo = s + ".NS" # 'RELIANCE.NS'
- Indexes start at 0; slices stop before the end index.
- Strings are immutable: methods return a new string, so assign it.
joinis called on the separator, not the list.
Check yourself 2 questions
How do you split 'RELIANCE,TCS,INFY' into a list?
Show answer
.split(",").Why does
s.strip()alone sometimes seem to do nothing?Show answer
Strings are immutable; the result must be assigned.
Takeaway Slice, strip, upper, replace, split and join; string methods return new strings, so capture the result.
02Core programming: data structures, decisions, loops and functions
OpenAlgo Open Varsity · Python for Traders · chapters 9–16 (lists, tuples, dictionaries, sets, conditionals, loops, comprehensions, functions)
Which container?#
| Container | Syntax | Access by | Mutable | Trading use |
|---|---|---|---|---|
| List | [101.2, 103.5] | Position | Yes | Price series, watchlist, trades |
| Tuple | (o, h, l, c) | Position | No | A fixed record: an OHLC bar, multiple return values |
| Dict | {"ltp": 1313.6} | Key (name) | Yes | A quote, API JSON, symbol → data lookup |
| Set | {"TCS", "INFY"} | Membership | Yes | Unique symbols, watchlist overlaps |
Rule of thumb: if changing one item alone would be a bug, use a tuple; if the collection is meant to change, a list; to look up by name, a dict; for uniqueness and fast "is it in here?", a set.
Check yourself 2 questions
Which container suits an OHLC bar that shouldn't change?
Show answer
A tuple.
Which suits API JSON or a symbol-to-data lookup?
Show answer
A dict.
Takeaway Lists for series, tuples for fixed records, dicts for keyed lookups, sets for unique membership.
Lists#
closes = [101.2, 103.5, 102.8, 104.1, 104.9, 106.3] closes[-1], closes[-2:] # today, last two days round(sum(closes) / len(closes), 2) watch = ["RELIANCE", "TCS", "INFY"] watch.append("HDFCBANK"); watch.insert(0, "NIFTY") watch.remove("TCS"); last = watch.pop() ranked = sorted(closes, reverse=True) # new list closes.sort() # in place, returns None
x = lst.sort()givesNone; prefersorted()to keep the original.remove()deletes only the first match and errors if absent.- A list of lists is a table: the idea behind DataFrames.
Check yourself 2 questions
How do you get the last two closes?
Show answer
closes[-2:].What does
pop()return?Show answer
The removed last item.
Takeaway Index from the end with −1, append and insert to add, remove and pop to delete, sorted to rank.
Tuples and unpacking#
bar = (1300.0, 1318.4, 1297.2, 1313.6) open_, high, low, close = bar # 'open' is a built-in day_range = high - low # 21.2 lots, rem = divmod(250, 75) # (3, 25): 3 lots, 25 shares spare support, resistance = resistance, support # swap, no temp
Assigning bar[0] = x raises TypeError: that protection is the point.
Check yourself 2 questions
divmod(250, 75) returns what?
Show answer
(3, 25): three lots and 25 shares spare.
What happens if you assign to bar[0] on a tuple?
Show answer
TypeError: tuples can't be changed, which is the point.
Takeaway Tuples are immutable records; unpack them into names, and divmod returns two values at once.
Dictionaries: quotes and JSON#
quote = {"symbol": "RELIANCE", "ltp": 1313.60, "volume": 4521000} quote["ltp"] = 1315.20 # update quote["high"] = 1318.40 # assignment adds a key quote.get("bid", "n/a") # safe read, no KeyError watch = {"TCS": {"ltp": 2109.0, "chg": -8.5}} watch["TCS"]["ltp"] # nested, like API JSON for sym, data in watch.items(): print(f"{sym:9} ltp {data['ltp']:>9.2f}")
Keys are case-sensitive ("ltp" ≠ "LTP"), a typo on assignment silently creates a new key, and lookups stay fast at any size.
Check yourself 2 questions
How do you read a key that may be missing without a KeyError?
Show answer
quote.get("bid", "n/a").What does assigning to a new key do?
Show answer
Adds it to the dict.
Takeaway Dicts map keys to values; .get() reads safely, and nested dicts mirror API JSON.
Sets: unique and overlapping#
trades = ["RELIANCE", "TCS", "RELIANCE", "INFY", "TCS"] unique = sorted(set(trades)) # 3 names, sorted for display mine = {"RELIANCE", "TCS", "INFY", "HDFCBANK"} friend = {"INFY", "HDFCBANK", "ITC", "SBIN"} mine & friend # in both mine | friend # in either (6 unique) mine - friend # only mine
{} is an empty dict; an empty set is set(). Sets have no order and no [0].
Check yourself 2 questions
Which operator gives symbols in both of two sets?
Show answer
& (intersection).
Does {} create an empty set?
Show answer
No, an empty dict; use set().
Takeaway Sets remove duplicates and answer overlap questions with &, | and −.
Decisions: if, elif, else#
def signal(price, sma, rsi): if price <= 0: # guard clause first return "BAD DATA" if price > sma and rsi < 70: return "BUY" elif price < sma: return "SELL" else: return "HOLD" signal(1313.60, 1305.00, 45) # BUY signal(1313.60, 1305.00, 75) # HOLD: overbought, still above SMA
- Only the first true branch runs, so order matters.
- Indentation (4 spaces) is syntax: it defines the block.
- Test bad cases first and return early instead of nesting deeply.
Check yourself 2 questions
Why check
price <= 0first?Show answer
A guard clause rejects bad data before any logic runs.
Price above SMA but RSI 75: what does the example return?
Show answer
HOLD: overbought, though still above the SMA.
Takeaway Put guard clauses first; only the first true branch runs, so order conditions carefully.
Loops: for, while, break, continue#
total = 0.0 for i, c in enumerate(closes, start=1): total += c capital, price, shares = 100000, 1313.60, 0 while capital >= price: # must move towards stopping capital -= price; shares += 1 # 76 shares, 166.40 left for p in [101.2, 99.8, 104.1, 106.3]: if p < 100: continue # skip this one if p >= 105: print("alert", p); break # stop scanning
for visits a known collection; while runs until a condition fails (an unchanging condition hangs forever: Ctrl+C). range(1, 6) stops at 5.
Check yourself 2 questions
What must every while loop do?
Show answer
Move towards its stopping condition.
What does
continuedo?Show answer
Skips the rest of this iteration and moves to the next.
Takeaway for loops over items, while loops until a condition fails, continue skips one item, break stops the loop.
Comprehensions#
tickers = [s + ".NS" for s in symbols] up = [c for c in closes if c > 100] # filter, then transform big = [round(c, 1) for c in closes if c > 104] # parallel lists → dict ltp = {s: p for s, p in zip(symbols, prices)}
Order is value, loop, optional filter. Use the one-breath test: if the purpose doesn't fit a short sentence, write a normal loop. Clear beats clever.
Check yourself 2 questions
Write a list of closes above 100.
Show answer
[c for c in closes if c > 100].How do you build a dict from two parallel lists?
Show answer
{s: p for s, p in zip(symbols, prices)}.
Takeaway Comprehensions read value, loop, optional filter; use them only when the purpose fits one breath.
Functions#
def pct_change(old, new): """Percentage change from old to new.""" return (new - old) / old * 100 def brokerage(turnover, rate=0.0003, cap=20.0): """0.03% of turnover, capped at ₹20 per order.""" return min(turnover * rate, cap) def trade_summary(buy, sell, qty): profit = (sell - buy) * qty return profit, pct_change(buy, sell) # a tuple brokerage(10000) # 3.0 brokerage(500000) # 20.0 (150 capped) p, move = trade_summary(1300, 1313.60, 50) # 680.0, 1.05
One function means one place to fix a bug. A function without return gives back None; defaults apply only when the argument is left out.
Check yourself 2 questions
What does
min(turnover * rate, cap)implement?Show answer
Brokerage at a rate, capped at ₹20 per order.
How does a function return two values?
Show answer
As a tuple, e.g.
return profit, pct.
Takeaway Functions name a job, take arguments with sensible defaults, document themselves and can return several values.
03Libraries, files and robust code
OpenAlgo Open Varsity · Python for Traders · chapters 17–24 (modules, standard library, pip and venv, errors, files, JSON, dates, getting unstuck)
Modules and imports#
| Style | Syntax | Call as |
|---|---|---|
| Whole module | import math | math.sqrt(2) |
| Specific names | from statistics import mean, stdev | mean(x) |
| Alias | import pandas as pd | pd.read_csv(...) |
| Wildcard | from m import * | Avoid: name clashes, hidden origins |
- Any
.pyfile is a module: putpnl()andpct_change()intradetools.pyandimport tradetools(no.py). - Python looks in your script's folder first, so a local
pandas.pywould shadow the real library. - Whole lots:
math.floor(76.12)→ 76,math.ceil(76.12)→ 77.
Check yourself 2 questions
Why avoid
from m import *?Show answer
Name clashes and hidden origins.
How do you reuse your own pnl() function across scripts?
Show answer
Put it in a .py file (a module) and import it.
Takeaway Import whole modules, specific names or aliases; avoid wildcard imports.
Standard library drawers#
| Module | Use |
|---|---|
datetime | Dates, times, date maths, formatting |
random | Simulations; random.seed(42) makes runs repeatable |
json | API data in and out |
math, statistics | Roots, rounding, mean, median, stdev |
csv, pathlib | Simple tables, file paths |
No install needed. Know which drawer exists and look up the details. timedelta counts calendar days, not trading days, and random is for simulation, never security.
Check yourself 2 questions
How do you make random simulations repeatable?
Show answer
random.seed(42)(any fixed seed).Which module handles API data in and out?
Show answer
json.
Takeaway datetime, random, json, math, statistics, csv and pathlib come with Python; know which drawer exists.
pip and virtual environments#
python -m venv .venv # one environment per project .venv\Scripts\activate # Windows source .venv/bin/activate # Mac / Linux pip install pandas yfinance matplotlib pip freeze > requirements.txt # record exact versions pip install -r requirements.txt # rebuild anywhere deactivate
- Run pip in the terminal, not inside Python; activate first (the prompt shows
(.venv)) or installs go global. - A clean
importproves the install; a missing one raisesModuleNotFoundError. - "pip not recognised": use
python -m pip.
Check yourself 2 questions
How do you record exact package versions?
Show answer
pip freeze > requirements.txt.Where should pip be run?
Show answer
In the terminal, not inside Python.
Takeaway One virtual environment per project, and requirements.txt to rebuild it anywhere.
Errors you will meet#
| Error | Cause | Trading example | Fix |
|---|---|---|---|
SyntaxError | Missing colon or bracket | An if without : | Fix the layout; nothing runs until then |
NameError | Undefined or misspelt name | ltp vs LTP | Check spelling and definition |
TypeError | Wrong type for the operation | Text price + number | Convert types |
ValueError | Right type, bad value | int("fifty"); price of 0 in sizing | Validate; raise your own clear error |
IndexError | Position doesn't exist | closes[10] on 7 closes | Check the length |
KeyError | Dict key missing | Quote without "bid" | q.get("bid") |
ZeroDivisionError | Divide by zero | Average of an empty list | Guard or return a fallback |
ModuleNotFoundError | Library not installed | import yfinance | pip install in the active venv |
Check yourself 2 questions
Adding a text price to a number raises which error?
Show answer
TypeError.
int("fifty") raises which error?
Show answer
ValueError: right type, bad value.
Takeaway SyntaxError, NameError, TypeError, ValueError, KeyError and more: each names a specific cause.
try / except done right#
def avg(prices): try: return sum(prices) / len(prices) except ZeroDivisionError: # catch the specific error return 0.0 def position_size(capital, price): if price <= 0: # fail early, clearly raise ValueError("price must be positive") return int(capital // price)
- Wrap only the risky line; never a bare
except:, which hides real bugs. - Read a traceback bottom-up: the last line says what, the lines above say where.
- Print actual values and change one thing at a time.
Check yourself 2 questions
Why not use a bare
except:?Show answer
It hides every error, including bugs you need to see.
What should position_size do with a negative price?
Show answer
Raise a ValueError early and clearly.
Takeaway Wrap only the risky line, catch specific errors, never use a bare except, and raise early on bad input.
Files: read, write, append#
| Mode | Does |
|---|---|
"r" | Read (default) |
"w" | Create or overwrite immediately |
"a" | Append; ideal for logs and journals |
with open("watchlist.txt", "a") as f: f.write("HDFCBANK,1642.40\n") # add the newline yourself with open("watchlist.txt") as f: for line in f: sym, price = line.strip().split(",") print(f"{sym:<10}{float(price):>10.2f}")
Always use with so the file closes; lines keep their trailing newline until stripped; relative paths depend on where you run from.
Check yourself 2 questions
Which mode suits a trading journal?
Show answer
'a' (append).
What's the danger of 'w'?
Show answer
It overwrites the file immediately.
Takeaway 'r' reads, 'w' overwrites immediately, 'a' appends; use with open(...) so files close.
JSON: the language of market APIs#
| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string, number | str, int / float |
true / false / null | True / False / None |
import json resp = json.loads(text) # s = string best_bid = resp["data"]["depth"]["buy"][0]["price"] with open("watch.json", "w") as f: json.dump(watch, f, indent=2) # no s = file
JSON needs double quotes. Until you parse it, it is just text, so text["ltp"] fails.
Check yourself 2 questions
What does JSON null become in Python?
Show answer
None.
json.loads versus json.load?
Show answer
loads parses a string; load reads from a file.
Takeaway JSON objects become dicts and arrays become lists; loads and dumps work on strings, load and dump on files.
Dates and market hours#
from datetime import datetime, time, timedelta # text → datetime dt = datetime.strptime("2026-06-25 09:15", "%Y-%m-%d %H:%M") dt.strftime("%A %d %b %Y") # datetime → text dt + timedelta(weeks=1); dt - timedelta(minutes=90) def market_open(dt): # NSE cash 09:15–15:30 IST in_hours = time(9, 15) <= dt.time() <= time(15, 30) return dt.weekday() < 5 and in_hours
| Code | Meaning | Code | Meaning |
|---|---|---|---|
%Y %m %d | Year, month, day | %H %M | 24-hour, minute |
%I %p | 12-hour, AM/PM | %A %b | Weekday, short month |
weekday() is Mon 0 to Sun 6 and knows nothing about exchange holidays: keep a holiday list.
Check yourself 2 questions
Which function turns '2026-06-25 09:15' into a datetime?
Show answer
datetime.strptimewith a format string.NSE cash market hours?
Show answer
9:15 am to 3:30 pm IST, weekdays.
Takeaway strptime turns text into datetimes, strftime formats them, timedelta does date maths.
The unstuck ladder#
- Read the error: the last line names the problem.
- Ask Python:
type(x)(what is it?),dir(x)(what can it do?),help(x)(how?). - Search the exact message, in quotes.
- Shrink it to the smallest snippet that still fails; that often reveals the bug.
- Ask clearly: code, output, and what you tried.
Experts look things up constantly. Be wary of pasting code you don't understand, from anywhere.
Check yourself 2 questions
Which line of a traceback names the problem?
Show answer
The last line.
Why shrink failing code to the smallest snippet?
Show answer
It often reveals the bug itself.
Takeaway Read the error's last line, inspect with type, dir and help, search the exact message, shrink the example, then ask clearly.
04NumPy and pandas: arrays, tables, cleaning, time series and charts
OpenAlgo Open Varsity · Python for Traders · chapters 25–32 (NumPy, Series, DataFrames, loading data, cleaning, time series, grouping, charts)
NumPy: vectorised maths#
import numpy as np c = np.array([291.58, 295.63, 291.13, 296.42, 299.24]) c - c[0] # rebase to day 1 c / c[0] * 100 # % of start ret = np.diff(c) / c[:-1] * 100 # daily returns, no loop (c > c.mean()).sum() # count days above average np.where(ret > 0, "up", "down") rng = np.random.default_rng(42); rng.normal(0, 1, 5)
- Arrays hold one numeric type and one shape;
.shape,.ndim,.reshape,.T. axis=0runs down columns,axis=1across rows; scalars and smaller arrays broadcast.*is element-wise, not matrix multiplication. NumPy'sstddefaults to population (ddof 0), pandas to sample (ddof 1).
Check yourself 2 questions
Daily returns from a NumPy close array without a loop?
Show answer
np.diff(c) / c[:-1] * 100.How do you count days above the average?
Show answer
(c > c.mean()).sum().
Takeaway NumPy applies maths to whole arrays at once: rebasing, returns and counts with no loops.
pandas Series#
| Job | Methods |
|---|---|
| Peek | head tail describe value_counts |
| Running | cumsum cumprod cummax rolling(n).mean() expanding() |
| Change | pct_change diff shift clip |
| Filter and rank | s[s > x] between nlargest nsmallest where |
| Transform | apply map round astype fillna sort_values |
- A Series is values plus an index (dates, symbols) that travels with every operation.
s.pct_change() * 100is the go-to for returns; its first value is NaN.iloc[0:3]excludes the stop;loc["Tue":"Thu"]includes it.applyis a Python loop in disguise: prefer built-in methods.
Check yourself 2 questions
What does shift(1) do?
Show answer
Moves values one step later, so today's row sees yesterday's value.
Which method gives a 20-period moving average?
Show answer
rolling(20).mean().
Takeaway A Series is values plus an index that travels with them; rolling, pct_change and shift do most time-series work.
DataFrames: select, filter, add, combine#
| Task | Syntax |
|---|---|
| One / several columns | df["Close"], df[["Open", "Close"]] |
| By label / position | df.loc["2026-06-24", "Close"], df.iloc[0:2, 0:4] |
| Filter | df[(df["Chg%"] > 2) & (df["Range"] > 40)] (use & and |, parenthesise each) |
| New column | df["Chg%"] = (df["Close"] - df["Open"]) / df["Open"] * 100 |
| Conditional column | np.where(df["Close"] >= df["Open"], "up", "down") |
| Sort, stack, join | sort_values("Range", ascending=False), pd.concat([a, b]), a.merge(b, on="Symbol") |
| Inspect | shape info dtypes describe head tail |
Gotcha: yf.download() returns two-level columns (field, ticker), so df["Close"] is a table; use df["Close"]["AAPL"] or droplevel(1, axis=1). yf.Ticker(t).history() returns flat columns.
Check yourself 2 questions
loc versus iloc?
Show answer
loc selects by label; iloc by position.
Why parenthesise each condition in a pandas filter?
Show answer
Because & and | bind tighter than comparisons.
Takeaway Select with [] and loc or iloc, filter with & and | in parentheses, add columns by assignment.
Loading market data#
import yfinance as yf, pandas as pd # .NS for NSE on Yahoo df = yf.Ticker("RELIANCE.NS").history(period="6mo") df = df.round(2).dropna() # today's bar may be empty until close df.to_csv("reliance.csv") df = pd.read_csv("reliance.csv", index_col="Date", parse_dates=True) df.describe()
Fetch once, save, then work offline. Without index_col you get a 0, 1, 2 counter; without parse_dates=True dates stay text and time maths fails.
Check yourself 2 questions
Yahoo suffix for NSE symbols?
Show answer
.NS.
Why dropna() right after download?
Show answer
Today's bar may be empty until the close.
Takeaway Fetch with yfinance (.NS for NSE), save to CSV, reload with a parsed date index.
Cleaning checklist#
| Problem | Fix |
|---|---|
| Missing values at the end | dropna() |
| Gap in the middle | ffill() carries the last value |
| Numbers stored as text | .astype(float) |
| Duplicate rows | drop_duplicates() |
| Impossible values | Spot with describe(), then investigate |
Five-line check on every dataset: shape, isna().sum(), dtypes, duplicated().sum(), describe(). Never fillna(0) a price, and test missing values with isna() because NaN == NaN is False.
Check yourself 2 questions
A gap in the middle of a price series: common fix?
Show answer
ffill()to carry the last value forward.Numbers stored as text: fix?
Show answer
.astype(float).
Takeaway Check shape, missing values, dtypes, duplicates and describe() on every dataset before any maths.
Time series: slice, resample, roll, shift#
close = df["Close"].sort_index() # time order first! close.loc["2026-05"] # a whole month close.loc["2026-06-01":"2026-06-10"] weekly = close.resample("W").last() # daily → weekly ohlc = close.resample("ME").agg(["first", "max", "min", "last"]) sma20 = close.rolling(20).mean() # first 19 values NaN ret = (close / close.shift(1) - 1) * 100
Frequency codes: "W" week, "ME" month-end, "QE" quarter-end, "B" business day, "h" hour, "min" minute. First, max, min, last build open, high, low, close.
Check yourself 2 questions
Daily closes to weekly closes?
Show answer
close.resample("W").last().What must you do before rolling or resampling?
Show answer
Sort the index by date.
Takeaway Sort by date first, then slice by label, resample to new frequencies, roll windows and shift to avoid look-ahead.
Grouping: split, apply, combine#
ret = df["Close"].pct_change().dropna() * 100 ret.groupby(ret.index.day_name()).mean() # by weekday monthly = ret.groupby(ret.index.to_period("M")) monthly.agg(["mean", "std", "min", "max"]) # long format basket.groupby("Stock")["Return"].agg(["mean", "std"])
- Standard deviation of returns is a quick volatility ranking.
- Groups sort alphabetically (Friday before Monday):
reindexto your order. - Six months is far too little data to claim a weekday effect; learn the mechanics, not the "pattern".
Check yourself 2 questions
Average return by weekday?
Show answer
ret.groupby(ret.index.day_name()).mean().What does standard deviation of returns measure?
Show answer
Volatility: how much returns swing.
Takeaway groupby splits the data, applies a summary and combines the results, for example returns by weekday.
Charts that tell the truth#
| Chart | Use for |
|---|---|
| Line | Price or equity over time |
| Histogram of returns | Risk and fat tails |
| Rebased lines (start = 100) | Comparing growth of different stocks |
| Bar | Comparing categories |
| Subplots | Price beside its return distribution |
fig, ax = plt.subplots(figsize=(8, 4)) rebased = close / close.iloc[0] * 100 ax.plot(close.index, rebased, label="RELIANCE") ax.set_title("Rebased to 100"); ax.legend() plt.savefig("chart.png", dpi=110, bbox_inches="tight")
Check yourself 2 questions
How do you compare growth of stocks with different prices?
Show answer
Rebase each to 100 at the start.
Which chart shows fat tails?
Show answer
A histogram of returns.
Takeaway Line for price or equity, histogram for return risk, rebased lines to compare growth.
05Python for the markets: symbols, timings, OHLCV, APIs and returns
OpenAlgo Open Varsity · Python for Traders · chapters 33–40 (market landscape, symbols and lot sizes, money, timings, holidays, OHLCV, HTTP, quotes, WebSockets, returns and signals)
The market landscape#
| Layer | India | US |
|---|---|---|
| Regulator | SEBI | SEC |
| Exchanges | NSE, BSE (1875) | NYSE, Nasdaq |
| Holding shares | Demat at NSDL / CDSL | Broker custody |
| Headline indices | Nifty 50, Sensex | S&P 500, Nasdaq Composite, Dow |
| Segments | Cash (shares) and derivatives (futures and options) | |
Data flows exchange → vendor → your tool. Delayed data is for study; live data is for trading. Index symbols such as ^NSEI or ^GSPC are not tradeable.
Check yourself 2 questions
What's delayed data suitable for?
Show answer
Study and backtests, not live orders.
Who holds Indian shares?
Show answer
Depositories (NSDL and CDSL), in demat.
Takeaway SEBI, NSE and BSE, demat at NSDL or CDSL; data flows exchange to vendor to your tool.
One stock, many symbols#
| System | Format | Example |
|---|---|---|
| NSE / BSE | Plain symbol | RELIANCE |
| Yahoo, NSE | .NS suffix | RELIANCE.NS |
| Yahoo, BSE | .BO suffix | RELIANCE.BO |
| Yahoo, US | No suffix | AAPL |
| Yahoo, index | ^ prefix | ^NSEI |
| Global ID | ISIN | INE002A01018 |
SUFFIX = {"NSE": ".NS", "BSE": ".BO", "US": ""} def to_yahoo(sym, exch): # KeyError beats a silent wrong ticker return sym + SUFFIX[exch]
A wrong suffix returns an empty result, not an error. Keep one mapper so strategy code uses plain symbols.
Check yourself 2 questions
Yahoo symbol for Reliance on BSE?
Show answer
RELIANCE.BO.
What's the global identifier for a security?
Show answer
Its ISIN.
Takeaway The same stock has different symbols per system: RELIANCE, RELIANCE.NS, RELIANCE.BO, and an ISIN.
Lot sizes and contract value#
Futures and options trade in fixed lots, and exchanges revise lot sizes periodically under SEBI rules. Fetch current lot sizes from the exchange or broker instead of hard-coding them.
Check yourself 2 questions
Reliance at ₹1,313.60 × 500: contract value?
Show answer
About ₹6.57 lakh.
Why not hard-code lot sizes?
Show answer
Exchanges revise them periodically.
Takeaway Contract value = price × lot size; fetch current lot sizes rather than hard-coding them.
Money formatting and market hours#
| Session | Local | In IST |
|---|---|---|
| NSE pre-open | 09:00–09:15 | 09:00–09:15 |
| NSE cash | 09:15–15:30, weekdays | 09:15–15:30 |
| US cash | 09:30–16:00 ET | 19:00–01:30 next day in US summer time; an hour later in winter |
from zoneinfo import ZoneInfo NY = ZoneInfo("America/New_York") ny = datetime(2026, 6, 25, 9, 30, tzinfo=NY) ny.astimezone(ZoneInfo("Asia/Kolkata")) # 19:00 IST (EDT)
- Lakh = 1,00,000; crore = 1,00,00,000 = 100 lakh = 10 million. Indian grouping is 2-2-3: 18016237 → 1,80,16,237 (Python's
:,gives Western grouping, so write a small helper). - IST is UTC+5:30, a half-hour offset. Never hard-code offsets across daylight saving; attach a zone.
- A weekend check misses exchange holidays (Republic Day, Holi, Diwali…); load the exchange's annual list. Diwali Muhurat is a one-hour exception.
Check yourself 2 questions
When does the US cash session open in IST during US summer time?
Show answer
7:00 pm IST.
Which module handles time zones?
Show answer
zoneinfo.
Takeaway Convert time zones with zoneinfo; US cash hours fall in the Indian evening and night.
Working with OHLCV#
df = pd.read_csv("reliance.csv", index_col="Date", parse_dates=True) bar = df.iloc[-1] # latest bar df["Range"] = df["High"] - df["Low"] # volatility gauge df["Body"] = df["Close"] - df["Open"] # net move within the day df["Ret%"] = df["Close"].pct_change() * 100 (df["Close"] >= df["Open"]).sum() # up days df["Range"].idxmax() # widest day
- One bar: O 1305.7, H 1322.0, L 1297.5, C 1313.6 → range 24.5, body +7.9.
- Body sign compares close with this bar's open; return compares with the previous close. They can disagree.
- In the course's 124-day sample: 60 up days, 64 down, close to a coin flip.
Check yourself 2 questions
How do you compute a day's range?
Show answer
High − Low.
How do you flag green candles?
Show answer
df["Close"] >= df["Open"].
Takeaway Range, body and returns come straight from OHLCV columns.
Fetching data over HTTP#
import os, requests url = os.getenv("OPENALGO_HOST") + "/api/v1/quotes" # never hard-code keys body = {"apikey": os.getenv("OPENALGO_API_KEY"), "symbol": "RELIANCE", "exchange": "NSE"} try: # always a timeout r = requests.post(url, json=body, timeout=10) r.raise_for_status() # 4xx / 5xx → error q = r.json()["data"] print(q["ltp"], q.get("bid")) except requests.RequestException as e: print("network problem:", e)
| Status | Meaning |
|---|---|
| 200 | OK |
| 404 | Endpoint not found |
| 500 | Server error |
The universal pattern: request, check status, parse JSON. GET fetches; POST sends a JSON body. Keep keys in environment variables, never in code or GitHub. An SDK such as OpenAlgo's hides the boilerplate and can return history as a DataFrame.
Check yourself 2 questions
Where should API keys live?
Show answer
In environment variables, never in code.
Why pass a timeout to requests?
Show answer
So a hung server can't freeze your program.
Takeaway Keys in environment variables, always a timeout, raise_for_status for errors.
Quotes: delayed vs live, polling vs streaming#
| Field | Meaning |
|---|---|
ltp | Last traded price |
prev_close | Yesterday's close; change = ltp − prev_close |
open high low | Today so far |
bid ask | Top of the book; spread = ask − bid |
volume | Shares traded today |
- yfinance is free but delayed about 15 minutes: fine for study and backtests, never for placing orders. Broker-fed APIs are live.
- The gap between delayed and live widens when price moves fast.
- Sandboxes may return zeros for fields other than the last price; that is expected, not a bug.
Check yourself 2 questions
How is change computed in a quote?
Show answer
ltp − prev_close.
Can you place orders off yfinance quotes?
Show answer
No; they're delayed about 15 minutes.
Takeaway yfinance is about 15 minutes delayed: fine for study, never for orders; broker APIs are live.
WebSockets: polling pulls, streaming pushes#
| Polling (HTTP) | WebSocket | |
|---|---|---|
| Pattern | Ask, reply, repeat | Subscribe once, server pushes ticks |
| Connection | New per request | One long-lived, two-way |
| Latency | As often as you ask | Near-instant per tick |
| Best for | Occasional checks, history | Live dashboards, tick-level reactions |
You write a callback that receives each tick; the SDK handles the handshake, drops and reconnects. Beginners rarely need streaming: polling is simpler for checking prices or studying history, and hand-written socket code is error-prone.
Check yourself 2 questions
Which suits a live tick-level dashboard?
Show answer
A WebSocket.
What do you write to handle streamed ticks?
Show answer
A callback that receives each tick.
Takeaway Polling asks repeatedly; a WebSocket subscribes once and the server pushes ticks to your callback.
Prices → returns → signal → scorecard#
close = df["Close"] ret = close.pct_change() growth = (1 + ret).cumprod() # growth of ₹1 total = (growth.iloc[-1] - 1) * 100 fast, slow = close.rolling(10).mean(), close.rolling(30).mean() position = (fast > slow).astype(int) # 1 = in the market trades = position.diff() # +1 buy, −1 sell strat = position.shift(1) * ret # act on the NEXT bar win_rate = (ret > 0).sum() / ret.notna().sum() drawdown = (growth / growth.cummax() - 1) * 100 max_dd = drawdown.min()
- In the course's six-month RELIANCE sample: buy-and-hold −15.31%, best day +3.36%, worst −4.60%, 44.7% up days, max drawdown −20.58%. Buy-and-hold can lose.
- The course's scorecard measures the stock's own returns; to judge a strategy, score
strat. Theshift(1)is our addition: a signal from today's close can only be acted on tomorrow, otherwise the test peeks into the future. - Six months, no costs and one stock prove nothing: distrust attractive results. The Algo Trading and Quant sheets go further.
Check yourself 2 questions
Growth of ₹1 from returns?
Show answer
(1 + ret).cumprod().How do you find buy and sell points from a 0/1 position?
Show answer
position.diff(): +1 buy, −1 sell.
Takeaway Returns from pct_change, growth from cumprod, position from a crossover, trades from diff.
06Checklists and quick reference
Keep these next to your editor.
New project checklist#
- New folder,
python -m venv .venv, activate, install,pip freeze > requirements.txt. - API keys in environment variables, never in code.
- Save downloaded data to CSV; work offline from the file.
- Run the five-line data check before any maths.
- Sort time series by date before rolling, shift or resample.
Check yourself 2 questions
Where do API keys go?
Show answer
Environment variables.
What must you do to time series before rolling, shift or resample?
Show answer
Sort by date.
Takeaway New folder and venv, keys in environment variables, data saved to CSV, the five-line check, and sort before rolling.
Bug-hunting checklist#
- Read the traceback from the bottom.
- Check
type()of anything that came from input, files or the web. =vs==;&and parentheses in pandas filters.- Slice ends: positions exclude, labels include.
- NaNs at the start of rolling windows and returns.
- Did a string method's result get assigned?
Check yourself 2 questions
Positional slices versus label slices: which includes the end?
Show answer
Label slices include it; positional slices exclude it.
Where do NaNs appear after rolling or returns?
Show answer
At the start of the series.
Takeaway Read tracebacks bottom up, check types from input, watch = versus ==, slice ends, NaNs and unassigned string results.
One-line idioms#
Check yourself 2 questions
Drawdown in one line?
Show answer
growth / growth.cummax() - 1.Weekly last close?
Show answer
close.resample("W").last().
Takeaway pct_change for returns, cumprod for growth, growth ÷ cummax − 1 for drawdown, rolling mean for SMA.
About this sheet#
This sheet condenses the free course Python for Traders from OpenAlgo Open Varsity (40 chapters, 5 modules) into reference cards in our own words. Code snippets are short examples in the course's spirit, not copies. Each section links back to its chapters. Educational, not investment advice.