Skip to content

Codal API

search

Codal announcement search.

CODAL_BASE module-attribute

CODAL_BASE = 'https://codal.ir'

CODAL_SEARCH_URL module-attribute

CODAL_SEARCH_URL = "https://search.codal.ir/api/search/v2/q"

MONTHLY_ACTIVITY_LETTER module-attribute

MONTHLY_ACTIVITY_LETTER = 58

INTERIM_FINANCIAL_LETTER module-attribute

INTERIM_FINANCIAL_LETTER = 6

__all__ module-attribute

__all__ = [
    "INTERIM_FINANCIAL_LETTER",
    "MONTHLY_ACTIVITY_LETTER",
    "get_financial_statements",
    "get_monthly_reports",
    "resolve_codal_url",
    "search_codal",
]

AsyncHTTPClient

AsyncHTTPClient(
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
)

Small retrying wrapper around :class:httpx.AsyncClient.

Requests use a verified transport when config.verify_ssl is true. A certificate failure is retried once over an unverified transport only when config.allow_tls_fallback is true; the first fallback emits a UserWarning and a log record. With fallback disabled, the failure raises :class:~iranquant.exceptions.IranQuantConnectionError without retrying.

Environment proxy variables are ignored by default (trust_env=False) to avoid corporate/VPN HTTP proxies breaking direct connections to domestic Iranian hosts. Pass proxy=... to opt into an explicit proxy.

Create the pooled HTTP transports.

Parameters:

Name Type Description Default
timeout float

Per-request timeout in seconds. Defaults to :data:iranquant.config.DEFAULT_TIMEOUT (30 s).

DEFAULT_TIMEOUT
max_concurrency int

Maximum number of simultaneous requests enforced by an internal :class:asyncio.Semaphore. Defaults to :data:iranquant.config.MAX_CONCURRENCY (10).

MAX_CONCURRENCY
max_retries int

Total attempts per request. Defaults to :data:iranquant.config.MAX_RETRIES (3).

MAX_RETRIES
retry_wait float

Base wait used by the exponential retry backoff, in seconds. Defaults to :data:iranquant.config.RETRY_WAIT (0.5).

RETRY_WAIT
headers Mapping[str, str] | None

Extra headers merged over the built-in TSETMC/Codal headers.

None
proxy str | None

Optional explicit proxy URL, e.g. "http://127.0.0.1:9090". When omitted, environment proxy variables are ignored.

None
trust_env bool | None

Whether to honour HTTP_PROXY / HTTPS_PROXY and other environment settings. Defaults to True only when an explicit proxy is supplied, otherwise False.

None
config IranQuantConfig | None

TLS policy. Defaults to :class:IranQuantConfig, which reads IRANQUANT_VERIFY_SSL and IRANQUANT_ALLOW_TLS_FALLBACK.

None

Examples:

>>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
>>> client.trust_env
False
>>> client = AsyncHTTPClient(
...     config=IranQuantConfig(allow_tls_fallback=False)
... )
Source code in src/iranquant/core/client.py
def __init__(
    self,
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
) -> None:
    """Create the pooled HTTP transports.

    Args:
        timeout: Per-request timeout in seconds.  Defaults to
            :data:`iranquant.config.DEFAULT_TIMEOUT` (30 s).
        max_concurrency: Maximum number of simultaneous requests enforced
            by an internal :class:`asyncio.Semaphore`.  Defaults to
            :data:`iranquant.config.MAX_CONCURRENCY` (10).
        max_retries: Total attempts per request.  Defaults to
            :data:`iranquant.config.MAX_RETRIES` (3).
        retry_wait: Base wait used by the exponential retry backoff, in
            seconds.  Defaults to :data:`iranquant.config.RETRY_WAIT` (0.5).
        headers: Extra headers merged over the built-in TSETMC/Codal
            headers.
        proxy: Optional explicit proxy URL, e.g.
            ``"http://127.0.0.1:9090"``.  When omitted, environment proxy
            variables are ignored.
        trust_env: Whether to honour ``HTTP_PROXY`` / ``HTTPS_PROXY`` and
            other environment settings.  Defaults to ``True`` only when an
            explicit ``proxy`` is supplied, otherwise ``False``.
        config: TLS policy. Defaults to :class:`IranQuantConfig`, which
            reads ``IRANQUANT_VERIFY_SSL`` and
            ``IRANQUANT_ALLOW_TLS_FALLBACK``.

    Examples:
        >>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
        >>> client.trust_env
        False
        >>> client = AsyncHTTPClient(
        ...     config=IranQuantConfig(allow_tls_fallback=False)
        ... )
    """
    self._semaphore = asyncio.Semaphore(max_concurrency)
    self._max_retries = max_retries
    self._retry_wait = retry_wait
    self._headers = dict(headers or {})
    self.config = config or IranQuantConfig()
    self.proxy = proxy
    # Explicit proxies imply honouring the environment unless overridden.
    self.trust_env = (proxy is not None) if trust_env is None else trust_env
    self._tls_fallback_warned = False

    common: dict[str, Any] = {
        "timeout": timeout,
        "follow_redirects": True,
        "trust_env": self.trust_env,
        "http2": False,
    }
    if proxy is not None:
        common["proxy"] = proxy

    self._client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=self.config.verify_ssl,
        **common,
    )
    self._fallback_client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=False,
        **common,
    )

get async

