CSCheatsheets
Open Varsity · Beginner

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.

7sections
50cards
2diagrams
0%known

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.

How to use this sheet#

  1. New to code: getting started and core programming, typing every example yourself.
  2. Know Python, new to data: jump to NumPy and pandas.
  3. Ready to touch markets: symbols, timings, OHLCV and returns, then the Algo Trading sheet.
  4. All code on this sheet is our own short example in the course's spirit, not copied from it.
Educational, not investment advice. Condensed in our own words from OpenAlgo Open Varsity: Python for Traders.

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
  1. What comes right after fetching data in the pipeline?

    Show answer

    Save it to CSV, then work offline from the file.

  2. 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
  1. Why is pure Python slow at big loops?

    Show answer

    It handles one value per step; vectorised libraries hand the loop to compiled code.

  2. 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#

TaskCommand
Check Python (any 3.x)python --version (or python3 on some Mac/Linux)
Check pippip --version (or python -m pip)
Install a library from PyPIpip install pandas
Run a scriptpython 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
  1. Command to install pandas?

    Show answer

    pip install pandas.

  2. 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 forReusable, automated runsExploring and learning
RunsTop to bottomCell by cell
OutputTerminal; 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
  1. What does a notebook show without print()?

    Show answer

    A cell's last expression, displayed inline.

  2. 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_price beats x = 50 * 1300.
Check yourself 2 questions
  1. What's the difference between = and ==?

    Show answer

    = assigns a value; == tests equality.

  2. 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#

TypeExampleUse
int50Shares, lots (no size limit)
float1313.60Prices, returns
str"RELIANCE"Symbols, labels
boolTrueFlags
  • 100 / 4 is 25.0, a float. 0.1 + 0.2 is 0.30000000000000004: floats are binary approximations, so round for display and use Decimal for exact accounting.
  • Keyboard, file and web input arrives as text: "50" * 3 is "505050"; convert with int() or float() first.
  • Falsy: 0, "", empty containers, None; almost everything else is truthy.
Check yourself 2 questions
  1. What does 0.1 + 0.2 give in Python, and why?

    Show answer

    0.30000000000000004, because floats are binary approximations.

  2. 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#

OperatorMeaningExample
//Floor division100000 // 65680 → 1 whole lot
%Remainder100000 % 65680 → 34320 cash left
**Power(1.01 ** 5 - 1) * 100 ≈ 5.10% (1% a day for 5 days)
== != > <Comparisons → True/Falseprice > sma
and or notCombine conditionssupport < price < resistance
pct change = (new − old) ÷ old × 100(1313.60 − 1300) ÷ 1300 × 100 ≈ +1.05%

// truncates (1.52 lots → 1), and * binds before +: parenthesise anything not obvious.

Check yourself 2 questions
  1. ₹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.

  2. 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#

SpecOutputUse
{v:,.2f}65,680.00Money with commas
{v:+.2f}+13.60Signed change
{r:.2%}1.05%Returns (multiplies by 100)
{s:<10} / {v:>10.2f}aligned columnsLabels left, numbers right
{n:05d}00042Zero-padded IDs
{d:%d %b %Y}25 Jun 2026Dates
{x=}x=1313.6Quick debugging

input() always returns a string: qty = int(input("Shares? ")). Forgetting the f prefix prints the braces literally.

Check yourself 2 questions
  1. Which format spec prints 65,680.00?

    Show answer

    {v:,.2f}.

  2. 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.
  • join is called on the separator, not the list.
Check yourself 2 questions
  1. How do you split 'RELIANCE,TCS,INFY' into a list?

    Show answer

    .split(",").

  2. 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?#

ContainerSyntaxAccess byMutableTrading use
List[101.2, 103.5]PositionYesPrice series, watchlist, trades
Tuple(o, h, l, c)PositionNoA fixed record: an OHLC bar, multiple return values
Dict{"ltp": 1313.6}Key (name)YesA quote, API JSON, symbol → data lookup
Set{"TCS", "INFY"}MembershipYesUnique 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
  1. Which container suits an OHLC bar that shouldn't change?

    Show answer

    A tuple.

  2. 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() gives None; prefer sorted() 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
  1. How do you get the last two closes?

    Show answer

    closes[-2:].

  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
  1. divmod(250, 75) returns what?

    Show answer

    (3, 25): three lots and 25 shares spare.

  2. 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
  1. How do you read a key that may be missing without a KeyError?

    Show answer

    quote.get("bid", "n/a").

  2. 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
  1. Which operator gives symbols in both of two sets?

    Show answer

    & (intersection).

  2. 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
  1. Why check price <= 0 first?

    Show answer

    A guard clause rejects bad data before any logic runs.

  2. 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
  1. What must every while loop do?

    Show answer

    Move towards its stopping condition.

  2. What does continue do?

    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
  1. Write a list of closes above 100.

    Show answer

    [c for c in closes if c > 100].

  2. 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
  1. What does min(turnover * rate, cap) implement?

    Show answer

    Brokerage at a rate, capped at ₹20 per order.

  2. 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#

