Python for Data Engineers
The Python a data engineer uses every day, from functional patterns and robust error handling to NumPy and pandas, ending with a full stock market analysis project.
1. Python Refresher: What Data Engineers Must Know Cold
Python is the glue of data engineering: Spark jobs, Airflow DAGs, API extractors, tests and automation. Most production bugs come from a few language rules people half-remember, so start there.
Mutability and references
Variables are names pointing at objects. Lists, dicts and sets are mutable, so two names can point at, and change, the same object:
batch = ["order_1", "order_2"]
backup = batch # same object, not a copy
backup.append("order_3")
print(batch) # changed too
safe = list(batch) # a real (shallow) copy
safe.append("order_4")
print(batch, safe, sep="\n")['order_1', 'order_2', 'order_3'] ['order_1', 'order_2', 'order_3'] ['order_1', 'order_2', 'order_3', 'order_4']
The mutable default argument trap
def add_tag(tag, tags=[]): # the list is created ONCE, when the function is defined
tags.append(tag)
return tags
print(add_tag("pii"), add_tag("finance")) # both calls share one list
def add_tag_fixed(tag, tags=None):
tags = [] if tags is None else tags
tags.append(tag)
return tags
print(add_tag_fixed("pii"), add_tag_fixed("finance"))['pii', 'finance'] ['pii', 'finance'] ['pii'] ['finance']
Comprehensions, dicts and sets
rows = [{"id": 1, "city": "Pune", "amt": 120}, {"id": 2, "city": "Delhi", "amt": 80},
{"id": 3, "city": "Pune", "amt": 50}]
pune_ids = [r["id"] for r in rows if r["city"] == "Pune"]
amount_by_id = {r["id"]: r["amt"] for r in rows}
cities = {r["city"] for r in rows}
totals = {}
for r in rows:
totals[r["city"]] = totals.get(r["city"], 0) + r["amt"]
print(pune_ids, amount_by_id, sorted(cities), totals, sep="\n")
print("in both:", {"Pune", "Delhi"} & {"Pune", "Mumbai"}, "| only left:", {"Pune", "Delhi"} - {"Pune", "Mumbai"})[1, 3]
{1: 120, 2: 80, 3: 50}
['Delhi', 'Pune']
{'Pune': 170, 'Delhi': 80}
in both: {'Pune'} | only left: {'Delhi'}
Identity vs equality, truthiness, unpacking
a, b = [1, 2], [1, 2]
print(a == b, a is b) # equal values, different objects; use "is" only for None
first, *middle, last = [10, 20, 30, 40]
print(first, middle, last)
for name, value in [("rows", 0), ("files", 3)]:
print(f"{name:>6}: {value or 'none'}") # 0, "", [], None and {} are all falsyTrue False 10 [20, 30] 40 rows: none files: 3
"Names point at objects; lists and dicts are mutable, so I copy when I need independence and never use a mutable default argument. I use comprehensions for clear transformations, sets for membership and set algebra, is only for None, and I remember that zero and empty containers are falsy."
2. Functional Programming
Functional style treats functions as values and avoids hidden state. In data engineering it gives you reusable transformations, lazy pipelines that process data larger than memory, and decorators that add retries, timing or logging without touching business logic. It is also how Spark thinks: map, filter, reduce over distributed data.
map, filter, reduce and lambda
from functools import reduce
amounts = ["120.50", "80", "bad", "45.25"]
def to_float(s):
try:
return float(s)
except ValueError:
return None
clean = list(filter(lambda x: x is not None, map(to_float, amounts)))
total = reduce(lambda acc, x: acc + x, clean, 0.0)
print(clean, total)[120.5, 80.0, 45.25] 245.75
In everyday code, comprehensions are usually clearer than map/filter with lambdas; know both, because interviewers and Spark use the functional vocabulary.
Closures and function factories
def make_validator(min_value, max_value):
def validate(x): # remembers min_value and max_value
return min_value <= x <= max_value
return validate
valid_amount = make_validator(0, 10_000)
valid_age = make_validator(18, 120)
print(valid_amount(250), valid_amount(-5), valid_age(17))True False False
Decorators: retries with exponential backoff
External APIs and databases fail transiently. A decorator wraps any function with retry logic, so extraction code stays clean:
import functools, time
def retry(times=3, base_delay=0.01, exceptions=(ConnectionError,)):
def decorator(func):
@functools.wraps(func) # keep the original name and docstring
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions as e:
if attempt == times:
raise
wait = base_delay * 2 ** (attempt - 1)
print(f"attempt {attempt} failed ({e}); retrying in {wait:.2f}s")
time.sleep(wait)
return wrapper
return decorator
calls = {"n": 0}
@retry(times=4)
def fetch_page(page):
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("timeout")
return {"page": page, "rows": 500}
print(fetch_page(7), "| function name:", fetch_page.__name__)attempt 1 failed (timeout); retrying in 0.01s
attempt 2 failed (timeout); retrying in 0.02s
{'page': 7, 'rows': 500} | function name: fetch_page
Generators: lazy pipelines for data bigger than memory
A generator yields one item at a time, so a chain of generators processes a 50 GB file with constant memory. Each stage pulls from the previous one only when needed:
import io
raw = io.StringIO("id,amount\n1,120\n2,abc\n3,80\n4,300\n") # stands in for a huge file
def read_lines(f):
next(f) # skip header
for line in f:
yield line.rstrip("\n").split(",")
def parse(rows):
for id_, amount in rows:
try:
yield int(id_), float(amount)
except ValueError:
print(f" skipped bad row id={id_}")
def only_large(rows, threshold):
return (r for r in rows if r[1] >= threshold) # generator expression
pipeline = only_large(parse(read_lines(raw)), 100)
print(type(pipeline).__name__) # nothing has run yet
print(list(pipeline))generator skipped bad row id=2 [(1, 120.0), (4, 300.0)]
itertools and functools in data work
from itertools import groupby, islice, chain
from functools import lru_cache, partial
events = [("u1", "click"), ("u1", "buy"), ("u2", "click"), ("u2", "click"), ("u3", "buy")]
for user, grp in groupby(events, key=lambda e: e[0]): # input must be sorted by key
print(user, [action for _, action in grp])
def batches(iterable, size): # micro-batches for bulk API calls or inserts
it = iter(iterable)
while chunk := list(islice(it, size)):
yield chunk
print(list(batches(range(1, 8), 3)))
print(list(islice(chain("ab", "cd"), 3)))
@lru_cache(maxsize=1024)
def fx_rate(currency): # cache slow lookups
print(f" looking up {currency}")
return {"USD": 83.2, "EUR": 90.1}[currency]
print(fx_rate("USD"), fx_rate("USD"), fx_rate.cache_info().hits, "cache hit")
round2 = partial(round, ndigits=2)
print(round2(3.14159))u1 ['click', 'buy'] u2 ['click', 'click'] u3 ['buy'] [[1, 2, 3], [4, 5, 6], [7]] ['a', 'b', 'c'] looking up USD 83.2 83.2 1 cache hit 3.14
Python 3.12 adds itertools.batched(iterable, n), which does the same as the batches helper; the helper works on any Python 3.8+.
"I use functions as values: closures for configurable validators, decorators for cross-cutting concerns like retries with exponential backoff, and generators to build lazy pipelines that stream data larger than memory. itertools and functools give me grouping, batching, caching and partial application without extra libraries."
3. Modules, Packages, Errors and Exceptions
Structuring a pipeline project
sales_pipeline/
├── pyproject.toml # dependencies, versions, tool config
├── src/sales_pipeline/
│ ├── __init__.py
│ ├── config.py # settings from environment variables
│ ├── extract.py # one module per responsibility
│ ├── transform.py
│ ├── load.py
│ └── main.py # entry point: python -m sales_pipeline.main
└── tests/
├── test_transform.py
└── conftest.py # shared pytest fixtures
- A module is one
.pyfile; a package is a folder of modules with__init__.py - Code under
if __name__ == "__main__":runs only when the file is executed, not when it is imported, so modules stay importable by tests - Pin dependencies in a virtual environment (
venv,uvorpoetry) so every environment runs the same versions - Keep secrets out of code: read them from environment variables or a secrets manager
Exceptions: catch narrowly, fail loudly, clean up always
class DataQualityError(Exception):
"""Raised when a batch fails validation."""
def validate(batch):
bad = [r for r in batch if r.get("amount") is None or r["amount"] < 0]
if bad:
raise DataQualityError(f"{len(bad)} invalid rows, first: {bad[0]}")
return batch
def load(batch):
try:
rows = validate(batch)
except DataQualityError as e:
print("quarantined batch:", e)
return 0
else: # runs only if no exception
print("loaded", len(rows), "rows")
return len(rows)
finally: # always runs: close connections, release locks
print("cleanup done")
load([{"amount": 10}, {"amount": 5}])
load([{"amount": 10}, {"amount": -3}])loaded 2 rows
cleanup done
quarantined batch: 1 invalid rows, first: {'amount': -3}
cleanup done
Chaining causes and context managers
from contextlib import contextmanager
import json
def parse_config(text):
try:
return json.loads(text)
except json.JSONDecodeError as e:
raise ValueError("config file is not valid JSON") from e # keep the original cause
try:
parse_config("{bad json")
except ValueError as e:
print(type(e).__name__, "->", e, "| caused by:", type(e.__cause__).__name__)
@contextmanager
def stage(name):
print(f"[start] {name}")
try:
yield
print(f"[ok] {name}")
except Exception as e:
print(f"[failed] {name}: {e}")
raise
finally:
print(f"[end] {name}")
with stage("transform"):
total = sum([1, 2, 3])ValueError -> config file is not valid JSON | caused by: JSONDecodeError [start] transform [ok] transform [end] transform
Logging, not print
import logging, sys
log = logging.getLogger("sales_pipeline")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("extracted %d rows from %s", 1200, "orders")
log.debug("not shown at INFO level")
try:
1 / 0
except ZeroDivisionError:
log.error("transform failed", exc_info=False)INFO sales_pipeline: extracted 1200 rows from orders ERROR sales_pipeline: transform failed
"I structure pipelines as packages with one module per responsibility, an entry point guarded by __name__ == '__main__', pinned dependencies and secrets from the environment. I catch specific exceptions, define custom ones such as DataQualityError, chain causes with raise from, clean up in finally or a context manager, and use logging with levels instead of print."
4. Object-Oriented Programming for Pipelines
OOP organises code around objects that combine data and behaviour. Its four pillars are encapsulation (hide internal state), abstraction (expose a simple interface), inheritance (reuse and specialise) and polymorphism (one interface, many implementations). In data engineering, OOP shines when building a framework: many sources and sinks that all plug into the same pipeline.
A small ETL framework with abstract base classes
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
class Extractor(ABC):
@abstractmethod
def extract(self) -> list[dict]: ...
class Loader(ABC):
@abstractmethod
def load(self, rows: list[dict]) -> int: ...
class ListExtractor(Extractor): # stands in for an API or database extractor
def __init__(self, rows):
self._rows = rows # "private" by convention
def extract(self):
return list(self._rows)
class MemoryLoader(Loader):
def __init__(self):
self.table = []
def load(self, rows):
self.table.extend(rows)
return len(rows)
@dataclass
class Pipeline:
name: str
extractor: Extractor # composition: a pipeline HAS an extractor
loader: Loader
transforms: list = field(default_factory=list)
def run(self):
rows = self.extractor.extract()
for t in self.transforms:
rows = t(rows)
n = self.loader.load(rows)
return f"{self.name}: {n} rows loaded"
def drop_negative(rows):
return [r for r in rows if r["amount"] >= 0]
def add_tax(rows):
return [{**r, "amount_with_tax": round(r["amount"] * 1.18, 2)} for r in rows]
sink = MemoryLoader()
p = Pipeline("orders", ListExtractor([{"id": 1, "amount": 100}, {"id": 2, "amount": -5}]),
sink, [drop_negative, add_tax])
print(p.run())
print(sink.table)
try:
Extractor()
except TypeError as e:
print("cannot instantiate an abstract class:", str(e).split("with")[0].strip())orders: 1 rows loaded
[{'id': 1, 'amount': 100, 'amount_with_tax': 118.0}]
cannot instantiate an abstract class: Can't instantiate abstract class Extractor
Dataclasses, properties and dunder methods
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Money:
amount: float
currency: str = "INR"
def __add__(self, other): # operator overloading
if self.currency != other.currency:
raise ValueError("currency mismatch")
return Money(round(self.amount + other.amount, 2), self.currency)
class Batch:
def __init__(self, rows):
self._rows = rows
def __len__(self):
return len(self._rows)
def __iter__(self):
return iter(self._rows)
@property
def total(self): # computed attribute
return sum(r for r in self._rows)
print(Money(10.5) + Money(4.25), Money(5) < Money(7))
b = Batch([3, 4, 5])
print(len(b), list(b), b.total)Money(amount=14.75, currency='INR') True 3 [3, 4, 5] 12
| Pattern | When to use in data code |
|---|---|
| Composition over inheritance | A pipeline has an extractor and a loader; swap them without subclassing the pipeline |
| Abstract base class | Define the contract every source or sink must implement |
| Dataclass | Configuration objects, records, results: less boilerplate, immutable with frozen=True |
| Factory | Build the right extractor from config: {"s3": S3Extractor, "jdbc": JdbcExtractor}[cfg.type] |
| Strategy | Pluggable transformations or load modes (append, merge, overwrite) |
Deep dive: the Python guide covers this in more depth.
"I use OOP where it pays: a framework where every source implements an Extractor interface and every sink a Loader, composed into a Pipeline object, so adding a source means one new class. I prefer composition to deep inheritance, dataclasses for config and records, and abstract base classes to enforce the contract."
5. NumPy
NumPy stores numbers in contiguous, typed arrays and runs operations in compiled C loops. Replacing Python loops with array operations (vectorisation) is usually 10–100× faster, and pandas, scikit-learn and PySpark's pandas UDFs are all built on it.
import numpy as np, time
prices = np.random.default_rng(7).uniform(100, 200, 1_000_000)
start = time.perf_counter(); loop = [p * 1.18 for p in prices]; t_loop = time.perf_counter() - start
start = time.perf_counter(); vec = prices * 1.18; t_vec = time.perf_counter() - start
print(f"same result: {np.allclose(loop, vec)}, vectorised faster: {t_vec < t_loop}")same result: True, vectorised faster: True
Shapes, broadcasting and axes
import numpy as np
sales = np.array([[120, 80, 50], # rows = stores, columns = days
[200, 150, 90]])
print("shape:", sales.shape, "| total:", sales.sum())
print("per store (axis=1):", sales.sum(axis=1), "| per day (axis=0):", sales.sum(axis=0))
fx = np.array([1.0, 83.2])[:, None] # shape (2, 1): one rate per store
print("converted:\n", sales * fx) # broadcast across the 3 day columnsshape: (2, 3) | total: 690 per store (axis=1): [250 440] | per day (axis=0): [320 230 140] converted: [[ 120. 80. 50.] [16640. 12480. 7488.]]
Boolean masks and vectorised conditions
import numpy as np
amounts = np.array([120.0, -5.0, 300.0, np.nan, 45.0])
valid = ~np.isnan(amounts) & (amounts >= 0)
print("valid:", amounts[valid])
print("bucket:", np.where(amounts >= 100, "high", "low"))
print("mean ignoring NaN:", np.nanmean(amounts))
print("percentiles:", np.percentile(amounts[valid], [50, 90]))valid: [120. 300. 45.] bucket: ['high' 'low' 'high' 'low' 'low'] mean ignoring NaN: 115.0 percentiles: [120. 264.]
dtypes and memory
import numpy as np ids = np.arange(1_000_000) print(ids.dtype, ids.nbytes // 1024, "KB") small = ids.astype(np.int32) print(small.dtype, small.nbytes // 1024, "KB") print(np.array([1, 2, 3]) / 2, np.array([1, 2, 3]) // 2) # true vs floor division
int64 7812 KB int32 3906 KB [0.5 1. 1.5] [0 1 1]
"NumPy gives typed, contiguous arrays with operations in compiled loops, so I vectorise instead of looping. I rely on broadcasting to combine arrays of different shapes, boolean masks for filtering, np.where for conditional logic, nan-aware functions for missing values, and I choose dtypes deliberately to control memory."
6. pandas for Data Engineering
pandas is a single-machine DataFrame library: perfect for files up to a few gigabytes, API extracts, data validation, tests and prototyping logic later moved to Spark. Its API (and the pandas API on Spark) is something every data engineer is expected to know.
Load, inspect and clean
import io
import pandas as pd
csv = io.StringIO("""order_id,customer,order_date,amount,status
101, asha ,2026-03-01,120.5,DELIVERED
102,Ravi,2026-03-01,,DELIVERED
103,Ravi,2026-03-02,200,cancelled
103,Ravi,2026-03-02,200,cancelled
104,Meera,2026-03-04,50,DELIVERED
""")
df = pd.read_csv(csv, parse_dates=["order_date"])
print(df.dtypes.to_string(), "\n")
df = (df.drop_duplicates()
.assign(customer=lambda d: d["customer"].str.strip().str.title(),
status=lambda d: d["status"].str.upper(),
amount=lambda d: d["amount"].fillna(0)))
print(df.to_string(index=False))
print("\nnulls left:", int(df.isna().sum().sum()), "| rows:", len(df))order_id int64
customer object
order_date datetime64[ns]
amount float64
status object
order_id customer order_date amount status
101 Asha 2026-03-01 120.5 DELIVERED
102 Ravi 2026-03-01 0.0 DELIVERED
103 Ravi 2026-03-02 200.0 CANCELLED
104 Meera 2026-03-04 50.0 DELIVERED
nulls left: 0 | rows: 4
Group, aggregate and pivot
summary = (df.groupby("customer", as_index=False)
.agg(orders=("order_id", "nunique"), revenue=("amount", "sum"),
last_order=("order_date", "max")))
print(summary.to_string(index=False), "\n")
print(df.pivot_table(index="customer", columns="status", values="amount",
aggfunc="sum", fill_value=0).to_string())customer orders revenue last_order
Asha 1 120.5 2026-03-01
Meera 1 50.0 2026-03-04
Ravi 2 200.0 2026-03-02
status CANCELLED DELIVERED
customer
Asha 0.0 120.5
Meera 0.0 50.0
Ravi 200.0 0.0
Joins with validation
customers = pd.DataFrame({"customer": ["Asha", "Ravi", "Meera"], "city": ["Pune", "Delhi", "Pune"]})
merged = df.merge(customers, on="customer", how="left", validate="many_to_one", indicator=True)
print(merged[["order_id", "customer", "city", "_merge"]].to_string(index=False))
dup_dim = pd.concat([customers, customers.iloc[[0]]])
try:
df.merge(dup_dim, on="customer", validate="many_to_one")
except pd.errors.MergeError as e:
print("\ncaught:", str(e)[:60]) order_id customer city _merge
101 Asha Pune both
102 Ravi Delhi both
103 Ravi Delhi both
104 Meera Pune both
caught: Merge keys are not unique in right dataset; not a many-to-on
validate="many_to_one" fails fast when the dimension has duplicate keys, instead of silently multiplying rows. indicator=True shows which side each row came from.
Time series: resample and rolling
import numpy as np
ts = pd.DataFrame({"ts": pd.date_range("2026-03-01", periods=10, freq="12h"),
"amount": [10, 20, 15, 30, 25, 5, 40, 35, 20, 10]}).set_index("ts")
daily = ts.resample("D").sum()
daily["rolling_3d"] = daily["amount"].rolling(3, min_periods=1).mean().round(1)
daily["pct_change"] = daily["amount"].pct_change().mul(100).round(1)
print(daily.to_string())amount rolling_3d pct_change ts 2026-03-01 30 30.0 NaN 2026-03-02 45 37.5 50.0 2026-03-03 30 35.0 -33.3 2026-03-04 75 50.0 150.0 2026-03-05 30 45.0 -60.0
Performance and memory
big = pd.DataFrame({"city": np.random.default_rng(1).choice(["Pune", "Delhi", "Mumbai"], 300_000),
"amount": np.random.default_rng(2).uniform(1, 500, 300_000)})
before = big.memory_usage(deep=True).sum() / 1e6
big["city"] = big["city"].astype("category")
after = big.memory_usage(deep=True).sum() / 1e6
print(f"memory: {before:.1f} MB -> {after:.1f} MB with category dtype")
# vectorised beats apply: same answer, no Python loop per row
big["tax_vec"] = np.where(big["amount"] > 100, big["amount"] * 0.18, 0)
print("rows:", len(big), "| taxed rows:", int((big["tax_vec"] > 0).sum()))memory: 21.0 MB -> 2.7 MB with category dtype rows: 300000 | taxed rows: 240449
| Tip | Why |
|---|---|
Use vectorised operations, not apply with Python functions | apply loops in Python; vectorised ops run in C |
category dtype for repeated strings | Stores codes instead of repeated strings |
Read only needed columns: usecols=; parse types up front | Less memory and fewer surprises |
Large files: chunksize= or Parquet with column selection | Process in pieces; Parquet is columnar and typed |
| Beyond one machine | Move the same logic to Spark, Polars or DuckDB |
"I load with explicit types, clean with method chains (drop_duplicates, assign, string methods), aggregate with named aggregations, and merge with validate to catch duplicate keys. For time series I use resample and rolling. For performance I vectorise, use category dtypes, read only needed columns and switch to Parquet, chunks or Spark when data outgrows memory."
7. Data Visualisation
Data engineers visualise data to check it (distributions, gaps, spikes after a load), to monitor pipelines (volumes and freshness over time) and to explain results. matplotlib is the base library; seaborn adds statistical charts; Plotly adds interactivity; BI tools take over for business dashboards.
| Question | Chart |
|---|---|
| How does a value change over time? | Line chart |
| How do categories compare? | Bar chart (sorted) |
| How is a value distributed? Outliers? | Histogram or box plot |
| Are two measures related? | Scatter plot |
| Did the daily load volume drop? | Line chart of row counts with a threshold line |
- Start the y-axis at zero for bars; label axes and units; remove chart junk
- One message per chart, stated in the title
- Use colour for meaning (highlight one series), not decoration
The chart below is produced by the project in the next section with matplotlib:
import matplotlib.pyplot as plt
a = prices["ALPHA"]
fig, axes = plt.subplots(2, 1, figsize=(9, 6), sharex=True, gridspec_kw={"height_ratios": [2, 1]})
axes[0].plot(a.index, a, label="ALPHA close")
axes[0].plot(a.index, a.rolling(20).mean(), label="20-day MA")
axes[0].plot(a.index, a.rolling(50).mean(), label="50-day MA")
axes[0].legend(); axes[0].set_ylabel("Price")
drawdown = (a / a.cummax() - 1) * 100
axes[1].fill_between(drawdown.index, drawdown, 0)
axes[1].set_ylabel("Drawdown %")
fig.savefig("alpha.png", dpi=150, bbox_inches="tight")
8. Project: Navigating the Stock Market with Python
This project ties the module together: load prices, compute returns and risk, find trading signals, backtest a simple strategy, and chart the result. It uses synthetic prices for three fictional tickers so it runs anywhere with a fixed seed; swapping in real data only changes load_prices().
Educational analysis only, not investment advice. Real market data has gaps, splits and dividends that must be handled before analysis.
Step 1: load and inspect
import numpy as np, pandas as pd
def load_prices():
"""Synthetic daily closes for three fictional tickers (geometric Brownian motion, fixed seed).
In a real project, replace this with a market data API or your broker's export."""
rng = np.random.default_rng(42)
days = pd.bdate_range("2025-01-01", "2025-12-31") # business days
params = {"ALPHA": (0.0006, 0.018), "BETA": (0.0002, 0.012), "GAMMA": (0.0009, 0.028)}
data = {}
for ticker, (mu, sigma) in params.items():
daily_log_returns = rng.normal(mu, sigma, len(days))
data[ticker] = 100 * np.exp(np.cumsum(daily_log_returns))
return pd.DataFrame(data, index=days).round(2)
prices = load_prices()
print(prices.shape, prices.index.min().date(), "to", prices.index.max().date())
print(prices.head(3).to_string())(261, 3) 2025-01-01 to 2025-12-31
ALPHA BETA GAMMA
2025-01-01 100.61 99.70 103.90
2025-01-02 98.80 100.00 103.44
2025-01-03 100.21 99.35 107.69
Step 2: returns, cumulative growth and volatility
returns = prices.pct_change().dropna()
summary = pd.DataFrame({
"total_return_%": ((prices.iloc[-1] / prices.iloc[0] - 1) * 100).round(1),
"avg_daily_%": (returns.mean() * 100).round(3),
"annual_vol_%": (returns.std() * np.sqrt(252) * 100).round(1), # 252 trading days
})
summary["return_per_risk"] = (summary["total_return_%"] / summary["annual_vol_%"]).round(2)
print(summary.to_string())total_return_% avg_daily_% annual_vol_% return_per_risk ALPHA -7.4 -0.015 26.9 -0.28 BETA 12.6 0.053 19.2 0.66 GAMMA -21.3 -0.051 45.4 -0.47
Step 3: maximum drawdown
Drawdown is the fall from the highest price seen so far; the maximum drawdown is the worst peak-to-trough loss, a key risk measure:
running_peak = prices.cummax()
drawdown = prices / running_peak - 1
worst = pd.DataFrame({"max_drawdown_%": (drawdown.min() * 100).round(1),
"worst_day": drawdown.idxmin().dt.date})
print(worst.to_string())max_drawdown_% worst_day ALPHA -23.3 2025-12-11 BETA -15.6 2025-09-05 GAMMA -53.5 2025-11-06
Step 4: correlation for diversification
print(returns.corr().round(2).to_string())
ALPHA BETA GAMMA ALPHA 1.00 0.01 -0.08 BETA 0.01 1.00 0.04 GAMMA -0.08 0.04 1.00
Low correlations between assets mean they do not move together, which reduces portfolio risk. These series were generated independently, so their correlations are near zero; real stocks in one market are usually positively correlated.
Step 5: moving-average crossover signals
A "golden cross" is when the 20-day moving average crosses above the 50-day; a "death cross" is the opposite. Detect crossings by comparing today's state with yesterday's:
a = prices["ALPHA"].to_frame("close")
a["ma20"] = a["close"].rolling(20).mean()
a["ma50"] = a["close"].rolling(50).mean()
a = a.dropna()
above = a["ma20"] > a["ma50"]
crosses = a[above != above.shift()].iloc[1:] # state changed, skip first row
crosses = crosses.assign(signal=np.where(above[crosses.index], "golden cross (buy)", "death cross (sell)"))
print(crosses[["close", "ma20", "ma50", "signal"]].round(2).head(6).to_string())
print("signals in 2025:", len(crosses))close ma20 ma50 signal 2025-04-30 106.05 108.54 108.80 death cross (sell) 2025-07-22 95.07 95.76 95.72 golden cross (buy) 2025-07-24 93.44 95.22 95.46 death cross (sell) 2025-08-07 93.28 94.68 94.50 golden cross (buy) 2025-08-12 92.27 94.37 94.39 death cross (sell) 2025-09-18 100.69 94.03 93.99 golden cross (buy) signals in 2025: 9
Step 6: backtest the strategy vs buy-and-hold
position = above.astype(int).shift(1).fillna(0) # act the day AFTER a signal: no look-ahead bias
daily_ret = a["close"].pct_change().fillna(0)
strategy = (1 + daily_ret * position).cumprod()
buy_hold = (1 + daily_ret).cumprod()
print(f"strategy growth: {strategy.iloc[-1]:.3f}x")
print(f"buy and hold growth: {buy_hold.iloc[-1]:.3f}x")
print(f"days invested: {int(position.sum())} of {len(position)}")strategy growth: 0.830x buy and hold growth: 0.833x days invested: 82 of 212
Reading the result: the crossover strategy ended almost level with buy-and-hold (0.830× vs 0.833×) while invested on only 82 of 212 trading days, so it carried market risk for far less time. Nine signals in one year also show its weakness: in sideways markets the averages cross back and forth (whipsaws), and each round trip would cost fees.
The one-day shift is essential: using today's signal on today's return is look-ahead bias, the most common backtesting mistake. A fair comparison would also include trading costs and test on data the rules were not tuned on.
Taking it to production
| Step | How |
|---|---|
| Real data | A market data API or vendor files; handle splits, dividends, holidays and missing days |
| Storage | Partitioned Parquet or a Delta/Iceberg table by date and ticker |
| Scheduling | An Airflow DAG that runs after market close |
| Scale | Thousands of tickers: Spark with grouped pandas UDFs (applyInPandas) per ticker |
| Quality | Checks for missing days, zero or negative prices, extreme jumps |
| Serving | A dashboard of returns, volatility, drawdown and signals |
"I built a stock analysis pipeline in Python: load daily prices, compute returns, annualised volatility, maximum drawdown and correlations with pandas and NumPy, detect moving-average crossovers, and backtest the strategy against buy-and-hold while avoiding look-ahead bias with a one-day shift. In production the same logic runs on Parquet or Delta tables, scheduled by Airflow, scaled with Spark per ticker."