get(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response

Perform a GET request with retries and TLS fallback.

The request is retried up to max_retries times on network errors, and responses with status codes >= 500 are treated as retryable. Certificate failures use the unverified fallback transport once when allow_tls_fallback is true; the first fallback emits a UserWarning. With fallback disabled, the request fails immediately with :class:~iranquant.exceptions.IranQuantConnectionError.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters. Ignored for URL encoding when raw is true.

None
headers Mapping[str, str] | None

Optional per-request headers merged over the defaults.

None
raw bool

When true the URL string is sent verbatim without percent-encoding. Required for the MarketWatch endpoint, whose paperTypes[0]=1 brackets must stay literal.

False

Returns:

Type Description
Response

The successful :class:httpx.Response.

Raises:

Type Description
NetworkError

If the host is unreachable, a non-2xx status is returned, or all retries are exhausted.

IranQuantConnectionError

If TLS verification fails and allow_tls_fallback is false.

Examples:

>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
async def get(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response:
    """Perform a GET request with retries and TLS fallback.

    The request is retried up to ``max_retries`` times on network errors,
    and responses with status codes >= 500 are treated as retryable.
    Certificate failures use the unverified fallback transport once when
    ``allow_tls_fallback`` is true; the first fallback emits a
    ``UserWarning``. With fallback disabled, the request fails immediately
    with :class:`~iranquant.exceptions.IranQuantConnectionError`.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.  Ignored for URL encoding when
            ``raw`` is true.
        headers: Optional per-request headers merged over the defaults.
        raw: When true the URL string is sent verbatim without
            percent-encoding.  Required for the MarketWatch endpoint, whose
            ``paperTypes[0]=1`` brackets must stay literal.

    Returns:
        The successful :class:`httpx.Response`.

    Raises:
        NetworkError: If the host is unreachable, a non-2xx status is
            returned, or all retries are exhausted.
        IranQuantConnectionError: If TLS verification fails and
            ``allow_tls_fallback`` is false.

    Examples:
        >>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
        >>> response.status_code
        200
    """

    target = self._build_url(url, params, raw=raw)

    try:
        async for attempt in self._retrying():
            with attempt:
                response = await self._send_with_fallback(target, headers)
                if response.status_code >= 500:
                    raise NetworkError(f"Server error {response.status_code} for {target}")
                response.raise_for_status()
                return response
    except httpx.HTTPStatusError as exc:
        raise NetworkError(f"HTTP {exc.response.status_code} for {exc.request.url}") from exc
    except httpx.HTTPError as exc:
        raise NetworkError(f"Request failed for {target}: {exc}") from exc

    raise NetworkError(f"Request failed after retries: {target}")

get_json async

get_json(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any

GET a URL and decode its JSON body.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters.

None
headers Mapping[str, str] | None

Optional per-request headers.

None
raw bool

When true, send the URL untouched (see :meth:get).

False

Returns:

Type Description
Any

The decoded JSON value (usually a dict or list).

Raises:

Type Description
NetworkError

If the request fails after retries.

ParseError

If the response body is not valid JSON.

Examples:

>>> payload = await client.get_json(
...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
... )
>>> "instrumentSearch" in payload
True
Source code in src/iranquant/core/client.py
async def get_json(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any:
    """GET a URL and decode its JSON body.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.
        headers: Optional per-request headers.
        raw: When true, send the URL untouched (see :meth:`get`).

    Returns:
        The decoded JSON value (usually a ``dict`` or ``list``).

    Raises:
        NetworkError: If the request fails after retries.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> payload = await client.get_json(
        ...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
        ... )
        >>> "instrumentSearch" in payload
        True
    """

    response = await self.get(url, params=params, headers=headers, raw=raw)
    try:
        return response.json()
    except ValueError as exc:
        raise ParseError(f"Invalid JSON from {response.request.url}") from exc

aclose async

aclose() -> None

Close the primary and fallback HTTP transports.

Safe to call more than once. After closing, the instance must not be used again.

Examples:

>>> client = AsyncHTTPClient()
>>> await client.aclose()
Source code in src/iranquant/core/client.py
async def aclose(self) -> None:
    """Close the primary and fallback HTTP transports.

    Safe to call more than once.  After closing, the instance must not be
    used again.

    Examples:
        >>> client = AsyncHTTPClient()
        >>> await client.aclose()
    """
    await self._client.aclose()
    await self._fallback_client.aclose()

__aenter__ async

__aenter__() -> AsyncHTTPClient

Enter the async context manager and return self.

Source code in src/iranquant/core/client.py
async def __aenter__(self) -> AsyncHTTPClient:
    """Enter the async context manager and return ``self``."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close all transports when leaving the async context manager.

Source code in src/iranquant/core/client.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close all transports when leaving the async context manager."""
    await self.aclose()

ParseError

Bases: IranQuantError

Raised when a remote payload cannot be parsed into the expected shape.

Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven or hEven values, and missing var datasource blocks.

CodalLetter

Bases: CodalBaseModel

CodalSearchResponse

Bases: CodalBaseModel

A page of Codal search results with Pythonic container behavior.

The wire-format field names (Total, Page, Letters) are kept for compatibility, and lowercase aliases (total, page, letters) are provided for idiomatic code. The object is also iterable, indexable and sized, and can be exported directly to a DataFrame.

Examples:

>>> response = iq.monthly_reports("فولاد")
>>> len(response) == response.total
True
>>> response[0].Symbol
'فولاد'
>>> response.to_dataframe()[["Symbol", "TracingNo"]].head()

total property

total: int

Total number of matching letters across all pages.

page property

page: int

One-based page number represented by this response.

letters property

letters: list[CodalLetter]

The letters on this page (alias of Letters).

__len__

__len__() -> int

Return the number of letters on this page.

Source code in src/iranquant/models/codal.py
def __len__(self) -> int:
    """Return the number of letters on this page."""
    return len(self.Letters)

__iter__

__iter__() -> Iterator[CodalLetter]

Iterate over the letters on this page.

Source code in src/iranquant/models/codal.py
def __iter__(self) -> Iterator[CodalLetter]:  # type: ignore[override]
    """Iterate over the letters on this page."""
    return iter(self.Letters)

__getitem__

__getitem__(index: int) -> CodalLetter
__getitem__(index: slice) -> list[CodalLetter]
__getitem__(
    index: int | slice,
) -> CodalLetter | list[CodalLetter]

Return one letter or a slice of letters.

Source code in src/iranquant/models/codal.py
def __getitem__(self, index: int | slice) -> CodalLetter | list[CodalLetter]:
    """Return one letter or a slice of letters."""
    return self.Letters[index]

to_dataframe

to_dataframe(
    engine: Literal["pandas", "polars"] = "pandas",
) -> Any

Export the letters to a Pandas or Polars DataFrame.

Parameters:

Name Type Description Default
engine Literal['pandas', 'polars']

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
Any

One row per letter with the declared :class:CodalLetter fields as

Any

columns (including nested extra fields is intentionally avoided so

Any

the schema stays stable).

Raises:

Type Description
ValueError

If engine is unsupported.

Examples:

>>> frame = iq.monthly_reports("فولاد").to_dataframe()
>>> frame[["Symbol", "TracingNo", "Title"]].head()
Source code in src/iranquant/models/codal.py
def to_dataframe(
    self,
    engine: Literal["pandas", "polars"] = "pandas",
) -> Any:
    """Export the letters to a Pandas or Polars DataFrame.

    Args:
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        One row per letter with the declared :class:`CodalLetter` fields as
        columns (including nested extra fields is intentionally avoided so
        the schema stays stable).

    Raises:
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> frame = iq.monthly_reports("فولاد").to_dataframe()
        >>> frame[["Symbol", "TracingNo", "Title"]].head()
    """

    columns = list(CodalLetter.model_fields)
    records = [letter.model_dump(include=set(columns)) for letter in self.Letters]
    if engine == "pandas":
        import pandas as pd

        return pd.DataFrame(records, columns=columns)
    if engine == "polars":
        import polars as pl

        if not records:
            return pl.DataFrame({column: [] for column in columns})
        return pl.DataFrame(records)
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

resolve_codal_url

resolve_codal_url(url: str) -> str

Make a Codal link absolute (/foo -> https://codal.ir/foo).

Protocol-relative links (//cdn...) become HTTPS, root-relative links are prefixed with :data:iranquant.config.CODAL_BASE, and absolute URLs are returned unchanged. Empty strings stay empty.

Parameters:

Name Type Description Default
url str

A raw Codal URL as returned by the search API.

required

Returns:

Type Description
str

An absolute URL suitable for :class:httpx.AsyncClient.

Examples:

>>> resolve_codal_url("/Report/123")
'https://codal.ir/Report/123'
>>> resolve_codal_url("//cdn.codal.ir/a.pdf")
'https://cdn.codal.ir/a.pdf'
Source code in src/iranquant/codal/search.py
def resolve_codal_url(url: str) -> str:
    """Make a Codal link absolute (``/foo`` -> ``https://codal.ir/foo``).

    Protocol-relative links (``//cdn...``) become HTTPS, root-relative links
    are prefixed with :data:`iranquant.config.CODAL_BASE`, and absolute URLs
    are returned unchanged.  Empty strings stay empty.

    Args:
        url: A raw Codal URL as returned by the search API.

    Returns:
        An absolute URL suitable for :class:`httpx.AsyncClient`.

    Examples:
        >>> resolve_codal_url("/Report/123")
        'https://codal.ir/Report/123'
        >>> resolve_codal_url("//cdn.codal.ir/a.pdf")
        'https://cdn.codal.ir/a.pdf'
    """

    cleaned = url.strip()
    if not cleaned:
        return cleaned
    if cleaned.startswith("//"):
        return f"https:{cleaned}"
    if cleaned.startswith("/"):
        return f"{CODAL_BASE}{cleaned}"
    if cleaned.startswith("http://") or cleaned.startswith("https://"):
        return cleaned
    return f"{CODAL_BASE}/{cleaned.lstrip('/')}"

_resolve_letter_urls

_resolve_letter_urls(letter: CodalLetter) -> CodalLetter
Source code in src/iranquant/codal/search.py
def _resolve_letter_urls(letter: CodalLetter) -> CodalLetter:
    letter.Url = resolve_codal_url(letter.Url)
    if letter.ExcelUrl:
        letter.ExcelUrl = resolve_codal_url(letter.ExcelUrl)
    if letter.PdfUrl:
        letter.PdfUrl = resolve_codal_url(letter.PdfUrl)
    return letter
_search(
    client: AsyncHTTPClient,
    *,
    symbol: str | None,
    letter_type: int,
    category: int,
    page: int,
    audited: bool,
    not_audited: bool,
    mains: bool,
    childs: bool,
) -> CodalSearchResponse
Source code in src/iranquant/codal/search.py
async def _search(
    client: AsyncHTTPClient,
    *,
    symbol: str | None,
    letter_type: int,
    category: int,
    page: int,
    audited: bool,
    not_audited: bool,
    mains: bool,
    childs: bool,
) -> CodalSearchResponse:
    params: dict[str, Any] = {
        "Symbol": symbol or "",
        "LetterType": letter_type,
        "Category": category,
        "CompanyState": -1,
        "CompanyType": -1,
        "PageNumber": page,
        "Audited": str(audited).lower(),
        "NotAudited": str(not_audited).lower(),
        "Mains": str(mains).lower(),
        "Childs": str(childs).lower(),
        "Consolidatable": "true",
        "NotConsolidatable": "true",
        "Publisher": "false",
        "search": "true",
    }
    payload = await client.get_json(CODAL_SEARCH_URL, params=params)
    try:
        response = CodalSearchResponse.model_validate(payload)
    except Exception as exc:  # pydantic.ValidationError
        raise ParseError("Unexpected Codal search payload") from exc

    response.Letters = [_resolve_letter_urls(letter) for letter in response.Letters]
    return response

search_codal async

search_codal(
    symbol: str | None = None,
    letter_type: int = -1,
    category: int = -1,
    page: int = 1,
    audited: bool = True,
    not_audited: bool = True,
    mains: bool = True,
    childs: bool = True,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse

Search Codal announcements.

Parameters mirror the search.codal.ir query API. A temporary client is created and closed when client is not supplied. Every returned letter has its Url, ExcelUrl and PdfUrl resolved to absolute URLs.

Parameters:

Name Type Description Default
symbol str | None

Optional Persian ticker to filter by, e.g. "فولاد".

None
letter_type int

Codal LetterType filter. -1 means all types; 58 selects monthly activity reports and 6 selects interim financial statements. Defaults to -1.

-1
category int

Codal Category filter; -1 means all. Defaults to -1.

-1
page int

One-based result page. Defaults to 1.

1
audited bool

Include audited reports. Defaults to True.

True
not_audited bool

Include unaudited reports. Defaults to True.

True
mains bool

Include parent-company reports. Defaults to True.

True
childs bool

Include subsidiary reports. Defaults to True.

True
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient. When omitted a temporary client is used and closed.

None

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse with Total,

CodalSearchResponse

Page and a list of :class:~iranquant.models.codal.CodalLetter.

Raises:

Type Description
NetworkError

If search.codal.ir cannot be reached.

ParseError

If the response is not valid JSON or does not match the expected schema.

Examples:

>>> response = await search_codal("فولاد", letter_type=58)
>>> response.Total
12
>>> response.Letters[0].Url.startswith("https://codal.ir")
True
Source code in src/iranquant/codal/search.py
async def search_codal(
    symbol: str | None = None,
    letter_type: int = -1,
    category: int = -1,
    page: int = 1,
    audited: bool = True,
    not_audited: bool = True,
    mains: bool = True,
    childs: bool = True,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse:
    """Search Codal announcements.

    Parameters mirror the ``search.codal.ir`` query API.  A temporary client is
    created and closed when ``client`` is not supplied.  Every returned letter
    has its ``Url``, ``ExcelUrl`` and ``PdfUrl`` resolved to absolute URLs.

    Args:
        symbol: Optional Persian ticker to filter by, e.g. ``"فولاد"``.
        letter_type: Codal ``LetterType`` filter.  ``-1`` means all types;
            ``58`` selects monthly activity reports and ``6`` selects interim
            financial statements.  Defaults to ``-1``.
        category: Codal ``Category`` filter; ``-1`` means all.  Defaults to
            ``-1``.
        page: One-based result page.  Defaults to ``1``.
        audited: Include audited reports.  Defaults to ``True``.
        not_audited: Include unaudited reports.  Defaults to ``True``.
        mains: Include parent-company reports.  Defaults to ``True``.
        childs: Include subsidiary reports.  Defaults to ``True``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.
            When omitted a temporary client is used and closed.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` with ``Total``,
        ``Page`` and a list of :class:`~iranquant.models.codal.CodalLetter`.

    Raises:
        NetworkError: If ``search.codal.ir`` cannot be reached.
        ParseError: If the response is not valid JSON or does not match the
            expected schema.

    Examples:
        >>> response = await search_codal("فولاد", letter_type=58)
        >>> response.Total
        12
        >>> response.Letters[0].Url.startswith("https://codal.ir")
        True
    """

    if client is not None:
        return await _search(
            client,
            symbol=symbol,
            letter_type=letter_type,
            category=category,
            page=page,
            audited=audited,
            not_audited=not_audited,
            mains=mains,
            childs=childs,
        )

    http = AsyncHTTPClient()
    try:
        return await _search(
            http,
            symbol=symbol,
            letter_type=letter_type,
            category=category,
            page=page,
            audited=audited,
            not_audited=not_audited,
            mains=mains,
            childs=childs,
        )
    finally:
        await http.aclose()

get_monthly_reports async

get_monthly_reports(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse

Monthly activity reports (گزارش فعالیت ماهانه, LetterType=58).

Parameters:

Name Type Description Default
symbol str

Persian ticker, e.g. "فولاد".

required
page int

One-based result page. Defaults to 1.

1
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient.

None

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse. Pass any

CodalSearchResponse

Letters entry to :func:fetch_and_parse_report to reconstruct its

CodalSearchResponse

tables.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = await get_monthly_reports("فولاد")
>>> tables = await fetch_and_parse_report(reports.Letters[0])
Source code in src/iranquant/codal/search.py
async def get_monthly_reports(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse:
    """Monthly activity reports (گزارش فعالیت ماهانه, ``LetterType=58``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based result page.  Defaults to ``1``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.  Pass any
        ``Letters`` entry to :func:`fetch_and_parse_report` to reconstruct its
        tables.

    Raises:
        NetworkError: If Codal cannot be reached.
        ParseError: If the response is malformed.

    Examples:
        >>> reports = await get_monthly_reports("فولاد")
        >>> tables = await fetch_and_parse_report(reports.Letters[0])
    """

    return await search_codal(
        symbol=symbol,
        letter_type=MONTHLY_ACTIVITY_LETTER,
        page=page,
        client=client,
    )

get_financial_statements async

get_financial_statements(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse

Interim financial statements (LetterType=6).

Parameters:

Name Type Description Default
symbol str

Persian ticker, e.g. "فولاد".

required
page int

One-based result page. Defaults to 1.

1
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient.

None

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse with interim

CodalSearchResponse

financial-statement letters.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> statements = await get_financial_statements("فولاد")
>>> statements.Letters[0].Title
'صورت‌های مالی ۳ ماهه'
Source code in src/iranquant/codal/search.py
async def get_financial_statements(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse:
    """Interim financial statements (``LetterType=6``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based result page.  Defaults to ``1``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` with interim
        financial-statement letters.

    Raises:
        NetworkError: If Codal cannot be reached.
        ParseError: If the response is malformed.

    Examples:
        >>> statements = await get_financial_statements("فولاد")
        >>> statements.Letters[0].Title
        'صورت‌های مالی ۳ ماهه'
    """

    return await search_codal(
        symbol=symbol,
        letter_type=INTERIM_FINANCIAL_LETTER,
        page=page,
        client=client,
    )

Datasource parser

parser

Extract and reconstruct Codal var datasource report tables.

Engine module-attribute

Engine = Literal['pandas', 'polars']

_DATASOURCE_PATTERN module-attribute

_DATASOURCE_PATTERN = re.compile(
    "var\\s+datasource\\s*=\\s*(\\{.*?\\})\\s*;\\s*</script>",
    re.DOTALL,
)

_DATASOURCE_MARKER module-attribute

_DATASOURCE_MARKER = re.compile(
    "var\\s+datasource\\s*=", re.DOTALL
)

_HEADER_HINTS module-attribute

_HEADER_HINTS = (
    "header",
    "هدر",
    "سرستون",
    "سر ستون",
    "عنوان",
    "title",
)

_NUMBER_PATTERN module-attribute

_NUMBER_PATTERN = re.compile("(?:\\d+(?:\\.\\d+)?|\\.\\d+)")

__all__ module-attribute

__all__ = [
    "Engine",
    "extract_datasource_json",
    "fetch_and_parse_report",
    "parse_codal_tables",
]

AsyncHTTPClient

AsyncHTTPClient(
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
)

Small retrying wrapper around :class:httpx.AsyncClient.

Requests use a verified transport when config.verify_ssl is true. A certificate failure is retried once over an unverified transport only when config.allow_tls_fallback is true; the first fallback emits a UserWarning and a log record. With fallback disabled, the failure raises :class:~iranquant.exceptions.IranQuantConnectionError without retrying.

Environment proxy variables are ignored by default (trust_env=False) to avoid corporate/VPN HTTP proxies breaking direct connections to domestic Iranian hosts. Pass proxy=... to opt into an explicit proxy.

Create the pooled HTTP transports.

Parameters:

Name Type Description Default
timeout float

Per-request timeout in seconds. Defaults to :data:iranquant.config.DEFAULT_TIMEOUT (30 s).

DEFAULT_TIMEOUT
max_concurrency int

Maximum number of simultaneous requests enforced by an internal :class:asyncio.Semaphore. Defaults to :data:iranquant.config.MAX_CONCURRENCY (10).

MAX_CONCURRENCY
max_retries int

Total attempts per request. Defaults to :data:iranquant.config.MAX_RETRIES (3).

MAX_RETRIES
retry_wait float

Base wait used by the exponential retry backoff, in seconds. Defaults to :data:iranquant.config.RETRY_WAIT (0.5).

RETRY_WAIT
headers Mapping[str, str] | None

Extra headers merged over the built-in TSETMC/Codal headers.

None
proxy str | None

Optional explicit proxy URL, e.g. "http://127.0.0.1:9090". When omitted, environment proxy variables are ignored.

None
trust_env bool | None

Whether to honour HTTP_PROXY / HTTPS_PROXY and other environment settings. Defaults to True only when an explicit proxy is supplied, otherwise False.

None
config IranQuantConfig | None

TLS policy. Defaults to :class:IranQuantConfig, which reads IRANQUANT_VERIFY_SSL and IRANQUANT_ALLOW_TLS_FALLBACK.

None

Examples:

>>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
>>> client.trust_env
False
>>> client = AsyncHTTPClient(
...     config=IranQuantConfig(allow_tls_fallback=False)
... )
Source code in src/iranquant/core/client.py
def __init__(
    self,
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
) -> None:
    """Create the pooled HTTP transports.

    Args:
        timeout: Per-request timeout in seconds.  Defaults to
            :data:`iranquant.config.DEFAULT_TIMEOUT` (30 s).
        max_concurrency: Maximum number of simultaneous requests enforced
            by an internal :class:`asyncio.Semaphore`.  Defaults to
            :data:`iranquant.config.MAX_CONCURRENCY` (10).
        max_retries: Total attempts per request.  Defaults to
            :data:`iranquant.config.MAX_RETRIES` (3).
        retry_wait: Base wait used by the exponential retry backoff, in
            seconds.  Defaults to :data:`iranquant.config.RETRY_WAIT` (0.5).
        headers: Extra headers merged over the built-in TSETMC/Codal
            headers.
        proxy: Optional explicit proxy URL, e.g.
            ``"http://127.0.0.1:9090"``.  When omitted, environment proxy
            variables are ignored.
        trust_env: Whether to honour ``HTTP_PROXY`` / ``HTTPS_PROXY`` and
            other environment settings.  Defaults to ``True`` only when an
            explicit ``proxy`` is supplied, otherwise ``False``.
        config: TLS policy. Defaults to :class:`IranQuantConfig`, which
            reads ``IRANQUANT_VERIFY_SSL`` and
            ``IRANQUANT_ALLOW_TLS_FALLBACK``.

    Examples:
        >>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
        >>> client.trust_env
        False
        >>> client = AsyncHTTPClient(
        ...     config=IranQuantConfig(allow_tls_fallback=False)
        ... )
    """
    self._semaphore = asyncio.Semaphore(max_concurrency)
    self._max_retries = max_retries
    self._retry_wait = retry_wait
    self._headers = dict(headers or {})
    self.config = config or IranQuantConfig()
    self.proxy = proxy
    # Explicit proxies imply honouring the environment unless overridden.
    self.trust_env = (proxy is not None) if trust_env is None else trust_env
    self._tls_fallback_warned = False

    common: dict[str, Any] = {
        "timeout": timeout,
        "follow_redirects": True,
        "trust_env": self.trust_env,
        "http2": False,
    }
    if proxy is not None:
        common["proxy"] = proxy

    self._client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=self.config.verify_ssl,
        **common,
    )
    self._fallback_client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=False,
        **common,
    )

get async

get(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response

Perform a GET request with retries and TLS fallback.

The request is retried up to max_retries times on network errors, and responses with status codes >= 500 are treated as retryable. Certificate failures use the unverified fallback transport once when allow_tls_fallback is true; the first fallback emits a UserWarning. With fallback disabled, the request fails immediately with :class:~iranquant.exceptions.IranQuantConnectionError.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters. Ignored for URL encoding when raw is true.

None
headers Mapping[str, str] | None

Optional per-request headers merged over the defaults.

None
raw bool

When true the URL string is sent verbatim without percent-encoding. Required for the MarketWatch endpoint, whose paperTypes[0]=1 brackets must stay literal.

False

Returns:

Type Description
Response

The successful :class:httpx.Response.

Raises:

Type Description
NetworkError

If the host is unreachable, a non-2xx status is returned, or all retries are exhausted.

IranQuantConnectionError

If TLS verification fails and allow_tls_fallback is false.

Examples:

>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
async def get(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response:
    """Perform a GET request with retries and TLS fallback.

    The request is retried up to ``max_retries`` times on network errors,
    and responses with status codes >= 500 are treated as retryable.
    Certificate failures use the unverified fallback transport once when
    ``allow_tls_fallback`` is true; the first fallback emits a
    ``UserWarning``. With fallback disabled, the request fails immediately
    with :class:`~iranquant.exceptions.IranQuantConnectionError`.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.  Ignored for URL encoding when
            ``raw`` is true.
        headers: Optional per-request headers merged over the defaults.
        raw: When true the URL string is sent verbatim without
            percent-encoding.  Required for the MarketWatch endpoint, whose
            ``paperTypes[0]=1`` brackets must stay literal.

    Returns:
        The successful :class:`httpx.Response`.

    Raises:
        NetworkError: If the host is unreachable, a non-2xx status is
            returned, or all retries are exhausted.
        IranQuantConnectionError: If TLS verification fails and
            ``allow_tls_fallback`` is false.

    Examples:
        >>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
        >>> response.status_code
        200
    """

    target = self._build_url(url, params, raw=raw)

    try:
        async for attempt in self._retrying():
            with attempt:
                response = await self._send_with_fallback(target, headers)
                if response.status_code >= 500:
                    raise NetworkError(f"Server error {response.status_code} for {target}")
                response.raise_for_status()
                return response
    except httpx.HTTPStatusError as exc:
        raise NetworkError(f"HTTP {exc.response.status_code} for {exc.request.url}") from exc
    except httpx.HTTPError as exc:
        raise NetworkError(f"Request failed for {target}: {exc}") from exc

    raise NetworkError(f"Request failed after retries: {target}")

get_json async

get_json(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any

GET a URL and decode its JSON body.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters.

None
headers Mapping[str, str] | None

Optional per-request headers.

None
raw bool

When true, send the URL untouched (see :meth:get).

False

Returns:

Type Description
Any

The decoded JSON value (usually a dict or list).

Raises:

Type Description
NetworkError

If the request fails after retries.

ParseError

If the response body is not valid JSON.

Examples:

>>> payload = await client.get_json(
...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
... )
>>> "instrumentSearch" in payload
True
Source code in src/iranquant/core/client.py
async def get_json(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any:
    """GET a URL and decode its JSON body.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.
        headers: Optional per-request headers.
        raw: When true, send the URL untouched (see :meth:`get`).

    Returns:
        The decoded JSON value (usually a ``dict`` or ``list``).

    Raises:
        NetworkError: If the request fails after retries.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> payload = await client.get_json(
        ...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
        ... )
        >>> "instrumentSearch" in payload
        True
    """

    response = await self.get(url, params=params, headers=headers, raw=raw)
    try:
        return response.json()
    except ValueError as exc:
        raise ParseError(f"Invalid JSON from {response.request.url}") from exc

aclose async

aclose() -> None

Close the primary and fallback HTTP transports.

Safe to call more than once. After closing, the instance must not be used again.

Examples:

>>> client = AsyncHTTPClient()
>>> await client.aclose()
Source code in src/iranquant/core/client.py
async def aclose(self) -> None:
    """Close the primary and fallback HTTP transports.

    Safe to call more than once.  After closing, the instance must not be
    used again.

    Examples:
        >>> client = AsyncHTTPClient()
        >>> await client.aclose()
    """
    await self._client.aclose()
    await self._fallback_client.aclose()

__aenter__ async

__aenter__() -> AsyncHTTPClient

Enter the async context manager and return self.

Source code in src/iranquant/core/client.py
async def __aenter__(self) -> AsyncHTTPClient:
    """Enter the async context manager and return ``self``."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close all transports when leaving the async context manager.

Source code in src/iranquant/core/client.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close all transports when leaving the async context manager."""
    await self.aclose()

ParseError

Bases: IranQuantError

Raised when a remote payload cannot be parsed into the expected shape.

Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven or hEven values, and missing var datasource blocks.

CodalDatasource

Bases: CodalBaseModel

CodalLetter

Bases: CodalBaseModel

resolve_codal_url

resolve_codal_url(url: str) -> str

Make a Codal link absolute (/foo -> https://codal.ir/foo).

Protocol-relative links (//cdn...) become HTTPS, root-relative links are prefixed with :data:iranquant.config.CODAL_BASE, and absolute URLs are returned unchanged. Empty strings stay empty.

Parameters:

Name Type Description Default
url str

A raw Codal URL as returned by the search API.

required

Returns:

Type Description
str

An absolute URL suitable for :class:httpx.AsyncClient.

Examples:

>>> resolve_codal_url("/Report/123")
'https://codal.ir/Report/123'
>>> resolve_codal_url("//cdn.codal.ir/a.pdf")
'https://cdn.codal.ir/a.pdf'
Source code in src/iranquant/codal/search.py
def resolve_codal_url(url: str) -> str:
    """Make a Codal link absolute (``/foo`` -> ``https://codal.ir/foo``).

    Protocol-relative links (``//cdn...``) become HTTPS, root-relative links
    are prefixed with :data:`iranquant.config.CODAL_BASE`, and absolute URLs
    are returned unchanged.  Empty strings stay empty.

    Args:
        url: A raw Codal URL as returned by the search API.

    Returns:
        An absolute URL suitable for :class:`httpx.AsyncClient`.

    Examples:
        >>> resolve_codal_url("/Report/123")
        'https://codal.ir/Report/123'
        >>> resolve_codal_url("//cdn.codal.ir/a.pdf")
        'https://cdn.codal.ir/a.pdf'
    """

    cleaned = url.strip()
    if not cleaned:
        return cleaned
    if cleaned.startswith("//"):
        return f"https:{cleaned}"
    if cleaned.startswith("/"):
        return f"{CODAL_BASE}{cleaned}"
    if cleaned.startswith("http://") or cleaned.startswith("https://"):
        return cleaned
    return f"{CODAL_BASE}/{cleaned.lstrip('/')}"

normalize_persian

normalize_persian(text: str) -> str

Normalize Persian/Arabic text for reliable comparison.

Converts Arabic yeh/kaf/teh-marbuta to their Persian equivalents, converts Arabic-Indic and Persian digits to ASCII digits, removes zero-width and directional control characters, and collapses whitespace.

This is what makes "فولاد" written with an Arabic yeh and the same symbol written with a Persian yeh resolve to the same TSETMC instrument.

Parameters:

Name Type Description Default
text str

Any string, including Persian, Arabic-Indic or mixed text.

required

Returns:

Type Description
str

The normalized string with single spaces and ASCII digits.

Examples:

>>> normalize_persian("۱۲۳")
'123'
>>> normalize_persian("  علي  ")
'علی'
Source code in src/iranquant/core/normalizer.py
def normalize_persian(text: str) -> str:
    """Normalize Persian/Arabic text for reliable comparison.

    Converts Arabic yeh/kaf/teh-marbuta to their Persian equivalents, converts
    Arabic-Indic and Persian digits to ASCII digits, removes zero-width and
    directional control characters, and collapses whitespace.

    This is what makes ``"فولاد"`` written with an Arabic yeh and the same
    symbol written with a Persian yeh resolve to the same TSETMC instrument.

    Args:
        text: Any string, including Persian, Arabic-Indic or mixed text.

    Returns:
        The normalized string with single spaces and ASCII digits.

    Examples:
        >>> normalize_persian("۱۲۳")
        '123'
        >>> normalize_persian("  علي  ")
        'علی'
    """

    translated = text.translate(_CHAR_MAP).translate(_ZERO_WIDTH)
    return " ".join(translated.split())

_extract_balanced_object

_extract_balanced_object(html: str) -> str | None
Source code in src/iranquant/codal/parser.py
def _extract_balanced_object(html: str) -> str | None:
    marker = _DATASOURCE_MARKER.search(html)
    if marker is None:
        return None
    start = html.find("{", marker.end())
    if start == -1:
        return None

    depth = 0
    in_string = False
    quote = ""
    escaped = False
    for index in range(start, len(html)):
        char = html[index]
        if in_string:
            if escaped:
                escaped = False
            elif char == "\\":
                escaped = True
            elif char == quote:
                in_string = False
            continue
        if char in ('"', "'"):
            in_string = True
            quote = char
        elif char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return html[start : index + 1]
    return None

extract_datasource_json

extract_datasource_json(html: str) -> dict[str, Any]

Extract the var datasource = {...} JSON object from a report page.

A fast regex is tried first; if the JSON contains nested braces inside strings or is followed by more JavaScript, a brace-balanced scanner is used as a fallback. Braces inside quoted strings are handled correctly.

Parameters:

Name Type Description Default
html str

The full HTML source of a Codal report page.

required

Returns:

Type Description
dict[str, Any]

The decoded datasource object, usually containing a "sheets" list.

Raises:

Type Description
ParseError

If no var datasource block is found, the block is not valid JSON, or it decodes to something other than an object.

Examples:

>>> html = '<script>var datasource = {"sheets": []};</script>'
>>> extract_datasource_json(html)
{'sheets': []}
Source code in src/iranquant/codal/parser.py
def extract_datasource_json(html: str) -> dict[str, Any]:
    """Extract the ``var datasource = {...}`` JSON object from a report page.

    A fast regex is tried first; if the JSON contains nested braces inside
    strings or is followed by more JavaScript, a brace-balanced scanner is used
    as a fallback.  Braces inside quoted strings are handled correctly.

    Args:
        html: The full HTML source of a Codal report page.

    Returns:
        The decoded datasource object, usually containing a ``"sheets"`` list.

    Raises:
        ParseError: If no ``var datasource`` block is found, the block is not
            valid JSON, or it decodes to something other than an object.

    Examples:
        >>> html = '<script>var datasource = {"sheets": []};</script>'
        >>> extract_datasource_json(html)
        {'sheets': []}
    """

    match = _DATASOURCE_PATTERN.search(html)
    raw = match.group(1) if match is not None else _extract_balanced_object(html)
    if raw is None:
        raise ParseError("No 'var datasource' object found in Codal report")

    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise ParseError("Malformed Codal datasource JSON") from exc
    if not isinstance(parsed, dict):
        raise ParseError("Codal datasource is not a JSON object")
    return cast(dict[str, Any], parsed)

_special_to_ascii

_special_to_ascii(text: str) -> str
Source code in src/iranquant/codal/parser.py
def _special_to_ascii(text: str) -> str:
    return (
        normalize_persian(text)
        .replace("٬", "")
        .replace(",", "")
        .replace("٫", ".")
        .replace("\u2212", "-")
        .strip()
    )

_parse_number

_parse_number(value: Any) -> float | None
Source code in src/iranquant/codal/parser.py
def _parse_number(value: Any) -> float | None:
    if isinstance(value, bool) or value is None:
        return None
    if isinstance(value, (int, float)):
        return float(value)
    if not isinstance(value, str):
        return None

    text = _special_to_ascii(value)
    if not text:
        return None

    negative = text.startswith("(") and text.endswith(")")
    if negative:
        text = text[1:-1].strip()

    sign = -1.0 if negative else 1.0
    if text.startswith("+") or text.startswith("-"):
        if text[0] == "-":
            sign *= -1.0
        text = text[1:].strip()

    if not _NUMBER_PATTERN.fullmatch(text):
        return None
    return sign * float(text)

_clean_value

_clean_value(value: Any) -> Any
Source code in src/iranquant/codal/parser.py
def _clean_value(value: Any) -> Any:
    if value is None:
        return None
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float)):
        return float(value)
    if isinstance(value, str):
        normalized = normalize_persian(value).strip()
        if not normalized:
            return None
        parsed = _parse_number(normalized)
        return parsed if parsed is not None else normalized
    return value

_is_number

_is_number(value: Any) -> bool
Source code in src/iranquant/codal/parser.py
def _is_number(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool)

_label

_label(value: Any) -> str
Source code in src/iranquant/codal/parser.py
def _label(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    return str(value).strip()

_dedupe_columns

_dedupe_columns(labels: list[str]) -> list[str]
Source code in src/iranquant/codal/parser.py
def _dedupe_columns(labels: list[str]) -> list[str]:
    seen: dict[str, int] = {}
    output: list[str] = []
    for index, label in enumerate(labels):
        base = label.strip() or f"column_{index + 1}"
        if base not in seen:
            seen[base] = 1
            output.append(base)
        else:
            seen[base] += 1
            output.append(f"{base}_{seen[base]}")
    return output

_normalize_column

_normalize_column(column: list[Any]) -> list[Any]
Source code in src/iranquant/codal/parser.py
def _normalize_column(column: list[Any]) -> list[Any]:
    has_number = any(_is_number(value) for value in column)
    has_text = any(isinstance(value, str) for value in column)
    if has_number and has_text:
        return [None if value is None else _label(value) for value in column]
    return column

_row_looks_like_header

_row_looks_like_header(values: list[Any]) -> bool
Source code in src/iranquant/codal/parser.py
def _row_looks_like_header(values: list[Any]) -> bool:
    non_empty = [value for value in values if value not in (None, "")]
    if len(non_empty) < 2:
        return False
    return not any(_is_number(value) for value in non_empty)

_reconstruct_table

_reconstruct_table(
    table: Any,
) -> tuple[list[str], list[list[Any]]]
Source code in src/iranquant/codal/parser.py
def _reconstruct_table(table: Any) -> tuple[list[str], list[list[Any]]]:
    raw_rows: dict[int, dict[int, Any]] = {}
    row_hints: dict[int, set[str]] = {}

    for cell in table.cells:
        if not cell.isVisible:
            continue
        row = int(cell.rowSequence or 0)
        column = int(cell.columnSequence or 0)
        raw_rows.setdefault(row, {})[column] = _clean_value(cell.value)
        for hint in (cell.rowType, cell.cellGroupName):
            if isinstance(hint, str):
                row_hints.setdefault(row, set()).add(normalize_persian(hint).lower())

    if not raw_rows:
        return [], []

    column_indexes = sorted({column for row in raw_rows.values() for column in row})
    if not column_indexes:
        return [], []

    ordered_rows: list[tuple[int, list[Any]]] = []
    for sequence in sorted(raw_rows):
        values = [raw_rows[sequence].get(column) for column in column_indexes]
        if all(value is None for value in values):
            continue
        ordered_rows.append((sequence, values))

    if not ordered_rows:
        return [], []

    header_positions: list[int] = []
    for position, (sequence, values) in enumerate(ordered_rows):
        hints = row_hints.get(sequence, set())
        hint_is_header = any(any(token in hint for token in _HEADER_HINTS) for hint in hints)
        if hint_is_header or (position == 0 and _row_looks_like_header(values)):
            header_positions.append(position)
        elif header_positions:
            # Only contiguous leading header rows are treated as headers.
            break

    header_rows = [ordered_rows[position][1] for position in header_positions]
    header_position_set = set(header_positions)
    if header_rows:
        labels: list[str] = []
        for column_index in range(len(column_indexes)):
            parts: list[str] = []
            for header_values in header_rows:
                label = _label(header_values[column_index])
                if label and (not parts or parts[-1] != label):
                    parts.append(label)
            labels.append(" - ".join(parts) if parts else f"column_{column_index + 1}")
        columns = _dedupe_columns(labels)
        data_rows = [
            values
            for position, (_, values) in enumerate(ordered_rows)
            if position not in header_position_set
        ]
    else:
        columns = _dedupe_columns([f"column_{index + 1}" for index in range(len(column_indexes))])
        data_rows = [values for _, values in ordered_rows]

    # Drop rows that became completely empty after cleaning.
    data_rows = [values for values in data_rows if any(value is not None for value in values)]
    if not data_rows:
        return columns, []

    normalized_columns = _normalize_all_columns(data_rows, len(columns))
    normalized_rows = [
        [normalized_columns[column][row] for column in range(len(columns))]
        for row in range(len(data_rows))
    ]
    return columns, normalized_rows

_normalize_all_columns

_normalize_all_columns(
    rows: list[list[Any]], width: int
) -> list[list[Any]]
Source code in src/iranquant/codal/parser.py
def _normalize_all_columns(
    rows: list[list[Any]],
    width: int,
) -> list[list[Any]]:
    return [_normalize_column([row[index] for row in rows]) for index in range(width)]

_build_frame

_build_frame(
    columns: list[str],
    rows: list[list[Any]],
    engine: Engine,
) -> Any
Source code in src/iranquant/codal/parser.py
def _build_frame(
    columns: list[str],
    rows: list[list[Any]],
    engine: Engine,
) -> Any:
    if engine == "polars":
        if not rows:
            return pl.DataFrame({column: [] for column in columns})
        return pl.DataFrame(
            {column: [row[index] for row in rows] for index, column in enumerate(columns)}
        )
    if engine == "pandas":
        return pd.DataFrame(rows, columns=columns)
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

parse_codal_tables

parse_codal_tables(
    datasource: dict[str, Any], engine: Engine = "pandas"
) -> dict[str, Any]

Reconstruct every visible table in a Codal datasource object.

Cells are grouped by rowSequence/columnSequence, invisible cells are dropped, header rows are detected (from rowType/cellGroupName hints or a text-only first row), and multi-row headers are joined with " - ". Persian/Arabic digits, thousands separators, ٫ decimals, unicode minus and accounting parentheses ((1,200) -> -1200.0) are normalized. Duplicate column labels get _2, _3 suffixes.

Parameters:

Name Type Description Default
datasource dict[str, Any]

A decoded datasource object, e.g. from :func:extract_datasource_json.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A dictionary mapping "<sheet title> - <table title>" to a clean

dict[str, Any]

DataFrame. Persistently duplicated keys are suffixed with (2),

dict[str, Any]

(3), and so on. Tables with no visible cells are omitted. Values

dict[str, Any]

are numeric (float) when parseable, otherwise str; missing

dict[str, Any]

cells are None/NaN.

Raises:

Type Description
ParseError

If the datasource does not match the expected structure.

ValueError

If engine is unsupported.

Examples:

>>> datasource = extract_datasource_json(html)
>>> tables = parse_codal_tables(datasource, engine="pandas")
>>> next(iter(tables))
'گزارش فعالیت ماهانه - تولید و فروش'
Source code in src/iranquant/codal/parser.py
def parse_codal_tables(
    datasource: dict[str, Any],
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Reconstruct every visible table in a Codal ``datasource`` object.

    Cells are grouped by ``rowSequence``/``columnSequence``, invisible cells are
    dropped, header rows are detected (from ``rowType``/``cellGroupName`` hints
    or a text-only first row), and multi-row headers are joined with ``" - "``.
    Persian/Arabic digits, thousands separators, ``٫`` decimals, unicode minus
    and accounting parentheses (``(1,200)`` -> ``-1200.0``) are normalized.
    Duplicate column labels get ``_2``, ``_3`` suffixes.

    Args:
        datasource: A decoded datasource object, e.g. from
            :func:`extract_datasource_json`.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A dictionary mapping ``"<sheet title> - <table title>"`` to a clean
        DataFrame.  Persistently duplicated keys are suffixed with `` (2)``,
        `` (3)``, and so on.  Tables with no visible cells are omitted.  Values
        are numeric (``float``) when parseable, otherwise ``str``; missing
        cells are ``None``/``NaN``.

    Raises:
        ParseError: If the datasource does not match the expected structure.
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> datasource = extract_datasource_json(html)
        >>> tables = parse_codal_tables(datasource, engine="pandas")
        >>> next(iter(tables))
        'گزارش فعالیت ماهانه - تولید و فروش'
    """

    if engine not in ("pandas", "polars"):
        raise ValueError(f"Unsupported dataframe engine: {engine!r}")

    try:
        model = CodalDatasource.model_validate(datasource)
    except Exception as exc:
        raise ParseError("Invalid Codal datasource structure") from exc

    output: dict[str, Any] = {}
    for sheet_index, sheet in enumerate(model.sheets):
        sheet_title = (
            normalize_persian(sheet.title_Fa or sheet.title_En or "") or f"sheet_{sheet_index + 1}"
        )
        for table_index, table in enumerate(sheet.tables):
            table_title = (
                normalize_persian(table.title_Fa or table.title_En or "")
                or f"table_{table_index + 1}"
            )
            columns, rows = _reconstruct_table(table)
            if not columns:
                continue
            key = f"{sheet_title} - {table_title}"
            if key in output:
                suffix = 2
                while f"{key} ({suffix})" in output:
                    suffix += 1
                key = f"{key} ({suffix})"
            output[key] = _build_frame(columns, rows, engine)
    return output

_fetch_and_parse async

_fetch_and_parse(
    client: AsyncHTTPClient, url: str, engine: Engine
) -> dict[str, Any]
Source code in src/iranquant/codal/parser.py
async def _fetch_and_parse(
    client: AsyncHTTPClient,
    url: str,
    engine: Engine,
) -> dict[str, Any]:
    response = await client.get(url)
    datasource = extract_datasource_json(response.text)
    return parse_codal_tables(datasource, engine=engine)

fetch_and_parse_report async

fetch_and_parse_report(
    url_or_letter: str | CodalLetter,
    engine: Engine = "pandas",
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]

Download a Codal report page and parse all of its datasource tables.

Relative URLs (including those on :class:~iranquant.models.codal.CodalLetter) are resolved with :func:~iranquant.codal.search.resolve_codal_url before the request is made.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Either an absolute/relative report URL or a CodalLetter whose Url is used.

required
engine Engine

"pandas" (default) or "polars".

'pandas'
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient. When omitted a temporary client is used and closed.

None

Returns:

Type Description
dict[str, Any]

The dictionary produced by :func:parse_codal_tables, keyed by

dict[str, Any]

"<sheet title> - <table title>".

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid var datasource JSON or the datasource structure is invalid.

ValueError

If engine is unsupported.

Examples:

>>> letter = reports.Letters[0]
>>> tables = await fetch_and_parse_report(letter)
>>> for name, table in tables.items():
...     print(name, table.shape)
Source code in src/iranquant/codal/parser.py
async def fetch_and_parse_report(
    url_or_letter: str | CodalLetter,
    engine: Engine = "pandas",
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]:
    """Download a Codal report page and parse all of its datasource tables.

    Relative URLs (including those on :class:`~iranquant.models.codal.CodalLetter`)
    are resolved with :func:`~iranquant.codal.search.resolve_codal_url` before
    the request is made.

    Args:
        url_or_letter: Either an absolute/relative report URL or a
            ``CodalLetter`` whose ``Url`` is used.
        engine: ``"pandas"`` (default) or ``"polars"``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.
            When omitted a temporary client is used and closed.

    Returns:
        The dictionary produced by :func:`parse_codal_tables`, keyed by
        ``"<sheet title> - <table title>"``.

    Raises:
        NetworkError: If the report page cannot be downloaded.
        ParseError: If the page has no valid ``var datasource`` JSON or the
            datasource structure is invalid.
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> letter = reports.Letters[0]
        >>> tables = await fetch_and_parse_report(letter)
        >>> for name, table in tables.items():
        ...     print(name, table.shape)
    """

    url = url_or_letter.Url if isinstance(url_or_letter, CodalLetter) else url_or_letter
    url = resolve_codal_url(url)

    if client is not None:
        return await _fetch_and_parse(client, url, engine)

    http = AsyncHTTPClient()
    try:
        return await _fetch_and_parse(http, url, engine)
    finally:
        await http.aclose()

Monthly sales analyzer

monthly

Monthly Codal sales analysis (LetterType=58).

The analyzer understands the standard گزارش فعالیت ماهانه - تولید و فروش table: a product section followed by summary rows such as جمع فروش داخلی, جمع فروش صادراتی, جمع درآمد ارائه خدمات and a final جمع row. It returns the current-month, year-to-date and prior-year values in million Rials (the unit used by Codal) together with Month-over-Month and Year-over-Year growth percentages.

_DATE_PATTERN module-attribute

_DATE_PATTERN = re.compile(
    "(\\d{4})\\s*/\\s*(\\d{1,2})\\s*/\\s*(\\d{1,2})"
)

_MONTH_HINTS module-attribute

_MONTH_HINTS = (
    "دوره یک ماهه",
    "دوره ۱ ماهه",
    "دوره ماه",
    "ماهه منتهی",
)

_YTD_HINTS module-attribute

_YTD_HINTS = (
    "از ابتدای سال مالی",
    "ازابتدای سال مالی",
    "ابتدای سال مالی",
)

_PREV_MONTH_HINTS module-attribute

_PREV_MONTH_HINTS = ('ماه قبل', 'دوره قبل', 'ماه گذشته')

_PRIOR_YEAR_HINTS module-attribute

_PRIOR_YEAR_HINTS = (
    "سال قبل",
    "سال مالی قبل",
    "دوره سال قبل",
)

_SUMMARY_TOKENS module-attribute

_SUMMARY_TOKENS = ('جمع', 'مجموع')

_TOTAL_LABELS module-attribute

_TOTAL_LABELS = {
    "جمع",
    "جمع کل",
    "مجموع",
    "مجموع کل",
    "جمع کل فروش",
}

_CATEGORY_LABELS module-attribute

_CATEGORY_LABELS = (
    "جمع فروش داخلی",
    "جمع فروش صادراتی",
    "جمع درآمد ارائه خدمات",
)

_EXCLUDED_SUMMARY_HINTS module-attribute

_EXCLUDED_SUMMARY_HINTS = ('برگشت', 'تخفیف')

__all__ module-attribute

__all__ = ["analyze_monthly_sales", "monthly_sales_summary"]

AsyncHTTPClient

AsyncHTTPClient(
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
)

Small retrying wrapper around :class:httpx.AsyncClient.

Requests use a verified transport when config.verify_ssl is true. A certificate failure is retried once over an unverified transport only when config.allow_tls_fallback is true; the first fallback emits a UserWarning and a log record. With fallback disabled, the failure raises :class:~iranquant.exceptions.IranQuantConnectionError without retrying.

Environment proxy variables are ignored by default (trust_env=False) to avoid corporate/VPN HTTP proxies breaking direct connections to domestic Iranian hosts. Pass proxy=... to opt into an explicit proxy.

Create the pooled HTTP transports.

Parameters:

Name Type Description Default
timeout float

Per-request timeout in seconds. Defaults to :data:iranquant.config.DEFAULT_TIMEOUT (30 s).

DEFAULT_TIMEOUT
max_concurrency int

Maximum number of simultaneous requests enforced by an internal :class:asyncio.Semaphore. Defaults to :data:iranquant.config.MAX_CONCURRENCY (10).

MAX_CONCURRENCY
max_retries int

Total attempts per request. Defaults to :data:iranquant.config.MAX_RETRIES (3).

MAX_RETRIES
retry_wait float

Base wait used by the exponential retry backoff, in seconds. Defaults to :data:iranquant.config.RETRY_WAIT (0.5).

RETRY_WAIT
headers Mapping[str, str] | None

Extra headers merged over the built-in TSETMC/Codal headers.

None
proxy str | None

Optional explicit proxy URL, e.g. "http://127.0.0.1:9090". When omitted, environment proxy variables are ignored.

None
trust_env bool | None

Whether to honour HTTP_PROXY / HTTPS_PROXY and other environment settings. Defaults to True only when an explicit proxy is supplied, otherwise False.

None
config IranQuantConfig | None

TLS policy. Defaults to :class:IranQuantConfig, which reads IRANQUANT_VERIFY_SSL and IRANQUANT_ALLOW_TLS_FALLBACK.

None

Examples:

>>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
>>> client.trust_env
False
>>> client = AsyncHTTPClient(
...     config=IranQuantConfig(allow_tls_fallback=False)
... )
Source code in src/iranquant/core/client.py
def __init__(
    self,
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    max_retries: int = MAX_RETRIES,
    retry_wait: float = RETRY_WAIT,
    headers: Mapping[str, str] | None = None,
    proxy: str | None = None,
    trust_env: bool | None = None,
    config: IranQuantConfig | None = None,
) -> None:
    """Create the pooled HTTP transports.

    Args:
        timeout: Per-request timeout in seconds.  Defaults to
            :data:`iranquant.config.DEFAULT_TIMEOUT` (30 s).
        max_concurrency: Maximum number of simultaneous requests enforced
            by an internal :class:`asyncio.Semaphore`.  Defaults to
            :data:`iranquant.config.MAX_CONCURRENCY` (10).
        max_retries: Total attempts per request.  Defaults to
            :data:`iranquant.config.MAX_RETRIES` (3).
        retry_wait: Base wait used by the exponential retry backoff, in
            seconds.  Defaults to :data:`iranquant.config.RETRY_WAIT` (0.5).
        headers: Extra headers merged over the built-in TSETMC/Codal
            headers.
        proxy: Optional explicit proxy URL, e.g.
            ``"http://127.0.0.1:9090"``.  When omitted, environment proxy
            variables are ignored.
        trust_env: Whether to honour ``HTTP_PROXY`` / ``HTTPS_PROXY`` and
            other environment settings.  Defaults to ``True`` only when an
            explicit ``proxy`` is supplied, otherwise ``False``.
        config: TLS policy. Defaults to :class:`IranQuantConfig`, which
            reads ``IRANQUANT_VERIFY_SSL`` and
            ``IRANQUANT_ALLOW_TLS_FALLBACK``.

    Examples:
        >>> client = AsyncHTTPClient(timeout=10.0, max_concurrency=5)
        >>> client.trust_env
        False
        >>> client = AsyncHTTPClient(
        ...     config=IranQuantConfig(allow_tls_fallback=False)
        ... )
    """
    self._semaphore = asyncio.Semaphore(max_concurrency)
    self._max_retries = max_retries
    self._retry_wait = retry_wait
    self._headers = dict(headers or {})
    self.config = config or IranQuantConfig()
    self.proxy = proxy
    # Explicit proxies imply honouring the environment unless overridden.
    self.trust_env = (proxy is not None) if trust_env is None else trust_env
    self._tls_fallback_warned = False

    common: dict[str, Any] = {
        "timeout": timeout,
        "follow_redirects": True,
        "trust_env": self.trust_env,
        "http2": False,
    }
    if proxy is not None:
        common["proxy"] = proxy

    self._client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=self.config.verify_ssl,
        **common,
    )
    self._fallback_client = httpx.AsyncClient(
        headers={**TSETMC_HEADERS, **self._headers},
        verify=False,
        **common,
    )

get async

get(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response

Perform a GET request with retries and TLS fallback.

The request is retried up to max_retries times on network errors, and responses with status codes >= 500 are treated as retryable. Certificate failures use the unverified fallback transport once when allow_tls_fallback is true; the first fallback emits a UserWarning. With fallback disabled, the request fails immediately with :class:~iranquant.exceptions.IranQuantConnectionError.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters. Ignored for URL encoding when raw is true.

None
headers Mapping[str, str] | None

Optional per-request headers merged over the defaults.

None
raw bool

When true the URL string is sent verbatim without percent-encoding. Required for the MarketWatch endpoint, whose paperTypes[0]=1 brackets must stay literal.

False

Returns:

Type Description
Response

The successful :class:httpx.Response.

Raises:

Type Description
NetworkError

If the host is unreachable, a non-2xx status is returned, or all retries are exhausted.

IranQuantConnectionError

If TLS verification fails and allow_tls_fallback is false.

Examples:

>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
async def get(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> httpx.Response:
    """Perform a GET request with retries and TLS fallback.

    The request is retried up to ``max_retries`` times on network errors,
    and responses with status codes >= 500 are treated as retryable.
    Certificate failures use the unverified fallback transport once when
    ``allow_tls_fallback`` is true; the first fallback emits a
    ``UserWarning``. With fallback disabled, the request fails immediately
    with :class:`~iranquant.exceptions.IranQuantConnectionError`.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.  Ignored for URL encoding when
            ``raw`` is true.
        headers: Optional per-request headers merged over the defaults.
        raw: When true the URL string is sent verbatim without
            percent-encoding.  Required for the MarketWatch endpoint, whose
            ``paperTypes[0]=1`` brackets must stay literal.

    Returns:
        The successful :class:`httpx.Response`.

    Raises:
        NetworkError: If the host is unreachable, a non-2xx status is
            returned, or all retries are exhausted.
        IranQuantConnectionError: If TLS verification fails and
            ``allow_tls_fallback`` is false.

    Examples:
        >>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
        >>> response.status_code
        200
    """

    target = self._build_url(url, params, raw=raw)

    try:
        async for attempt in self._retrying():
            with attempt:
                response = await self._send_with_fallback(target, headers)
                if response.status_code >= 500:
                    raise NetworkError(f"Server error {response.status_code} for {target}")
                response.raise_for_status()
                return response
    except httpx.HTTPStatusError as exc:
        raise NetworkError(f"HTTP {exc.response.status_code} for {exc.request.url}") from exc
    except httpx.HTTPError as exc:
        raise NetworkError(f"Request failed for {target}: {exc}") from exc

    raise NetworkError(f"Request failed after retries: {target}")

get_json async

get_json(
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any

GET a URL and decode its JSON body.

Parameters:

Name Type Description Default
url str

Absolute request URL.

required
params Mapping[str, Any] | None

Optional query parameters.

None
headers Mapping[str, str] | None

Optional per-request headers.

None
raw bool

When true, send the URL untouched (see :meth:get).

False

Returns:

Type Description
Any

The decoded JSON value (usually a dict or list).

Raises:

Type Description
NetworkError

If the request fails after retries.

ParseError

If the response body is not valid JSON.

Examples:

>>> payload = await client.get_json(
...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
... )
>>> "instrumentSearch" in payload
True
Source code in src/iranquant/core/client.py
async def get_json(
    self,
    url: str,
    *,
    params: Mapping[str, Any] | None = None,
    headers: Mapping[str, str] | None = None,
    raw: bool = False,
) -> Any:
    """GET a URL and decode its JSON body.

    Args:
        url: Absolute request URL.
        params: Optional query parameters.
        headers: Optional per-request headers.
        raw: When true, send the URL untouched (see :meth:`get`).

    Returns:
        The decoded JSON value (usually a ``dict`` or ``list``).

    Raises:
        NetworkError: If the request fails after retries.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> payload = await client.get_json(
        ...     "https://cdn.tsetmc.com/api/Instrument/GetInstrumentSearch/فولاد"
        ... )
        >>> "instrumentSearch" in payload
        True
    """

    response = await self.get(url, params=params, headers=headers, raw=raw)
    try:
        return response.json()
    except ValueError as exc:
        raise ParseError(f"Invalid JSON from {response.request.url}") from exc

aclose async

aclose() -> None

Close the primary and fallback HTTP transports.

Safe to call more than once. After closing, the instance must not be used again.

Examples:

>>> client = AsyncHTTPClient()
>>> await client.aclose()
Source code in src/iranquant/core/client.py
async def aclose(self) -> None:
    """Close the primary and fallback HTTP transports.

    Safe to call more than once.  After closing, the instance must not be
    used again.

    Examples:
        >>> client = AsyncHTTPClient()
        >>> await client.aclose()
    """
    await self._client.aclose()
    await self._fallback_client.aclose()

__aenter__ async

__aenter__() -> AsyncHTTPClient

Enter the async context manager and return self.

Source code in src/iranquant/core/client.py
async def __aenter__(self) -> AsyncHTTPClient:
    """Enter the async context manager and return ``self``."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close all transports when leaving the async context manager.

Source code in src/iranquant/core/client.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close all transports when leaving the async context manager."""
    await self.aclose()

IranQuantError

Bases: Exception

Base class for every exception raised by iranquant.

Catching this single type covers every library-specific failure while still allowing narrower handlers for specific cases.

Examples:

>>> try:
...     iq.history("نماد_ناموجود")
... except iq.IranQuantError as exc:
...     print(type(exc).__name__)
SymbolNotFoundError

ParseError

Bases: IranQuantError

Raised when a remote payload cannot be parsed into the expected shape.

Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven or hEven values, and missing var datasource blocks.

_Block dataclass

_Block(
    start: int,
    end: int,
    kind: str,
    date: tuple[int, int, int] | None,
    corrected: bool,
    label: str,
    amount_index: int,
)

A contiguous group of columns describing one reporting period.

fetch_and_parse_report async

fetch_and_parse_report(
    url_or_letter: str | CodalLetter,
    engine: Engine = "pandas",
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]

Download a Codal report page and parse all of its datasource tables.

Relative URLs (including those on :class:~iranquant.models.codal.CodalLetter) are resolved with :func:~iranquant.codal.search.resolve_codal_url before the request is made.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Either an absolute/relative report URL or a CodalLetter whose Url is used.

required
engine Engine

"pandas" (default) or "polars".

'pandas'
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient. When omitted a temporary client is used and closed.

None

Returns:

Type Description
dict[str, Any]

The dictionary produced by :func:parse_codal_tables, keyed by

dict[str, Any]

"<sheet title> - <table title>".

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid var datasource JSON or the datasource structure is invalid.

ValueError

If engine is unsupported.

Examples:

>>> letter = reports.Letters[0]
>>> tables = await fetch_and_parse_report(letter)
>>> for name, table in tables.items():
...     print(name, table.shape)
Source code in src/iranquant/codal/parser.py
async def fetch_and_parse_report(
    url_or_letter: str | CodalLetter,
    engine: Engine = "pandas",
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]:
    """Download a Codal report page and parse all of its datasource tables.

    Relative URLs (including those on :class:`~iranquant.models.codal.CodalLetter`)
    are resolved with :func:`~iranquant.codal.search.resolve_codal_url` before
    the request is made.

    Args:
        url_or_letter: Either an absolute/relative report URL or a
            ``CodalLetter`` whose ``Url`` is used.
        engine: ``"pandas"`` (default) or ``"polars"``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.
            When omitted a temporary client is used and closed.

    Returns:
        The dictionary produced by :func:`parse_codal_tables`, keyed by
        ``"<sheet title> - <table title>"``.

    Raises:
        NetworkError: If the report page cannot be downloaded.
        ParseError: If the page has no valid ``var datasource`` JSON or the
            datasource structure is invalid.
        ValueError: If ``engine`` is unsupported.

    Examples:
        >>> letter = reports.Letters[0]
        >>> tables = await fetch_and_parse_report(letter)
        >>> for name, table in tables.items():
        ...     print(name, table.shape)
    """

    url = url_or_letter.Url if isinstance(url_or_letter, CodalLetter) else url_or_letter
    url = resolve_codal_url(url)

    if client is not None:
        return await _fetch_and_parse(client, url, engine)

    http = AsyncHTTPClient()
    try:
        return await _fetch_and_parse(http, url, engine)
    finally:
        await http.aclose()

get_monthly_reports async

get_monthly_reports(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse

Monthly activity reports (گزارش فعالیت ماهانه, LetterType=58).

Parameters:

Name Type Description Default
symbol str

Persian ticker, e.g. "فولاد".

required
page int

One-based result page. Defaults to 1.

1
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient.

None

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse. Pass any

CodalSearchResponse

Letters entry to :func:fetch_and_parse_report to reconstruct its

CodalSearchResponse

tables.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = await get_monthly_reports("فولاد")
>>> tables = await fetch_and_parse_report(reports.Letters[0])
Source code in src/iranquant/codal/search.py
async def get_monthly_reports(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> CodalSearchResponse:
    """Monthly activity reports (گزارش فعالیت ماهانه, ``LetterType=58``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based result page.  Defaults to ``1``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.  Pass any
        ``Letters`` entry to :func:`fetch_and_parse_report` to reconstruct its
        tables.

    Raises:
        NetworkError: If Codal cannot be reached.
        ParseError: If the response is malformed.

    Examples:
        >>> reports = await get_monthly_reports("فولاد")
        >>> tables = await fetch_and_parse_report(reports.Letters[0])
    """

    return await search_codal(
        symbol=symbol,
        letter_type=MONTHLY_ACTIVITY_LETTER,
        page=page,
        client=client,
    )

normalize_persian

normalize_persian(text: str) -> str

Normalize Persian/Arabic text for reliable comparison.

Converts Arabic yeh/kaf/teh-marbuta to their Persian equivalents, converts Arabic-Indic and Persian digits to ASCII digits, removes zero-width and directional control characters, and collapses whitespace.

This is what makes "فولاد" written with an Arabic yeh and the same symbol written with a Persian yeh resolve to the same TSETMC instrument.

Parameters:

Name Type Description Default
text str

Any string, including Persian, Arabic-Indic or mixed text.

required

Returns:

Type Description
str

The normalized string with single spaces and ASCII digits.

Examples:

>>> normalize_persian("۱۲۳")
'123'
>>> normalize_persian("  علي  ")
'علی'
Source code in src/iranquant/core/normalizer.py
def normalize_persian(text: str) -> str:
    """Normalize Persian/Arabic text for reliable comparison.

    Converts Arabic yeh/kaf/teh-marbuta to their Persian equivalents, converts
    Arabic-Indic and Persian digits to ASCII digits, removes zero-width and
    directional control characters, and collapses whitespace.

    This is what makes ``"فولاد"`` written with an Arabic yeh and the same
    symbol written with a Persian yeh resolve to the same TSETMC instrument.

    Args:
        text: Any string, including Persian, Arabic-Indic or mixed text.

    Returns:
        The normalized string with single spaces and ASCII digits.

    Examples:
        >>> normalize_persian("۱۲۳")
        '123'
        >>> normalize_persian("  علي  ")
        'علی'
    """

    translated = text.translate(_CHAR_MAP).translate(_ZERO_WIDTH)
    return " ".join(translated.split())

_is_missing

_is_missing(value: Any) -> bool
Source code in src/iranquant/codal/monthly.py
def _is_missing(value: Any) -> bool:
    if value is None:
        return True
    if isinstance(value, (list, tuple, dict, set)):
        return False
    try:
        return bool(pd.isna(value))
    except (TypeError, ValueError):
        return False

_label

_label(value: Any) -> str
Source code in src/iranquant/codal/monthly.py
def _label(value: Any) -> str:
    if _is_missing(value):
        return ""
    return normalize_persian(str(value)).strip()

_to_number

_to_number(value: Any) -> float | None
Source code in src/iranquant/codal/monthly.py
def _to_number(value: Any) -> float | None:
    if _is_missing(value) or isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return float(value)
    if not isinstance(value, str):
        return None

    text = (
        normalize_persian(value)
        .replace("٬", "")
        .replace(",", "")
        .replace("٫", ".")
        .replace("\u2212", "-")
        .strip()
    )
    if not text or text in {"-", "—", "_"}:
        return None

    negative = text.startswith("(") and text.endswith(")")
    if negative:
        text = text[1:-1].strip()
    sign = -1.0 if negative else 1.0
    if text.startswith("+") or text.startswith("-"):
        if text[0] == "-":
            sign *= -1.0
        text = text[1:].strip()
    try:
        return sign * float(text)
    except ValueError:
        return None

_as_pandas

_as_pandas(frame: Any) -> pd.DataFrame
Source code in src/iranquant/codal/monthly.py
def _as_pandas(frame: Any) -> pd.DataFrame:
    if isinstance(frame, pl.DataFrame):
        return frame.to_pandas()
    if isinstance(frame, pd.DataFrame):
        return frame
    raise TypeError(f"Expected a pandas or polars DataFrame, got {type(frame)!r}")

_numeric_cells

_numeric_cells(frame: DataFrame) -> int
Source code in src/iranquant/codal/monthly.py
def _numeric_cells(frame: pd.DataFrame) -> int:
    total = 0
    for column in frame.columns[1:]:
        values = pd.to_numeric(frame[column], errors="coerce")
        total += int(values.notna().sum())
    return total

_select_table

_select_table(
    tables: dict[str, Any],
) -> tuple[str, pd.DataFrame]

Pick the production & sales table, falling back to the most numeric one.

Source code in src/iranquant/codal/monthly.py
def _select_table(tables: dict[str, Any]) -> tuple[str, pd.DataFrame]:
    """Pick the production & sales table, falling back to the most numeric one."""

    candidates: list[tuple[float, str, pd.DataFrame]] = []
    for key, raw_frame in tables.items():
        frame = _as_pandas(raw_frame)
        if frame.empty or frame.shape[1] == 0:
            continue
        name = normalize_persian(str(key))
        score = float(_numeric_cells(frame))
        if "تولید و فروش" in name:
            score += 1_000_000.0
        elif "فروش" in name:
            score += 1_000.0
        candidates.append((score, str(key), frame))

    if not candidates:
        raise ValueError("No usable Codal tables were supplied")

    candidates.sort(key=lambda item: item[0], reverse=True)
    best = candidates[0]
    return best[1], best[2]

_parse_date

_parse_date(label: str) -> tuple[int, int, int] | None
Source code in src/iranquant/codal/monthly.py
def _parse_date(label: str) -> tuple[int, int, int] | None:
    match = _DATE_PATTERN.search(label)
    if match is None:
        return None
    return (int(match.group(1)), int(match.group(2)), int(match.group(3)))

_build_blocks

_build_blocks(frame: DataFrame) -> list[_Block]
Source code in src/iranquant/codal/monthly.py
def _build_blocks(frame: pd.DataFrame) -> list[_Block]:
    starts: list[tuple[int, str, tuple[int, int, int] | None, bool, str]] = []
    for index, column in enumerate(frame.columns):
        label = _label(column)
        kind: str | None = None
        if any(hint in label for hint in _MONTH_HINTS) or ("دوره" in label and "ماه" in label):
            kind = "month"
        elif any(hint in label for hint in _YTD_HINTS):
            kind = "ytd"
        elif "اصلاحات" in label:
            kind = "adjustment"
        if kind is None:
            continue
        corrected = "اصلاح شده" in label or "اصلاح‌شده" in label
        starts.append((index, kind, _parse_date(label), corrected, label))

    blocks: list[_Block] = []
    for position, (start, kind, date, corrected, label) in enumerate(starts):
        end = starts[position + 1][0] if position + 1 < len(starts) else len(frame.columns)
        amount_index = end - 1
        for column_index in range(start, end):
            column_label = _label(frame.columns[column_index])
            if "مبلغ" in column_label:
                amount_index = column_index
                if "فروش" in column_label or "درآمد" in column_label:
                    break
        blocks.append(
            _Block(
                start=start,
                end=end,
                kind=kind,
                date=date,
                corrected=corrected,
                label=label,
                amount_index=amount_index,
            )
        )
    return blocks

_pick_period_blocks

_pick_period_blocks(
    blocks: list[_Block],
) -> tuple[
    _Block | None,
    _Block | None,
    _Block | None,
    _Block | None,
]

Return (current_month, previous_month, current_ytd, previous_ytd).

Source code in src/iranquant/codal/monthly.py
def _pick_period_blocks(
    blocks: list[_Block],
) -> tuple[_Block | None, _Block | None, _Block | None, _Block | None]:
    """Return ``(current_month, previous_month, current_ytd, previous_ytd)``."""

    month_blocks = [block for block in blocks if block.kind == "month"]
    ytd_blocks = [block for block in blocks if block.kind == "ytd"]

    current_month: _Block | None = None
    if month_blocks:
        current_month = max(
            month_blocks,
            key=lambda block: (block.date or (0, 0, 0), block.start),
        )

    previous_month: _Block | None = None
    previous_hint = next(
        (block for block in month_blocks if any(hint in block.label for hint in _PREV_MONTH_HINTS)),
        None,
    )
    if previous_hint is not None:
        previous_month = previous_hint
    elif current_month is not None and current_month.date is not None:
        earlier = [
            block
            for block in month_blocks
            if block.date is not None and block.date < current_month.date
        ]
        if earlier:
            previous_month = max(earlier, key=lambda block: block.date or (0, 0, 0))

    report_date = max(
        (block.date for block in blocks if block.date is not None),
        default=None,
    )

    current_ytd: _Block | None = None
    previous_ytd: _Block | None = None
    if report_date is not None:
        same_period = [block for block in ytd_blocks if block.date == report_date]
        if same_period:
            current_ytd = max(
                same_period,
                key=lambda block: (not block.corrected, block.start),
            )
        earlier_year = [
            block
            for block in ytd_blocks
            if block.date is not None and block.date[0] < report_date[0]
        ]
        if earlier_year:
            previous_ytd = max(
                earlier_year,
                key=lambda block: (block.date or (0, 0, 0), block.start),
            )
    else:
        usable = [block for block in ytd_blocks if not block.corrected] or ytd_blocks
        if usable:
            current_ytd = max(usable, key=lambda block: block.start)
        previous_ytd = next(
            (
                block
                for block in ytd_blocks
                if any(hint in block.label for hint in _PRIOR_YEAR_HINTS)
            ),
            None,
        )

    return current_month, previous_month, current_ytd, previous_ytd

_pct_change

_pct_change(
    current: float | None, previous: float | None
) -> float | None
Source code in src/iranquant/codal/monthly.py
def _pct_change(current: float | None, previous: float | None) -> float | None:
    if current is None or previous is None or previous == 0:
        return None
    return (current - previous) / abs(previous) * 100.0

_row_value

_row_value(
    frame: DataFrame, row: int, column: int
) -> float | None
Source code in src/iranquant/codal/monthly.py
def _row_value(frame: pd.DataFrame, row: int, column: int) -> float | None:
    if row < 0 or column < 0 or row >= frame.shape[0] or column >= frame.shape[1]:
        return None
    return _to_number(frame.iat[row, column])

_pick_total_row

_pick_total_row(labels: Series) -> int | None
Source code in src/iranquant/codal/monthly.py
def _pick_total_row(labels: pd.Series) -> int | None:
    exact = labels[labels.isin(_TOTAL_LABELS)]
    if not exact.empty:
        index = int(str(exact.index[0]))
        return index

    candidates = [
        int(str(index))
        for index, label in labels.items()
        if any(token in label for token in _SUMMARY_TOKENS)
        and label not in _CATEGORY_LABELS
        and not any(hint in label for hint in _EXCLUDED_SUMMARY_HINTS)
    ]
    return candidates[-1] if candidates else None

_aggregate

_aggregate(
    frame: DataFrame,
    total_row: int | None,
    category_rows: list[int],
    column: int,
) -> float | None
Source code in src/iranquant/codal/monthly.py
def _aggregate(
    frame: pd.DataFrame,
    total_row: int | None,
    category_rows: list[int],
    column: int,
) -> float | None:
    if total_row is not None:
        value = _row_value(frame, total_row, column)
        if value is not None:
            return value
    values = [
        value
        for value in (_row_value(frame, row, column) for row in category_rows)
        if value is not None
    ]
    return float(sum(values)) if values else None

analyze_monthly_sales

analyze_monthly_sales(
    tables: dict[str, Any],
) -> dict[str, Any]

Summarize a monthly activity report's production & sales table.

The main table is the one whose key contains "تولید و فروش"; if no such key exists, the table with the most numeric cells is used. Summary rows are detected by normalized جمع/مجموع labels. A final جمع row is preferred; when it is absent, the جمع فروش داخلی, جمع فروش صادراتی and جمع درآمد ارائه خدمات rows are added together.

Values are reported in million Rials, the unit printed in the source table. prev_month_sales is only populated when the same table exposes a separate previous-month period; :func:monthly_sales_summary fills it by parsing the previous monthly letter.

Parameters:

Name Type Description Default
tables dict[str, Any]

The mapping returned by :func:~iranquant.codal.parser.fetch_and_parse_report (or :func:~iranquant.codal.parser.parse_codal_tables), with Pandas or Polars DataFrames as values.

required

Returns:

Type Description
dict[str, Any]

A dictionary with:

dict[str, Any]
  • table_key (str) — key of the selected table.
dict[str, Any]
  • period_end (str | None) — latest reporting date in the table.
dict[str, Any]
  • current_month_sales (float | None) — one-month sales amount.
dict[str, Any]
  • prev_month_sales (float | None) — previous standalone month, when present in the same table.
dict[str, Any]
  • ytd_sales (float | None) — year-to-date sales amount.
dict[str, Any]
  • prev_ytd_sales (float | None) — prior-year YTD sales amount.
dict[str, Any]
  • mom_change_pct (float | None) — month-over-month percentage.
dict[str, Any]
  • yoy_change_pct (float | None) — year-over-year percentage.
dict[str, Any]
  • summary_df (pandas.DataFrame) — filtered summary rows.

Raises:

Type Description
ValueError

If tables is empty or contains no usable table.

TypeError

If a table value is not a Pandas or Polars DataFrame.

Examples:

>>> letter = iq.monthly_reports("فولاد").Letters[0]
>>> tables = iq.parse_codal_report(letter)
>>> summary = iq.analyze_monthly_sales(tables)
>>> summary["current_month_sales"]
662639489.0
>>> summary["summary_df"][["شرح - نام محصول"]]
Source code in src/iranquant/codal/monthly.py
def analyze_monthly_sales(tables: dict[str, Any]) -> dict[str, Any]:
    """Summarize a monthly activity report's production & sales table.

    The main table is the one whose key contains ``"تولید و فروش"``; if no such
    key exists, the table with the most numeric cells is used.  Summary rows are
    detected by normalized ``جمع``/``مجموع`` labels.  A final ``جمع`` row is
    preferred; when it is absent, the ``جمع فروش داخلی``, ``جمع فروش صادراتی``
    and ``جمع درآمد ارائه خدمات`` rows are added together.

    Values are reported in **million Rials**, the unit printed in the source
    table.  ``prev_month_sales`` is only populated when the same table exposes a
    separate previous-month period; :func:`monthly_sales_summary` fills it by
    parsing the previous monthly letter.

    Args:
        tables: The mapping returned by
            :func:`~iranquant.codal.parser.fetch_and_parse_report` (or
            :func:`~iranquant.codal.parser.parse_codal_tables`), with Pandas or
            Polars DataFrames as values.

    Returns:
        A dictionary with:

        * ``table_key`` (``str``) — key of the selected table.
        * ``period_end`` (``str | None``) — latest reporting date in the table.
        * ``current_month_sales`` (``float | None``) — one-month sales amount.
        * ``prev_month_sales`` (``float | None``) — previous standalone month,
            when present in the same table.
        * ``ytd_sales`` (``float | None``) — year-to-date sales amount.
        * ``prev_ytd_sales`` (``float | None``) — prior-year YTD sales amount.
        * ``mom_change_pct`` (``float | None``) — month-over-month percentage.
        * ``yoy_change_pct`` (``float | None``) — year-over-year percentage.
        * ``summary_df`` (``pandas.DataFrame``) — filtered summary rows.

    Raises:
        ValueError: If ``tables`` is empty or contains no usable table.
        TypeError: If a table value is not a Pandas or Polars DataFrame.

    Examples:
        >>> letter = iq.monthly_reports("فولاد").Letters[0]
        >>> tables = iq.parse_codal_report(letter)
        >>> summary = iq.analyze_monthly_sales(tables)
        >>> summary["current_month_sales"]
        662639489.0
        >>> summary["summary_df"][["شرح - نام محصول"]]
    """

    table_key, frame = _select_table(tables)
    label_column = frame.columns[0]
    labels = frame[label_column].map(_label)

    summary_mask = labels.str.contains("جمع|مجموع", regex=True, na=False)
    summary_df = frame.loc[summary_mask].copy().reset_index(drop=True)

    total_row = _pick_total_row(labels)
    category_rows = [int(str(index)) for index in labels[labels.isin(_CATEGORY_LABELS)].index]

    blocks = _build_blocks(frame)
    current_month, previous_month, current_ytd, previous_ytd = _pick_period_blocks(blocks)

    current_month_sales = (
        _aggregate(frame, total_row, category_rows, current_month.amount_index)
        if current_month is not None
        else None
    )
    prev_month_sales = (
        _aggregate(frame, total_row, category_rows, previous_month.amount_index)
        if previous_month is not None
        else None
    )
    ytd_sales = (
        _aggregate(frame, total_row, category_rows, current_ytd.amount_index)
        if current_ytd is not None
        else None
    )
    prev_ytd_sales = (
        _aggregate(frame, total_row, category_rows, previous_ytd.amount_index)
        if previous_ytd is not None
        else None
    )

    period_end = None
    if current_month is not None and current_month.date is not None:
        period_end = "{:04d}-{:02d}-{:02d}".format(*current_month.date)
    elif current_ytd is not None and current_ytd.date is not None:
        period_end = "{:04d}-{:02d}-{:02d}".format(*current_ytd.date)

    return {
        "table_key": table_key,
        "period_end": period_end,
        "current_month_sales": current_month_sales,
        "prev_month_sales": prev_month_sales,
        "ytd_sales": ytd_sales,
        "prev_ytd_sales": prev_ytd_sales,
        "mom_change_pct": _pct_change(current_month_sales, prev_month_sales),
        "yoy_change_pct": _pct_change(ytd_sales, prev_ytd_sales),
        "summary_df": summary_df,
    }

_letter_period

_letter_period(letter: Any) -> tuple[int, int, int] | None
Source code in src/iranquant/codal/monthly.py
def _letter_period(letter: Any) -> tuple[int, int, int] | None:
    return _parse_date(normalize_persian(str(getattr(letter, "Title", "") or "")))

monthly_sales_summary async

monthly_sales_summary(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]

Fetch and analyze a symbol's latest monthly sales report.

The newest report on page is parsed, and its previous distinct monthly period is parsed too so a true Month-over-Month comparison can be computed.

Parameters:

Name Type Description Default
symbol str

Persian ticker, e.g. "فولاد".

required
page int

One-based Codal result page. Defaults to 1.

1
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient.

None

Returns:

Type Description
dict[str, Any]

The dictionary from :func:analyze_monthly_sales plus

dict[str, Any]

symbol, tracing_no, title, prev_month_tracing_no and a

dict[str, Any]

mom_change_pct derived from the previous month's report.

Raises:

Type Description
ParseError

If Codal returns no HTML monthly reports.

NetworkError

If Codal or the report page cannot be fetched.

ValueError

If the latest report has no usable tables.

Examples:

>>> summary = await monthly_sales_summary("فولاد")
>>> summary["current_month_sales"]
>>> summary["mom_change_pct"]
Source code in src/iranquant/codal/monthly.py
async def monthly_sales_summary(
    symbol: str,
    page: int = 1,
    *,
    client: AsyncHTTPClient | None = None,
) -> dict[str, Any]:
    """Fetch and analyze a symbol's latest monthly sales report.

    The newest report on ``page`` is parsed, and its previous distinct monthly
    period is parsed too so a true Month-over-Month comparison can be computed.

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based Codal result page.  Defaults to ``1``.
        client: Optional shared :class:`~iranquant.core.client.AsyncHTTPClient`.

    Returns:
        The dictionary from :func:`analyze_monthly_sales` plus
        ``symbol``, ``tracing_no``, ``title``, ``prev_month_tracing_no`` and a
        ``mom_change_pct`` derived from the previous month's report.

    Raises:
        ParseError: If Codal returns no HTML monthly reports.
        NetworkError: If Codal or the report page cannot be fetched.
        ValueError: If the latest report has no usable tables.

    Examples:
        >>> summary = await monthly_sales_summary("فولاد")
        >>> summary["current_month_sales"]
        >>> summary["mom_change_pct"]
    """

    reports = await get_monthly_reports(symbol, page=page, client=client)
    letters = [letter for letter in reports.Letters if letter.HasHtml and letter.Url]
    if not letters:
        raise ParseError(f"No HTML monthly report found for {symbol!r}")

    def sort_key(letter: Any) -> tuple[tuple[int, int, int], int]:
        period = _letter_period(letter) or (0, 0, 0)
        return period, int(getattr(letter, "TracingNo", 0) or 0)

    ordered = sorted(letters, key=sort_key, reverse=True)
    latest = ordered[0]
    latest_period = _letter_period(latest)

    tables = await fetch_and_parse_report(latest, client=client)
    result = analyze_monthly_sales(tables)
    result.update(
        {
            "symbol": normalize_persian(symbol),
            "tracing_no": latest.TracingNo,
            "title": latest.Title,
            "page": page,
        }
    )

    previous = next(
        (
            letter
            for letter in ordered[1:]
            if latest_period is None or (_letter_period(letter) or (0, 0, 0)) < latest_period
        ),
        None,
    )
    if previous is None:
        return result

    try:
        previous_tables = await fetch_and_parse_report(previous, client=client)
        previous_result = analyze_monthly_sales(previous_tables)
    except (IranQuantError, ValueError, TypeError):
        return result

    previous_sales = previous_result.get("current_month_sales")
    if isinstance(previous_sales, (int, float)):
        result["prev_month_sales"] = float(previous_sales)
        result["prev_month_tracing_no"] = previous.TracingNo
        current_sales = result.get("current_month_sales")
        result["mom_change_pct"] = _pct_change(
            float(current_sales) if isinstance(current_sales, (int, float)) else None,
            float(previous_sales),
        )
    return result