StyleSyntaxCall as
Whole moduleimport mathmath.sqrt(2)
Specific namesfrom statistics import mean, stdevmean(x)
Aliasimport pandas as pdpd.read_csv(...)
Wildcardfrom m import *Avoid: name clashes, hidden origins
  • Any .py file is a module: put pnl() and pct_change() in tradetools.py and import tradetools (no .py).
  • Python looks in your script's folder first, so a local pandas.py would shadow the real library.
  • Whole lots: math.floor(76.12) → 76, math.ceil(76.12) → 77.
Check yourself 2 questions
  1. Why avoid from m import *?

    Show answer

    Name clashes and hidden origins.

  2. 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#

ModuleUse
datetimeDates, times, date maths, formatting
randomSimulations; random.seed(42) makes runs repeatable
jsonAPI data in and out
math, statisticsRoots, rounding, mean, median, stdev
csv, pathlibSimple 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
  1. How do you make random simulations repeatable?

    Show answer

    random.seed(42) (any fixed seed).

  2. 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 import proves the install; a missing one raises ModuleNotFoundError.
  • "pip not recognised": use python -m pip.
Check yourself 2 questions
  1. How do you record exact package versions?

    Show answer

    pip freeze > requirements.txt.

  2. 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#

ErrorCauseTrading exampleFix
SyntaxErrorMissing colon or bracketAn if without :Fix the layout; nothing runs until then
NameErrorUndefined or misspelt nameltp vs LTPCheck spelling and definition
TypeErrorWrong type for the operationText price + numberConvert types
ValueErrorRight type, bad valueint("fifty"); price of 0 in sizingValidate; raise your own clear error
IndexErrorPosition doesn't existcloses[10] on 7 closesCheck the length
KeyErrorDict key missingQuote without "bid"q.get("bid")
ZeroDivisionErrorDivide by zeroAverage of an empty listGuard or return a fallback
ModuleNotFoundErrorLibrary not installedimport yfinancepip install in the active venv
Check yourself 2 questions
  1. Adding a text price to a number raises which error?

    Show answer

    TypeError.

  2. 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
  1. Why not use a bare except:?

    Show answer

    It hides every error, including bugs you need to see.

  2. 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#

ModeDoes
"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
  1. Which mode suits a trading journal?

    Show answer

    'a' (append).

  2. 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#

JSONPython
object {}dict
array []list
string, numberstr, int / float
true / false / nullTrue / 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
  1. What does JSON null become in Python?

    Show answer

    None.

  2. 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
CodeMeaningCodeMeaning
%Y %m %dYear, month, day%H %M24-hour, minute
%I %p12-hour, AM/PM%A %bWeekday, short month

weekday() is Mon 0 to Sun 6 and knows nothing about exchange holidays: keep a holiday list.

Check yourself 2 questions
  1. Which function turns '2026-06-25 09:15' into a datetime?

    Show answer

    datetime.strptime with a format string.

  2. 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#

  1. Read the error: the last line names the problem.
  2. Ask Python: type(x) (what is it?), dir(x) (what can it do?), help(x) (how?).
  3. Search the exact message, in quotes.
  4. Shrink it to the smallest snippet that still fails; that often reveals the bug.
  5. 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
  1. Which line of a traceback names the problem?

    Show answer

    The last line.

  2. 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=0 runs down columns, axis=1 across rows; scalars and smaller arrays broadcast.
  • * is element-wise, not matrix multiplication. NumPy's std defaults to population (ddof 0), pandas to sample (ddof 1).
Check yourself 2 questions
  1. Daily returns from a NumPy close array without a loop?

    Show answer

    np.diff(c) / c[:-1] * 100.

  2. 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#

JobMethods
Peekhead tail describe value_counts
Runningcumsum cumprod cummax rolling(n).mean() expanding()
Changepct_change diff shift clip
Filter and ranks[s > x] between nlargest nsmallest where
Transformapply map round astype fillna sort_values
  • A Series is values plus an index (dates, symbols) that travels with every operation.
  • s.pct_change() * 100 is the go-to for returns; its first value is NaN.
  • iloc[0:3] excludes the stop; loc["Tue":"Thu"] includes it.
  • apply is a Python loop in disguise: prefer built-in methods.
Check yourself 2 questions
  1. What does shift(1) do?

    Show answer

    Moves values one step later, so today's row sees yesterday's value.

  2. 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#

