Lesson 03

Functions, modules, and venv

Turn scripts into clean, testable components. Organize code into modules and isolate dependencies.

Functions

def pct_change(prev: float, curr: float) -> float:
    """Return percentage change from prev to curr."""
    if prev == 0:
        raise ValueError("prev must be non-zero")
    return (curr - prev) / prev * 100

print(pct_change(100, 110))  # 10.0

Modules & imports

Create a file metrics.py:

# metrics.py
from statistics import mean


def annualize(daily_returns: list[float]) -> float:
    return mean(daily_returns) * 252


if __name__ == "__main__":
    # Only runs when you execute: python metrics.py
    print(annualize([0.01, -0.002, 0.004]))

Import it in another file:

# app.py
import metrics
print(metrics.annualize([0.01, -0.002, 0.004]))

Packaging basics

Group related files into a package by adding an __init__.py file:

project/
  analytics/
    __init__.py
    metrics.py
  app.py

Then import with from analytics import metrics.

Virtual environments (venv)

Create an isolated environment for dependencies:

# Windows (PowerShell)
python -m venv .venv
. .venv/Scripts/Activate.ps1
pip install requests pytest

Deactivate with deactivate. Keep a requirements.txt via pip freeze > requirements.txt.

Accelerate with SigLabs Financial Software

Forecasting, market screening, risk insights, and reporting—built for speed and clarity.

Next steps

Next up: files, errors, and testing in Lesson 04.