{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Functions, Modules, Errors, and Testing\n",
        "\n**Opening question:** How can a calculation be trusted when it is reused in several chapters or projects?\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def simple_return(start_price: float, end_price: float) -> float:\n",
        "    \"\"\"Return the decimal holding-period return.\"\"\"\n",
        "    if start_price <= 0:\n",
        "        raise ValueError(\"start_price must be positive\")\n",
        "    return end_price / start_price - 1\n",
        "\n",
        "print(simple_return(100, 105))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Interpretation check:** Interpretation. The tiny binary representation difference is normal. Formatting or math.isclose is appropriate when comparing floating-point values.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import math\n",
        "\n",
        "assert math.isclose(simple_return(100, 105), 0.05)\n",
        "try:\n",
        "    simple_return(0, 105)\n",
        "except ValueError as err:\n",
        "    print(err)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Interpretation check:** Interpretation. The first assertion protects the formula; the second check demonstrates that an invalid denominator is rejected.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Verified source output\n",
        "\n",
        "```text\n0.050000000000000044\n```\n\n```text\nstart_price must be positive\n```\n\n```text\ndef simple_return(start_price: float, end_price: float) -> float:\nraise ValueError(\"start_price must be positive\")\nprint(simple_return(100, 105))\nimport math\nassert math.isclose(simple_return(100, 105), 0.05)\nsimple_return(0, 105)\n```\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3"
    },
    "ceteris_lab": {
      "course_slug": "fundamentals-python-econometrics",
      "source_derived": true,
      "course_title": "Fundamentals of Python for Financial Econometrics",
      "chapter": 6,
      "source_origin": "source-derived"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