TaskSyntax
One / several columnsdf["Close"], df[["Open", "Close"]]
By label / positiondf.loc["2026-06-24", "Close"], df.iloc[0:2, 0:4]
Filterdf[(df["Chg%"] > 2) & (df["Range"] > 40)] (use & and |, parenthesise each)
New columndf["Chg%"] = (df["Close"] - df["Open"]) / df["Open"] * 100
Conditional columnnp.where(df["Close"] >= df["Open"], "up", "down")
Sort, stack, joinsort_values("Range", ascending=False), pd.concat([a, b]), a.merge(b, on="Symbol")
Inspectshape 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
  1. loc versus iloc?

    Show answer

    loc selects by label; iloc by position.

  2. 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
  1. Yahoo suffix for NSE symbols?

    Show answer

    .NS.

  2. 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#

ProblemFix
Missing values at the enddropna()
Gap in the middleffill() carries the last value
Numbers stored as text.astype(float)
Duplicate rowsdrop_duplicates()
Impossible valuesSpot 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
  1. A gap in the middle of a price series: common fix?

    Show answer

    ffill() to carry the last value forward.

  2. 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
  1. Daily closes to weekly closes?

    Show answer

    close.resample("W").last().

  2. 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): reindex to your order.
  • Six months is far too little data to claim a weekday effect; learn the mechanics, not the "pattern".
Check yourself 2 questions
  1. Average return by weekday?

    Show answer

    ret.groupby(ret.index.day_name()).mean().

  2. 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#

ChartUse for
LinePrice or equity over time
Histogram of returnsRisk and fat tails
Rebased lines (start = 100)Comparing growth of different stocks
BarComparing categories
SubplotsPrice 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
  1. How do you compare growth of stocks with different prices?

    Show answer

    Rebase each to 100 at the start.

  2. 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#

LayerIndiaUS
RegulatorSEBISEC
ExchangesNSE, BSE (1875)NYSE, Nasdaq
Holding sharesDemat at NSDL / CDSLBroker custody
Headline indicesNifty 50, SensexS&P 500, Nasdaq Composite, Dow
SegmentsCash (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
  1. What's delayed data suitable for?

    Show answer

    Study and backtests, not live orders.

  2. 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#

SystemFormatExample
NSE / BSEPlain symbolRELIANCE
Yahoo, NSE.NS suffixRELIANCE.NS
Yahoo, BSE.BO suffixRELIANCE.BO
Yahoo, USNo suffixAAPL
Yahoo, index^ prefix^NSEI
Global IDISININE002A01018
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
  1. Yahoo symbol for Reliance on BSE?

    Show answer

    RELIANCE.BO.

  2. 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#

contract value = price × lot sizeRELIANCE: ₹1,313.60 × 500 ≈ ₹6.57 lakhTCS: ₹2,109 × 175 ≈ ₹3.69 lakh

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
  1. Reliance at ₹1,313.60 × 500: contract value?

    Show answer

    About ₹6.57 lakh.

  2. 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#

SessionLocalIn IST
NSE pre-open09:00–09:1509:00–09:15
NSE cash09:15–15:30, weekdays09:15–15:30
US cash09:30–16:00 ET19: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
  1. When does the US cash session open in IST during US summer time?

    Show answer

    7:00 pm IST.

  2. 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
  1. How do you compute a day's range?

    Show answer

    High − Low.

  2. 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)
StatusMeaning
200OK
404Endpoint not found
500Server 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
  1. Where should API keys live?

    Show answer

    In environment variables, never in code.

  2. 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#

FieldMeaning
ltpLast traded price
prev_closeYesterday's close; change = ltp − prev_close
open high lowToday so far
bid askTop of the book; spread = ask − bid
volumeShares 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
  1. How is change computed in a quote?

    Show answer

    ltp − prev_close.

  2. 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
PatternAsk, reply, repeatSubscribe once, server pushes ticks
ConnectionNew per requestOne long-lived, two-way
LatencyAs often as you askNear-instant per tick
Best forOccasional checks, historyLive 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
  1. Which suits a live tick-level dashboard?

    Show answer

    A WebSocket.

  2. 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. The shift(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
  1. Growth of ₹1 from returns?

    Show answer

    (1 + ret).cumprod().

  2. 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
  1. Where do API keys go?

    Show answer

    Environment variables.

  2. 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
  1. Positional slices versus label slices: which includes the end?

    Show answer

    Label slices include it; positional slices exclude it.

  2. 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#

pct change = (new − old) / old * 100returns = close.pct_change()growth = (1 + returns).cumprod()drawdown = growth / growth.cummax() − 1sma = close.rolling(n).mean()weekly = close.resample("W").last()contract value = price × lot size
Check yourself 2 questions
  1. Drawdown in one line?

    Show answer

    growth / growth.cummax() - 1.

  2. 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.

No cards match. Try fewer or different words, or press Esc to clear.