Skip to content

Top-level API

The iranquant package re-exports the synchronous helpers, the AsyncIranQuant client, the IranQuant facade, exceptions, models and quant functions.

import iranquant as iq

iq.history("فولاد")
iq.AsyncIranQuant()
iq.IranQuant()
iq.MarketScreener
iq.MarketWatcher

iranquant

iranquant — async-first TSETMC / Codal market data client.

Synchronous module-level helpers are the easiest entry point::

import iranquant as iq
df = iq.history("فولاد")

Inside an async application use :class:AsyncIranQuant::

async with AsyncIranQuant() as iq:
    df = await iq.history("فولاد")

DEFAULT_TIMEOUT module-attribute

DEFAULT_TIMEOUT = 30.0

MAX_CONCURRENCY module-attribute

MAX_CONCURRENCY = 10

OVERALL_INDEX_CODE module-attribute

OVERALL_INDEX_CODE = '32097828799138957'

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

Engine module-attribute

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

AdjustMode module-attribute

AdjustMode = Literal['none', 'all', 'capital_only']

__version__ module-attribute

__version__ = '0.1.0'

T module-attribute

T = TypeVar('T')

__all__ module-attribute

__all__ = [
    "AsyncHTTPClient",
    "AsyncIranQuant",
    "CodalLetter",
    "CodalSearchResponse",
    "DataFrame",
    "Engine",
    "IranQuant",
    "IranQuantConfig",
    "IranQuantConnectionError",
    "IranQuantError",
    "MarketEvent",
    "MarketScreener",
    "MarketWatcher",
    "NetworkError",
    "ParseError",
    "SymbolNotFoundError",
    "__version__",
    "analyze_monthly_sales",
    "client_type",
    "codal_report",
    "codal_search",
    "compute_money_flow",
    "compute_movement_power",
    "detect_swing_legs",
    "fetch_and_parse_report",
    "financial_statements",
    "full_history",
    "get_financial_statements",
    "get_inscode",
    "get_monthly_reports",
    "history",
    "index_history",
    "indices_live",
    "intraday_trades",
    "is_market_open",
    "market_watch",
    "money_flow",
    "monthly_reports",
    "monthly_sales_summary",
    "movement_power",
    "order_book",
    "parse_codal_report",
    "search",
    "search_codal",
]

IranQuantConfig dataclass

IranQuantConfig(
    verify_ssl: bool = (
        lambda: _env_flag("IRANQUANT_VERIFY_SSL", True)
    )(),
    allow_tls_fallback: bool = (
        lambda: _env_flag(
            "IRANQUANT_ALLOW_TLS_FALLBACK", True
        )
    )(),
)

Transport security policy.

Values are read from the environment when omitted, and explicit keyword arguments take precedence.

Parameters:

Name Type Description Default
verify_ssl bool

Verify upstream TLS certificates. Defaults to IRANQUANT_VERIFY_SSL or True.

(lambda: _env_flag('IRANQUANT_VERIFY_SSL', True))()
allow_tls_fallback bool

Retry once over an unverified transport when certificate verification fails. Defaults to IRANQUANT_ALLOW_TLS_FALLBACK or True.

(lambda: _env_flag('IRANQUANT_ALLOW_TLS_FALLBACK', True))()

Examples:

>>> IranQuantConfig(allow_tls_fallback=False).allow_tls_fallback
False

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()

IranQuantConnectionError

Bases: NetworkError

Raised when TLS verification fails and fallback is disabled.

Inherits from :class:NetworkError, so existing handlers keep working, but is excluded from retry loops because the failure is deterministic.

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

NetworkError

Bases: IranQuantError

Raised when a remote endpoint cannot be reached or returns an error.

Wraps connection failures, timeouts, HTTP error statuses and exhausted retries from TSETMC or Codal.

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.

SymbolNotFoundError

Bases: IranQuantError

Raised when a symbol cannot be resolved to a TSETMC instrument code.

Examples:

>>> iq.get_inscode("نماد_ناموجود")
Traceback (most recent call last):
...
iranquant.exceptions.SymbolNotFoundError: Symbol not found: 'نماد_ناموجود'

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}")

MarketScreener

MarketScreener(frame: DataFrame | None = None)

Vectorized filters over a MarketWatch (or batch) DataFrame.

Every filter accepts an optional alternative frame; when omitted the frame passed to the constructor is used. Results preserve the input engine type (Pandas in, Pandas out; Polars in, Polars out) and are reset to a clean index.

Parameters:

Name Type Description Default
frame DataFrame | None

An optional MarketWatch frame from :func:iranquant.market_watch (or any frame with the same columns). Filters may instead receive the frame directly, so both MarketScreener(frame).filter_buy_queue() and MarketScreener().filter_buy_queue(frame) are equivalent.

None

Raises:

Type Description
ValueError

If a filter runs without a bound or call-time frame.

TypeError

If the selected frame is neither a Pandas nor a Polars DataFrame (raised lazily when a filter runs).

Examples:

>>> screener = MarketScreener(iq.market_watch())
>>> screener.filter_buy_queue()[["symbol", "close", "tmax"]]
>>> MarketScreener().filter_buy_queue(iq.market_watch()).head()
Source code in src/iranquant/quant/screener.py
def __init__(self, frame: DataFrame | None = None) -> None:
    self._frame = frame

filter_buy_queue

filter_buy_queue(
    frame: DataFrame | None = None,
) -> DataFrame

Symbols locked at tmax with a positive buy-queue volume.

The mask is (tmax > 0) & (close >= tmax) & (sum(zmd) > 0). The buy-queue volume is the sum of zmd (bid volume) across all order-book levels.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or tmax is missing.

Examples:

>>> locked = screener.filter_buy_queue()
>>> locked[["symbol", "close", "tmax"]].head()
Source code in src/iranquant/quant/screener.py
def filter_buy_queue(self, frame: DataFrame | None = None) -> DataFrame:
    """Symbols locked at ``tmax`` with a positive buy-queue volume.

    The mask is ``(tmax > 0) & (close >= tmax) & (sum(zmd) > 0)``.  The
    buy-queue volume is the sum of ``zmd`` (bid volume) across all order-book
    levels.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``tmax`` is missing.

    Examples:
        >>> locked = screener.filter_buy_queue()
        >>> locked[["symbol", "close", "tmax"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "tmax"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    tmax = source["tmax"].astype(float)
    buy_volume = self._queue_volume(source, "buy")
    mask = (tmax > 0) & (close >= tmax) & (buy_volume > 0)
    return self._restore(original, source.loc[mask])

filter_sell_queue

filter_sell_queue(
    frame: DataFrame | None = None,
) -> DataFrame

Symbols locked at tmin with a positive sell-queue volume.

The mask is (tmin > 0) & (close <= tmin) & (sum(zmo) > 0). The sell-queue volume is the sum of zmo (ask volume) across all order-book levels.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or tmin is missing.

Examples:

>>> locked = screener.filter_sell_queue()
>>> locked[["symbol", "close", "tmin"]].head()
Source code in src/iranquant/quant/screener.py
def filter_sell_queue(self, frame: DataFrame | None = None) -> DataFrame:
    """Symbols locked at ``tmin`` with a positive sell-queue volume.

    The mask is ``(tmin > 0) & (close <= tmin) & (sum(zmo) > 0)``.  The
    sell-queue volume is the sum of ``zmo`` (ask volume) across all
    order-book levels.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``tmin`` is missing.

    Examples:
        >>> locked = screener.filter_sell_queue()
        >>> locked[["symbol", "close", "tmin"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "tmin"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    tmin = source["tmin"].astype(float)
    sell_volume = self._queue_volume(source, "sell")
    mask = (tmin > 0) & (close <= tmin) & (sell_volume > 0)
    return self._restore(original, source.loc[mask])

filter_positive_tick_surge

filter_positive_tick_surge(
    frame: DataFrame | None = None,
    min_diff_pct: float = 1.5,
) -> DataFrame

Symbols whose last price exceeds the final price by min_diff_pct.

The mask is ((close - final_price) / max(final_price, 1)) * 100 >= min_diff_pct.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None
min_diff_pct float

Minimum percentage gap between the last traded price and the closing price. Defaults to 1.5.

1.5

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or final_price is missing.

Examples:

>>> surges = screener.filter_positive_tick_surge(min_diff_pct=1.5)
>>> surges[["symbol", "close", "final_price"]].head()
Source code in src/iranquant/quant/screener.py
def filter_positive_tick_surge(
    self,
    frame: DataFrame | None = None,
    min_diff_pct: float = 1.5,
) -> DataFrame:
    """Symbols whose last price exceeds the final price by ``min_diff_pct``.

    The mask is
    ``((close - final_price) / max(final_price, 1)) * 100 >= min_diff_pct``.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.
        min_diff_pct: Minimum percentage gap between the last traded price
            and the closing price.  Defaults to ``1.5``.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``final_price`` is missing.

    Examples:
        >>> surges = screener.filter_positive_tick_surge(min_diff_pct=1.5)
        >>> surges[["symbol", "close", "final_price"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "final_price"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    final_price = source["final_price"].astype(float)
    diff_pct = ((close - final_price) / final_price.clip(lower=1.0)) * 100.0
    mask = diff_pct >= min_diff_pct
    return self._restore(original, source.loc[mask])

scan_market

scan_market(
    custom_predicate: Callable[
        [DataFrame], DataFrame | Series
    ],
    frame: DataFrame | None = None,
) -> DataFrame

Apply a custom Pandas predicate/mask and restore the engine type.

Parameters:

Name Type Description Default
custom_predicate Callable[[DataFrame], DataFrame | Series]

A callable that receives the frame as a :class:pandas.DataFrame and returns either a filtered DataFrame or a boolean Series mask. NaN mask values are treated as False.

required
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The filtered rows converted back to the input engine.

Raises:

Type Description
TypeError

If custom_predicate returns neither a DataFrame nor a Series.

Examples:

>>> high_volume = screener.scan_market(
...     lambda df: df["volume"] > df["volume"].median()
... )
>>> high_volume[["symbol", "volume"]].sort_values("volume").tail()
Source code in src/iranquant/quant/screener.py
def scan_market(
    self,
    custom_predicate: Callable[[pd.DataFrame], pd.DataFrame | pd.Series],
    frame: DataFrame | None = None,
) -> DataFrame:
    """Apply a custom Pandas predicate/mask and restore the engine type.

    Args:
        custom_predicate: A callable that receives the frame as a
            :class:`pandas.DataFrame` and returns either a filtered
            DataFrame or a boolean Series mask.  ``NaN`` mask values are
            treated as ``False``.
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The filtered rows converted back to the input engine.

    Raises:
        TypeError: If ``custom_predicate`` returns neither a DataFrame nor
            a Series.

    Examples:
        >>> high_volume = screener.scan_market(
        ...     lambda df: df["volume"] > df["volume"].median()
        ... )
        >>> high_volume[["symbol", "volume"]].sort_values("volume").tail()
    """

    original, source = self._source(frame)
    result = custom_predicate(source)
    if isinstance(result, pd.DataFrame):
        filtered = result
    elif isinstance(result, pd.Series):
        mask = result.fillna(False).astype(bool)
        filtered = source.loc[mask]
    else:
        raise TypeError("custom_predicate must return a pandas DataFrame or boolean Series")
    return self._restore(original, filtered)

MarketEvent dataclass

MarketEvent(
    event_type: str,
    ins_code: str,
    symbol: str,
    timestamp: datetime,
    data: dict[str, Any] = dict(),
)

A structured market state-change event.

Attributes:

Name Type Description
event_type str

One of BUY_QUEUE_LOCKED, BUY_QUEUE_BROKEN, SELL_QUEUE_LOCKED, SELL_QUEUE_BROKEN or VOLUME_SPIKE.

ins_code str

TSETMC instrument code (empty when the snapshot lacks it).

symbol str

Persian ticker from MarketWatch.

timestamp datetime

When the event was detected (UTC unless supplied).

data dict[str, Any]

Event-specific payload. Queue events include close, tmax, tmin, buy_queue_volume, sell_queue_volume and volume; VOLUME_SPIKE includes volume, delta, avg_delta and close.

Examples:

>>> event = MarketEvent(
...     event_type=BUY_QUEUE_LOCKED,
...     ins_code="46348559193224090",
...     symbol="فولاد",
...     timestamp=dt.datetime.now(dt.timezone.utc),
...     data={"close": 4150.0, "tmax": 4150.0},
... )
>>> event.symbol
'فولاد'

MarketWatcher

MarketWatcher(client: AsyncHTTPClient | None = None)

Poll MarketWatch and emit queue/volume transitions.

process_snapshot is synchronous and stateful so it can also be used in backtests or tests without any network access. The state machine emits:

  • BUY_QUEUE_LOCKED / BUY_QUEUE_BROKEN when close >= tmax with a positive buy queue starts or stops.
  • SELL_QUEUE_LOCKED / SELL_QUEUE_BROKEN when close <= tmin with a positive sell queue starts or stops.
  • VOLUME_SPIKE when the per-poll volume increase is at least 1.8x the running average increase.

Parameters:

Name Type Description Default
client AsyncHTTPClient | None

Optional shared :class:~iranquant.core.client.AsyncHTTPClient. When omitted, :meth:watch creates and owns a client itself, or :meth:__aenter__ creates one for the context manager.

None

Examples:

>>> watcher = MarketWatcher()
>>> @watcher.on_event(BUY_QUEUE_LOCKED)
... def on_lock(event: MarketEvent) -> None:
...     print(event.symbol, event.data["buy_queue_volume"])
>>> async for event in watcher.watch(interval=5.0, symbols=["فولاد"]):
...     print(event.event_type)
Source code in src/iranquant/stream/watcher.py
def __init__(self, client: AsyncHTTPClient | None = None) -> None:
    self._client = client
    self._owns_client = False
    self._states: dict[str, _SymbolState] = {}
    self._listeners: dict[str, list[EventCallback]] = {}

on_event

on_event(
    event_type: str,
) -> Callable[[EventCallback], EventCallback]

Register a sync or async callback for an event type ("*" = all).

Parameters:

Name Type Description Default
event_type str

A specific event constant or "*" to receive every event.

required

Returns:

Type Description
Callable[[EventCallback], EventCallback]

A decorator that registers the callback and returns it unchanged,

Callable[[EventCallback], EventCallback]

so the method can be used as @watcher.on_event(...).

Examples:

>>> @watcher.on_event("*")
... async def log(event: MarketEvent) -> None:
...     print(event.event_type, event.symbol)
Source code in src/iranquant/stream/watcher.py
def on_event(
    self,
    event_type: str,
) -> Callable[[EventCallback], EventCallback]:
    """Register a sync or async callback for an event type (``"*"`` = all).

    Args:
        event_type: A specific event constant or ``"*"`` to receive every
            event.

    Returns:
        A decorator that registers the callback and returns it unchanged,
        so the method can be used as ``@watcher.on_event(...)``.

    Examples:
        >>> @watcher.on_event("*")
        ... async def log(event: MarketEvent) -> None:
        ...     print(event.event_type, event.symbol)
    """

    def decorator(callback: EventCallback) -> EventCallback:
        self._listeners.setdefault(event_type, []).append(callback)
        return callback

    return decorator

dispatch async

dispatch(events: Iterable[MarketEvent]) -> None

Invoke every matching listener for each event.

Sync callbacks are called directly; awaitable results are awaited. Listeners registered for "*" run after type-specific listeners.

Parameters:

Name Type Description Default
events Iterable[MarketEvent]

Events to deliver, typically returned by :meth:process_snapshot.

required

Examples:

>>> await watcher.dispatch(watcher.process_snapshot(snapshot))
Source code in src/iranquant/stream/watcher.py
async def dispatch(self, events: Iterable[MarketEvent]) -> None:
    """Invoke every matching listener for each event.

    Sync callbacks are called directly; awaitable results are awaited.
    Listeners registered for ``"*"`` run after type-specific listeners.

    Args:
        events: Events to deliver, typically returned by
            :meth:`process_snapshot`.

    Examples:
        >>> await watcher.dispatch(watcher.process_snapshot(snapshot))
    """
    for event in events:
        callbacks = [
            *self._listeners.get(event.event_type, []),
            *self._listeners.get("*", []),
        ]
        for callback in callbacks:
            result = callback(event)
            if inspect.isawaitable(result):
                await cast(Awaitable[Any], result)

reset

reset() -> None

Forget all per-symbol state so the next snapshot starts fresh.

Does not remove registered listeners.

Source code in src/iranquant/stream/watcher.py
def reset(self) -> None:
    """Forget all per-symbol state so the next snapshot starts fresh.

    Does not remove registered listeners.
    """
    self._states.clear()

process_snapshot

process_snapshot(
    snapshot: DataFrame,
    *,
    timestamp: datetime | None = None,
    symbols: list[str] | None = None,
) -> list[MarketEvent]

Update internal state from a MarketWatch frame and return events.

No I/O is performed; the result is deterministic for a given snapshot sequence, so this is safe to use in backtests and unit tests.

Parameters:

Name Type Description Default
snapshot DataFrame

A MarketWatch frame (from :func:iranquant.market_watch) with at least close, tmax, tmin and volume. ins_code, symbol and order_book are used when present.

required
timestamp datetime | None

Timestamp attached to emitted events. Defaults to the current UTC time.

None
symbols list[str] | None

Optional allow-list. Numeric strings are matched against ins_code; other strings are normalized and matched against symbol.

None

Returns:

Type Description
list[MarketEvent]

The newly triggered events in snapshot order. An empty frame

list[MarketEvent]

returns an empty list without mutating state.

Examples:

>>> events = watcher.process_snapshot(iq.market_watch())
>>> [event.event_type for event in events]
['BUY_QUEUE_LOCKED']
Source code in src/iranquant/stream/watcher.py
def process_snapshot(
    self,
    snapshot: DataFrame,
    *,
    timestamp: dt.datetime | None = None,
    symbols: list[str] | None = None,
) -> list[MarketEvent]:
    """Update internal state from a MarketWatch frame and return events.

    No I/O is performed; the result is deterministic for a given snapshot
    sequence, so this is safe to use in backtests and unit tests.

    Args:
        snapshot: A MarketWatch frame (from
            :func:`iranquant.market_watch`) with at least ``close``,
            ``tmax``, ``tmin`` and ``volume``.  ``ins_code``, ``symbol``
            and ``order_book`` are used when present.
        timestamp: Timestamp attached to emitted events.  Defaults to the
            current UTC time.
        symbols: Optional allow-list.  Numeric strings are matched against
            ``ins_code``; other strings are normalized and matched against
            ``symbol``.

    Returns:
        The newly triggered events in snapshot order.  An empty frame
        returns an empty list without mutating state.

    Examples:
        >>> events = watcher.process_snapshot(iq.market_watch())
        >>> [event.event_type for event in events]
        ['BUY_QUEUE_LOCKED']
    """

    frame = to_pandas(snapshot)
    if frame.empty:
        return []

    wanted_codes = {str(symbol) for symbol in symbols or [] if str(symbol).isdigit()}
    wanted_symbols = {
        normalize_persian(symbol) for symbol in symbols or [] if not str(symbol).isdigit()
    }
    moment = timestamp or dt.datetime.now(dt.timezone.utc)

    events: list[MarketEvent] = []
    for _, row in frame.iterrows():
        ins_code = str(row.get("ins_code", "") or "")
        symbol = str(row.get("symbol", "") or "")
        if symbols is not None:
            matches = ins_code in wanted_codes or normalize_persian(symbol) in wanted_symbols
            if not matches:
                continue

        key = ins_code or symbol
        if not key:
            continue

        close = _to_float(row.get("close"))
        tmax = _to_float(row.get("tmax"))
        tmin = _to_float(row.get("tmin"))
        volume = _to_float(row.get("volume"))
        buy_volume = _book_volume(row.get("order_book"), "buy")
        sell_volume = _book_volume(row.get("order_book"), "sell")

        buy_locked = tmax > 0 and close >= tmax and buy_volume > 0
        sell_locked = tmin > 0 and close <= tmin and sell_volume > 0

        state = self._states.get(key)
        is_new = state is None
        if state is None:
            state = _SymbolState()
            self._states[key] = state

        base_data: dict[str, Any] = {
            "close": close,
            "tmax": tmax,
            "tmin": tmin,
            "buy_queue_volume": buy_volume,
            "sell_queue_volume": sell_volume,
            "volume": volume,
        }

        if buy_locked and not state.buy_locked:
            events.append(
                MarketEvent(BUY_QUEUE_LOCKED, ins_code, symbol, moment, dict(base_data))
            )
        elif state.buy_locked and not buy_locked:
            events.append(
                MarketEvent(BUY_QUEUE_BROKEN, ins_code, symbol, moment, dict(base_data))
            )

        if sell_locked and not state.sell_locked:
            events.append(
                MarketEvent(SELL_QUEUE_LOCKED, ins_code, symbol, moment, dict(base_data))
            )
        elif state.sell_locked and not sell_locked:
            events.append(
                MarketEvent(SELL_QUEUE_BROKEN, ins_code, symbol, moment, dict(base_data))
            )

        if not is_new and state.last_volume is not None:
            delta = volume - state.last_volume
            if delta < 0:
                # A new trading day/reset: restart the spike baseline.
                state.avg_delta = 0.0
                state.delta_count = 0
            elif delta > 0:
                previous_average = state.avg_delta
                if state.delta_count > 0 and delta >= 1.8 * previous_average:
                    events.append(
                        MarketEvent(
                            VOLUME_SPIKE,
                            ins_code,
                            symbol,
                            moment,
                            {
                                "volume": volume,
                                "delta": delta,
                                "avg_delta": previous_average,
                                "close": close,
                            },
                        )
                    )
                state.delta_count += 1
                state.avg_delta = (
                    (previous_average * (state.delta_count - 1)) + delta
                ) / state.delta_count

        state.buy_locked = buy_locked
        state.sell_locked = sell_locked
        state.last_volume = volume
        state.last_close = close

    return events

watch async

watch(
    interval: float = 5.0,
    symbols: list[str] | None = None,
    only_market_hours: bool = False,
) -> AsyncGenerator[MarketEvent, None]

Poll MarketWatch forever, yielding state-change events.

Each iteration fetches a full market snapshot, updates the state machine, dispatches callbacks, yields every new event, then sleeps. IranQuant errors during a poll are swallowed and retried on the next interval.

Parameters:

Name Type Description Default
interval float

Seconds between full MarketWatch polls. Must be positive. Defaults to 5.0.

5.0
symbols list[str] | None

Optional allow-list passed to :meth:process_snapshot.

None
only_market_hours bool

When True, skip polling outside Saturday-Wednesday 09:00-12:30 Tehran time. Defaults to False.

False

Yields:

Type Description
AsyncGenerator[MarketEvent, None]

class:MarketEvent objects as state transitions occur.

Raises:

Type Description
ValueError

If interval <= 0.

Examples:

>>> async for event in watcher.watch(interval=3.0, symbols=["فولاد"]):
...     print(event.event_type, event.symbol)
Source code in src/iranquant/stream/watcher.py
async def watch(
    self,
    interval: float = 5.0,
    symbols: list[str] | None = None,
    only_market_hours: bool = False,
) -> AsyncGenerator[MarketEvent, None]:
    """Poll MarketWatch forever, yielding state-change events.

    Each iteration fetches a full market snapshot, updates the state
    machine, dispatches callbacks, yields every new event, then sleeps.
    IranQuant errors during a poll are swallowed and retried on the next
    interval.

    Args:
        interval: Seconds between full MarketWatch polls.  Must be positive.
            Defaults to ``5.0``.
        symbols: Optional allow-list passed to :meth:`process_snapshot`.
        only_market_hours: When ``True``, skip polling outside
            Saturday-Wednesday 09:00-12:30 Tehran time.  Defaults to
            ``False``.

    Yields:
        :class:`MarketEvent` objects as state transitions occur.

    Raises:
        ValueError: If ``interval <= 0``.

    Examples:
        >>> async for event in watcher.watch(interval=3.0, symbols=["فولاد"]):
        ...     print(event.event_type, event.symbol)
    """

    if interval <= 0:
        raise ValueError("interval must be positive")

    owns_client = self._client is None
    if self._client is None:
        self._client = AsyncHTTPClient()
    client = self._client

    try:
        while True:
            if only_market_hours and not is_market_open():
                await asyncio.sleep(interval)
                continue
            try:
                snapshot = await get_market_watch(client)
            except IranQuantError:
                await asyncio.sleep(interval)
                continue

            events = self.process_snapshot(snapshot, symbols=symbols)
            await self.dispatch(events)
            for event in events:
                yield event
            await asyncio.sleep(interval)
    finally:
        if owns_client:
            await client.aclose()
            self._client = None

__aenter__ async

__aenter__() -> MarketWatcher

Enter the async context manager, creating a client if needed.

Returns:

Type Description
MarketWatcher

self so the watcher can be used with async with.

Source code in src/iranquant/stream/watcher.py
async def __aenter__(self) -> MarketWatcher:
    """Enter the async context manager, creating a client if needed.

    Returns:
        ``self`` so the watcher can be used with ``async with``.
    """
    if self._client is None:
        self._client = AsyncHTTPClient()
        self._owns_client = True
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close the owned HTTP client when leaving the context manager.

Source code in src/iranquant/stream/watcher.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close the owned HTTP client when leaving the context manager."""
    if self._owns_client and self._client is not None:
        await self._client.aclose()
        self._client = None
        self._owns_client = False

AsyncIranQuant

AsyncIranQuant(
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    proxy: str | None = None,
    config: IranQuantConfig | None = None,
)

Async client owning a single pooled HTTP transport.

Use this class when your application already runs an event loop. It keeps one :class:~iranquant.core.client.AsyncHTTPClient alive for all requests, which reuses connections and applies a shared concurrency limit.

Every method is a thin async wrapper around the corresponding function in :mod:iranquant.market, :mod:iranquant.codal or :mod:iranquant.quant. Results default to Pandas; pass engine="polars" for Polars.

Examples:

>>> import iranquant as iq
>>> async with iq.AsyncIranQuant(timeout=15.0) as client:
...     frame = await client.history("فولاد")
...     market = await client.market_watch()

Create the async client.

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 simultaneous requests. Defaults to :data:iranquant.config.MAX_CONCURRENCY (10).

MAX_CONCURRENCY
proxy str | None

Optional explicit proxy URL. Environment proxies are ignored unless this is supplied.

None
config IranQuantConfig | None

TLS and fallback policy. Defaults to :class:~iranquant.config.IranQuantConfig, which reads IRANQUANT_VERIFY_SSL and IRANQUANT_ALLOW_TLS_FALLBACK.

None

Examples:

>>> client = AsyncIranQuant(proxy="http://127.0.0.1:9090")
>>> strict = AsyncIranQuant(
...     config=IranQuantConfig(allow_tls_fallback=False)
... )
Source code in src/iranquant/__init__.py
def __init__(
    self,
    *,
    timeout: float = DEFAULT_TIMEOUT,
    max_concurrency: int = MAX_CONCURRENCY,
    proxy: str | None = None,
    config: IranQuantConfig | None = None,
) -> None:
    """Create the async client.

    Args:
        timeout: Per-request timeout in seconds.  Defaults to
            :data:`iranquant.config.DEFAULT_TIMEOUT` (30 s).
        max_concurrency: Maximum simultaneous requests.  Defaults to
            :data:`iranquant.config.MAX_CONCURRENCY` (10).
        proxy: Optional explicit proxy URL.  Environment proxies are
            ignored unless this is supplied.
        config: TLS and fallback policy. Defaults to
            :class:`~iranquant.config.IranQuantConfig`, which reads
            ``IRANQUANT_VERIFY_SSL`` and
            ``IRANQUANT_ALLOW_TLS_FALLBACK``.

    Examples:
        >>> client = AsyncIranQuant(proxy="http://127.0.0.1:9090")
        >>> strict = AsyncIranQuant(
        ...     config=IranQuantConfig(allow_tls_fallback=False)
        ... )
    """
    self._client = AsyncHTTPClient(
        timeout=timeout,
        max_concurrency=max_concurrency,
        proxy=proxy,
        config=config,
    )

client property

client: AsyncHTTPClient

The underlying :class:~iranquant.core.client.AsyncHTTPClient.

close async

close() -> None

Close the underlying HTTP transports.

Called automatically when used as an async context manager.

Source code in src/iranquant/__init__.py
async def close(self) -> None:
    """Close the underlying HTTP transports.

    Called automatically when used as an async context manager.
    """
    await self._client.aclose()

__aenter__ async

__aenter__() -> AsyncIranQuant

Return self for use with async with.

Source code in src/iranquant/__init__.py
async def __aenter__(self) -> AsyncIranQuant:
    """Return ``self`` for use with ``async with``."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Close the HTTP transports on context exit.

Source code in src/iranquant/__init__.py
async def __aexit__(self, *exc_info: object) -> None:
    """Close the HTTP transports on context exit."""
    await self.close()

resolve async

resolve(symbol_or_inscode: str | int) -> str

Resolve a symbol name or numeric instrument code to an insCode.

Numeric input (int or an all-digit string, including Persian digits) is returned unchanged without any network request.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker ("فولاد") or a numeric instrument code (46348559193224090).

required

Returns:

Type Description
str

The numeric insCode as a string.

Raises:

Type Description
SymbolNotFoundError

If a symbol name cannot be matched.

NetworkError

If the lookup request fails.

ParseError

If the search response is malformed.

Examples:

>>> await client.resolve("فولاد")
'46348559193224090'
>>> await client.resolve(46348559193224090)
'46348559193224090'
Source code in src/iranquant/__init__.py
async def resolve(self, symbol_or_inscode: str | int) -> str:
    """Resolve a symbol name or numeric instrument code to an ``insCode``.

    Numeric input (``int`` or an all-digit string, including Persian digits)
    is returned unchanged without any network request.

    Args:
        symbol_or_inscode: Persian ticker (``"فولاد"``) or a numeric
            instrument code (``46348559193224090``).

    Returns:
        The numeric ``insCode`` as a string.

    Raises:
        SymbolNotFoundError: If a symbol name cannot be matched.
        NetworkError: If the lookup request fails.
        ParseError: If the search response is malformed.

    Examples:
        >>> await client.resolve("فولاد")
        '46348559193224090'
        >>> await client.resolve(46348559193224090)
        '46348559193224090'
    """
    code = _as_ins_code(symbol_or_inscode)
    if code is not None:
        return code
    return await _symbol.get_inscode(self._client, str(symbol_or_inscode))

search async

search(
    query: str, *, engine: Engine = "pandas"
) -> DataFrame

Search TSETMC instruments by ticker or company name.

Parameters:

Name Type Description Default
query str

Symbol or company-name fragment, e.g. "فولاد".

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per match with ins_code, symbol, company_name,

DataFrame

isin, shares, flow, board, last_date and

DataFrame

last_date_jdate.

Raises:

Type Description
NetworkError

If TSETMC cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> results = await client.search("فولاد")
>>> results.iloc[0]["symbol"]
'فولاد'
Source code in src/iranquant/__init__.py
async def search(self, query: str, *, engine: Engine = "pandas") -> DataFrame:
    """Search TSETMC instruments by ticker or company name.

    Args:
        query: Symbol or company-name fragment, e.g. ``"فولاد"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        One row per match with ``ins_code``, ``symbol``, ``company_name``,
        ``isin``, ``shares``, ``flow``, ``board``, ``last_date`` and
        ``last_date_jdate``.

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

    Examples:
        >>> results = await client.search("فولاد")
        >>> results.iloc[0]["symbol"]
        'فولاد'
    """
    items = await _symbol.search_symbol(self._client, query)
    return to_dataframe(
        [_symbol.instrument_to_dict(item) for item in items],
        engine,
    )

history async

history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch backward-adjusted daily OHLCV history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date (datetime.date), jdate (str),

DataFrame

open, high, low, close, final_price,

DataFrame

prev_price, volume, value and trades (all

DataFrame

float), sorted by date.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If TSETMC cannot be reached.

ParseError

If the payload is malformed.

ValueError

If adjust or engine is unsupported.

Examples:

>>> frame = await client.history("فولاد", adjust="all")
>>> frame[["jdate", "close", "final_price"]].tail()
Source code in src/iranquant/__init__.py
async def history(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch backward-adjusted daily OHLCV history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date`` (``datetime.date``), ``jdate`` (``str``),
        ``open``, ``high``, ``low``, ``close``, ``final_price``,
        ``prev_price``, ``volume``, ``value`` and ``trades`` (all
        ``float``), sorted by date.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If TSETMC cannot be reached.
        ParseError: If the payload is malformed.
        ValueError: If ``adjust`` or ``engine`` is unsupported.

    Examples:
        >>> frame = await client.history("فولاد", adjust="all")
        >>> frame[["jdate", "close", "final_price"]].tail()
    """
    ins_code = await self.resolve(symbol_or_inscode)
    return await _history.get_daily_history(
        self._client,
        ins_code,
        adjust=adjust,
        engine=engine,
    )

full_history async

full_history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch daily OHLCV merged with retail/institutional client-type data.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The eleven :meth:history columns plus buy_I_Volume,

DataFrame

buy_N_Volume, buy_I_Value, buy_N_Value,

DataFrame

buy_N_Count, buy_I_Count, sell_I_Volume,

DataFrame

sell_N_Volume, sell_I_Value, sell_N_Value,

DataFrame

sell_N_Count and sell_I_Count, outer-joined on date.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If either request fails.

ParseError

If either payload is malformed.

Examples:

>>> frame = await client.full_history("فولاد")
>>> frame[["jdate", "buy_I_Volume", "sell_N_Count"]].tail()
Source code in src/iranquant/__init__.py
async def full_history(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch daily OHLCV merged with retail/institutional client-type data.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The eleven :meth:`history` columns plus ``buy_I_Volume``,
        ``buy_N_Volume``, ``buy_I_Value``, ``buy_N_Value``,
        ``buy_N_Count``, ``buy_I_Count``, ``sell_I_Volume``,
        ``sell_N_Volume``, ``sell_I_Value``, ``sell_N_Value``,
        ``sell_N_Count`` and ``sell_I_Count``, outer-joined on ``date``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If either request fails.
        ParseError: If either payload is malformed.

    Examples:
        >>> frame = await client.full_history("فولاد")
        >>> frame[["jdate", "buy_I_Volume", "sell_N_Count"]].tail()
    """
    ins_code = await self.resolve(symbol_or_inscode)
    return await _history.get_full_history(
        self._client,
        ins_code,
        adjust=adjust,
        engine=engine,
    )

client_type async

client_type(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch retail/institutional (حقیقی/حقوقی) history only.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date, jdate, buy_I_Volume, buy_N_Volume,

DataFrame

buy_I_Value, buy_N_Value, buy_N_Count, buy_I_Count,

DataFrame

sell_I_Volume, sell_N_Volume, sell_I_Value,

DataFrame

sell_N_Value, sell_N_Count and sell_I_Count.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the payload is malformed.

Examples:

>>> frame = await client.client_type("فولاد")
>>> frame[["date", "buy_I_Volume", "sell_I_Volume"]].tail()
Source code in src/iranquant/__init__.py
async def client_type(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch retail/institutional (حقیقی/حقوقی) history only.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date``, ``jdate``, ``buy_I_Volume``, ``buy_N_Volume``,
        ``buy_I_Value``, ``buy_N_Value``, ``buy_N_Count``, ``buy_I_Count``,
        ``sell_I_Volume``, ``sell_N_Volume``, ``sell_I_Value``,
        ``sell_N_Value``, ``sell_N_Count`` and ``sell_I_Count``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the payload is malformed.

    Examples:
        >>> frame = await client.client_type("فولاد")
        >>> frame[["date", "buy_I_Volume", "sell_I_Volume"]].tail()
    """
    ins_code = await self.resolve(symbol_or_inscode)
    return await _history.get_client_type_history(
        self._client,
        ins_code,
        engine=engine,
    )

market_watch async

market_watch(*, engine: Engine = 'pandas') -> DataFrame

Fetch the live market-wide snapshot in one request.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per symbol with ins_code, symbol, company_name,

DataFrame

eps, pe, open, high, low, close,

DataFrame

final_price, prev_price, volume, value, trades,

DataFrame

tmax, tmin, total_shares and order_book.

Raises:

Type Description
NetworkError

If the MarketWatch endpoint cannot be reached.

ParseError

If the response body is not valid JSON.

ValidationError

If the payload does not match the schema.

Examples:

>>> market = await client.market_watch()
>>> market[["symbol", "close", "tmax"]].head()
Source code in src/iranquant/__init__.py
async def market_watch(self, *, engine: Engine = "pandas") -> DataFrame:
    """Fetch the live market-wide snapshot in one request.

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

    Returns:
        One row per symbol with ``ins_code``, ``symbol``, ``company_name``,
        ``eps``, ``pe``, ``open``, ``high``, ``low``, ``close``,
        ``final_price``, ``prev_price``, ``volume``, ``value``, ``trades``,
        ``tmax``, ``tmin``, ``total_shares`` and ``order_book``.

    Raises:
        NetworkError: If the MarketWatch endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.
        pydantic.ValidationError: If the payload does not match the schema.

    Examples:
        >>> market = await client.market_watch()
        >>> market[["symbol", "close", "tmax"]].head()
    """
    return await _live.get_market_watch(self._client, engine=engine)

order_book async

order_book(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch the best-limit order book (levels 1..5).

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns n, qmd, zmd, pmd, pmo, zmo and

DataFrame

qmo sorted by level.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the response body is not valid JSON.

Examples:

>>> book = await client.order_book("فولاد")
>>> book[["pmd", "zmd", "pmo", "zmo"]].head()
Source code in src/iranquant/__init__.py
async def order_book(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch the best-limit order book (levels 1..5).

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``n``, ``qmd``, ``zmd``, ``pmd``, ``pmo``, ``zmo`` and
        ``qmo`` sorted by level.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> book = await client.order_book("فولاد")
        >>> book[["pmd", "zmd", "pmo", "zmo"]].head()
    """
    ins_code = await self.resolve(symbol_or_inscode)
    return await _live.get_order_book(self._client, ins_code, engine=engine)

intraday_trades async

intraday_trades(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch intraday OHLCV bars for the current/last session.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns time (datetime.time | None), open, high,

DataFrame

low, close and volume.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the response body is not valid JSON.

Examples:

>>> bars = await client.intraday_trades("فولاد")
>>> bars[["time", "close", "volume"]].tail()
Source code in src/iranquant/__init__.py
async def intraday_trades(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch intraday OHLCV bars for the current/last session.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``time`` (``datetime.time | None``), ``open``, ``high``,
        ``low``, ``close`` and ``volume``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> bars = await client.intraday_trades("فولاد")
        >>> bars[["time", "close", "volume"]].tail()
    """
    ins_code = await self.resolve(symbol_or_inscode)
    return await _live.get_intraday_trades(self._client, ins_code, engine=engine)

indices_live async

indices_live(*, engine: Engine = 'pandas') -> DataFrame

Fetch live overall, equal-weight and sector index snapshots.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized columns index_code, name, index_value,

DataFrame

change, change_pct, date, jdate and time; the

DataFrame

overall/equal-weight rows also carry market_state and

DataFrame

market_state_title.

Raises:

Type Description
NetworkError

If no index data can be fetched.

Examples:

>>> indices = await client.indices_live()
>>> indices[["name", "index_value", "change_pct"]].head()
Source code in src/iranquant/__init__.py
async def indices_live(self, *, engine: Engine = "pandas") -> DataFrame:
    """Fetch live overall, equal-weight and sector index snapshots.

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

    Returns:
        Standardized columns ``index_code``, ``name``, ``index_value``,
        ``change``, ``change_pct``, ``date``, ``jdate`` and ``time``; the
        overall/equal-weight rows also carry ``market_state`` and
        ``market_state_title``.

    Raises:
        NetworkError: If no index data can be fetched.

    Examples:
        >>> indices = await client.indices_live()
        >>> indices[["name", "index_value", "change_pct"]].head()
    """
    return await _index.get_indices_live(self._client, engine=engine)

index_history async

index_history(
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch historical daily values for an index code.

Parameters:

Name Type Description Default
index_code str

TSETMC index code. Defaults to the overall index (OVERALL_INDEX_CODE).

OVERALL_INDEX_CODE
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized index columns plus the raw upstream fields, sorted by

DataFrame

date.

Raises:

Type Description
NetworkError

If both the B2 and B1 endpoints fail.

ParseError

If a body is not valid JSON.

Examples:

>>> history = await client.index_history()
>>> history[["date", "index_value"]].tail()
Source code in src/iranquant/__init__.py
async def index_history(
    self,
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch historical daily values for an index code.

    Args:
        index_code: TSETMC index code.  Defaults to the overall index
            (``OVERALL_INDEX_CODE``).
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Standardized index columns plus the raw upstream fields, sorted by
        ``date``.

    Raises:
        NetworkError: If both the B2 and B1 endpoints fail.
        ParseError: If a body is not valid JSON.

    Examples:
        >>> history = await client.index_history()
        >>> history[["date", "index_value"]].tail()
    """
    return await _index.get_index_history(
        self._client,
        index_code,
        engine=engine,
    )
codal_search(
    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,
) -> CodalSearchResponse

Search Codal announcements using this client's transport.

Parameters:

Name Type Description Default
symbol str | None

Optional Persian ticker filter.

None
letter_type int

Codal LetterType (-1 for all, 58 monthly activity, 6 interim financials). Defaults to -1.

-1
category int

Codal Category filter. Defaults to -1.

-1
page int

One-based 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

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse whose

CodalSearchResponse

letters have absolute URLs.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = await client.codal_search("فولاد", letter_type=58)
>>> reports.Total
Source code in src/iranquant/__init__.py
async def codal_search(
    self,
    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,
) -> CodalSearchResponse:
    """Search Codal announcements using this client's transport.

    Args:
        symbol: Optional Persian ticker filter.
        letter_type: Codal ``LetterType`` (``-1`` for all, ``58`` monthly
            activity, ``6`` interim financials).  Defaults to ``-1``.
        category: Codal ``Category`` filter.  Defaults to ``-1``.
        page: One-based 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``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` whose
        letters have absolute URLs.

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

    Examples:
        >>> reports = await client.codal_search("فولاد", letter_type=58)
        >>> reports.Total
    """
    return await search_codal(
        symbol=symbol,
        letter_type=letter_type,
        category=category,
        page=page,
        audited=audited,
        not_audited=not_audited,
        mains=mains,
        childs=childs,
        client=self._client,
    )

monthly_reports async

monthly_reports(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Fetch monthly activity reports (LetterType=58).

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = await client.monthly_reports("فولاد")
>>> tables = await client.codal_report(reports.Letters[0])
Source code in src/iranquant/__init__.py
async def monthly_reports(
    self,
    symbol: str,
    page: int = 1,
) -> CodalSearchResponse:
    """Fetch monthly activity reports (``LetterType=58``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.

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

    Examples:
        >>> reports = await client.monthly_reports("فولاد")
        >>> tables = await client.codal_report(reports.Letters[0])
    """
    return await get_monthly_reports(symbol, page=page, client=self._client)

financial_statements async

financial_statements(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Fetch interim financial statements (LetterType=6).

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> statements = await client.financial_statements("فولاد")
Source code in src/iranquant/__init__.py
async def financial_statements(
    self,
    symbol: str,
    page: int = 1,
) -> CodalSearchResponse:
    """Fetch interim financial statements (``LetterType=6``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.

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

    Examples:
        >>> statements = await client.financial_statements("فولاد")
    """
    return await get_financial_statements(symbol, page=page, client=self._client)

codal_report async

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

Download and parse all tables of a Codal report.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

ValueError

If engine is unsupported.

Examples:

>>> tables = await client.codal_report("/Report/123")
>>> for name, table in tables.items():
...     print(name, table.shape)
Source code in src/iranquant/__init__.py
async def codal_report(
    self,
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Download and parse all tables of a Codal report.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

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

    Examples:
        >>> tables = await client.codal_report("/Report/123")
        >>> for name, table in tables.items():
        ...     print(name, table.shape)
    """
    return await fetch_and_parse_report(
        url_or_letter,
        engine=engine,
        client=self._client,
    )

parse_codal_report async

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

Download and parse a Codal report using this client's transport.

This is the async counterpart of the top-level :func:parse_codal_report and an alias for :meth:codal_report.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

ValueError

If engine is unsupported.

Examples:

>>> tables = await client.parse_codal_report("/Report/123")
>>> for name, table in tables.items():
...     print(name, table.shape)
Source code in src/iranquant/__init__.py
async def parse_codal_report(
    self,
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Download and parse a Codal report using this client's transport.

    This is the async counterpart of the top-level
    :func:`parse_codal_report` and an alias for :meth:`codal_report`.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

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

    Examples:
        >>> tables = await client.parse_codal_report("/Report/123")
        >>> for name, table in tables.items():
        ...     print(name, table.shape)
    """
    return await fetch_and_parse_report(
        url_or_letter,
        engine=engine,
        client=self._client,
    )

monthly_sales_summary async

monthly_sales_summary(
    symbol: str, page: int = 1
) -> dict[str, Any]

Analyze a symbol's latest monthly sales report.

Parses the newest LetterType=58 report and compares its current month with the previous distinct monthly period.

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based Codal result page. Defaults to 1.

1

Returns:

Type Description
dict[str, Any]

The dictionary produced by

dict[str, Any]

func:~iranquant.codal.monthly.analyze_monthly_sales plus

dict[str, Any]

symbol, tracing_no, title, prev_month_tracing_no

dict[str, Any]

and a mom_change_pct computed from the previous report.

Raises:

Type Description
ParseError

If no HTML monthly report is available.

NetworkError

If Codal cannot be reached.

ValueError

If the report has no usable tables.

Examples:

>>> summary = await client.monthly_sales_summary("فولاد")
>>> summary["current_month_sales"]
>>> summary["summary_df"].head()
Source code in src/iranquant/__init__.py
async def monthly_sales_summary(
    self,
    symbol: str,
    page: int = 1,
) -> dict[str, Any]:
    """Analyze a symbol's latest monthly sales report.

    Parses the newest ``LetterType=58`` report and compares its current
    month with the previous distinct monthly period.

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based Codal result page.  Defaults to ``1``.

    Returns:
        The dictionary produced by
        :func:`~iranquant.codal.monthly.analyze_monthly_sales` plus
        ``symbol``, ``tracing_no``, ``title``, ``prev_month_tracing_no``
        and a ``mom_change_pct`` computed from the previous report.

    Raises:
        ParseError: If no HTML monthly report is available.
        NetworkError: If Codal cannot be reached.
        ValueError: If the report has no usable tables.

    Examples:
        >>> summary = await client.monthly_sales_summary("فولاد")
        >>> summary["current_month_sales"]
        >>> summary["summary_df"].head()
    """
    return await _monthly_sales_summary(
        symbol,
        page=page,
        client=self._client,
    )

money_flow async

money_flow(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame

Fetch full history and compute money-flow/smart-money analytics.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
vol_window int

Rolling volume window. Defaults to 20.

20
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus real_buy_per_capita,

DataFrame

real_buy_per_capita_m, real_sell_per_capita,

DataFrame

real_sell_per_capita_m, buyer_power_ratio,

DataFrame

net_real_value, ownership_change_pct, close_vs_final_pct,

DataFrame

vol_ratio, smart_money_entry and smart_money_exit.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

KeyError

If a required history column is missing.

ValueError

If vol_window < 1.

Examples:

>>> flow = await client.money_flow("فولاد")
>>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail()
Source code in src/iranquant/__init__.py
async def money_flow(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch full history and compute money-flow/smart-money analytics.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        vol_window: Rolling volume window.  Defaults to ``20``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus ``real_buy_per_capita``,
        ``real_buy_per_capita_m``, ``real_sell_per_capita``,
        ``real_sell_per_capita_m``, ``buyer_power_ratio``,
        ``net_real_value``, ``ownership_change_pct``, ``close_vs_final_pct``,
        ``vol_ratio``, ``smart_money_entry`` and ``smart_money_exit``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.
        KeyError: If a required history column is missing.
        ValueError: If ``vol_window < 1``.

    Examples:
        >>> flow = await client.money_flow("فولاد")
        >>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail()
    """
    frame = await self.full_history(
        symbol_or_inscode,
        adjust=adjust,
        engine=engine,
    )
    return compute_money_flow(frame, vol_window=vol_window)

movement_power async

movement_power(
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch full history and compute the movement-power score.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
windows tuple[int, int, int]

Lookback windows. Defaults to (5, 20, 60).

(5, 20, 60)
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus er_<window> columns and

DataFrame

movement_power_score in [-100, +100].

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

KeyError

If close is missing.

ValueError

If windows is empty or non-positive.

Examples:

>>> power = await client.movement_power("فولاد")
>>> power[["jdate", "movement_power_score"]].tail()
Source code in src/iranquant/__init__.py
async def movement_power(
    self,
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch full history and compute the movement-power score.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        windows: Lookback windows.  Defaults to ``(5, 20, 60)``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus ``er_<window>`` columns and
        ``movement_power_score`` in ``[-100, +100]``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.
        KeyError: If ``close`` is missing.
        ValueError: If ``windows`` is empty or non-positive.

    Examples:
        >>> power = await client.movement_power("فولاد")
        >>> power[["jdate", "movement_power_score"]].tail()
    """
    frame = await self.full_history(
        symbol_or_inscode,
        adjust=adjust,
        engine=engine,
    )
    return compute_movement_power(frame, windows=windows)

watch

watch(
    interval: float = 5.0,
    symbols: list[str] | None = None,
    only_market_hours: bool = False,
) -> AsyncIterator[MarketEvent]

Return an async iterator of live MarketWatcher events.

The returned watcher shares this client's transport and does not close it when iteration ends.

Parameters:

Name Type Description Default
interval float

Seconds between MarketWatch polls. Defaults to 5.0.

5.0
symbols list[str] | None

Optional ticker/insCode allow-list.

None
only_market_hours bool

Skip polls outside Sat-Wed 09:00-12:30 Tehran time. Defaults to False.

False

Returns:

Type Description
AsyncIterator[MarketEvent]

An async iterator of :class:~iranquant.stream.MarketEvent.

Raises:

Type Description
ValueError

When iterated with interval <= 0.

Examples:

>>> async for event in client.watch(interval=3.0, symbols=["فولاد"]):
...     print(event.event_type, event.symbol)
Source code in src/iranquant/__init__.py
def watch(
    self,
    interval: float = 5.0,
    symbols: list[str] | None = None,
    only_market_hours: bool = False,
) -> AsyncIterator[MarketEvent]:
    """Return an async iterator of live MarketWatcher events.

    The returned watcher shares this client's transport and does not close
    it when iteration ends.

    Args:
        interval: Seconds between MarketWatch polls.  Defaults to ``5.0``.
        symbols: Optional ticker/``insCode`` allow-list.
        only_market_hours: Skip polls outside Sat-Wed 09:00-12:30 Tehran
            time.  Defaults to ``False``.

    Returns:
        An async iterator of :class:`~iranquant.stream.MarketEvent`.

    Raises:
        ValueError: When iterated with ``interval <= 0``.

    Examples:
        >>> async for event in client.watch(interval=3.0, symbols=["فولاد"]):
        ...     print(event.event_type, event.symbol)
    """

    watcher = MarketWatcher(client=self._client)
    return watcher.watch(
        interval=interval,
        symbols=symbols,
        only_market_hours=only_market_hours,
    )

IranQuant

Synchronous facade over :class:AsyncIranQuant.

Each method delegates to the same-named module-level function, so an IranQuant instance can be passed around as a small client object without managing any HTTP transport or event loop.

Examples:

>>> iq_client = IranQuant()
>>> frame = iq_client.history("فولاد")
>>> screener = iq_client.screener(iq_client.market_watch())

search

search(
    query: str, *, engine: Engine = "pandas"
) -> DataFrame

Search TSETMC instruments by ticker or company name.

Parameters:

Name Type Description Default
query str

Symbol or company-name fragment, e.g. "فولاد".

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per match with ins_code, symbol, company_name,

DataFrame

isin, shares, flow, board, last_date and

DataFrame

last_date_jdate.

Raises:

Type Description
NetworkError

If TSETMC cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> IranQuant().search("فولاد").head()
Source code in src/iranquant/__init__.py
def search(self, query: str, *, engine: Engine = "pandas") -> DataFrame:
    """Search TSETMC instruments by ticker or company name.

    Args:
        query: Symbol or company-name fragment, e.g. ``"فولاد"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        One row per match with ``ins_code``, ``symbol``, ``company_name``,
        ``isin``, ``shares``, ``flow``, ``board``, ``last_date`` and
        ``last_date_jdate``.

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

    Examples:
        >>> IranQuant().search("فولاد").head()
    """
    return search(query, engine=engine)

get_inscode

get_inscode(symbol_or_inscode: str | int) -> str

Resolve a symbol or numeric code to its TSETMC insCode.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric instrument code.

required

Returns:

Type Description
str

The numeric insCode as a string.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be matched.

NetworkError

If the lookup request fails.

Examples:

>>> IranQuant().get_inscode("فولاد").isdigit()
True
Source code in src/iranquant/__init__.py
def get_inscode(self, symbol_or_inscode: str | int) -> str:
    """Resolve a symbol or numeric code to its TSETMC ``insCode``.

    Args:
        symbol_or_inscode: Persian ticker or numeric instrument code.

    Returns:
        The numeric ``insCode`` as a string.

    Raises:
        SymbolNotFoundError: If the symbol cannot be matched.
        NetworkError: If the lookup request fails.

    Examples:
        >>> IranQuant().get_inscode("فولاد").isdigit()
        True
    """
    return get_inscode(symbol_or_inscode)

history

history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch backward-adjusted daily OHLCV history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date, jdate, open, high, low,

DataFrame

close, final_price, prev_price, volume, value

DataFrame

and trades, sorted by date.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the payload is malformed.

Examples:

>>> IranQuant().history("فولاد").tail()
Source code in src/iranquant/__init__.py
def history(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch backward-adjusted daily OHLCV history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date``, ``jdate``, ``open``, ``high``, ``low``,
        ``close``, ``final_price``, ``prev_price``, ``volume``, ``value``
        and ``trades``, sorted by date.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the payload is malformed.

    Examples:
        >>> IranQuant().history("فولاد").tail()
    """
    return history(symbol_or_inscode, adjust=adjust, engine=engine)

full_history

full_history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch daily OHLCV merged with client-type history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The history columns plus the twelve buy_*/sell_*

DataFrame

client-type columns.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

Examples:

>>> IranQuant().full_history("فولاد").tail()
Source code in src/iranquant/__init__.py
def full_history(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch daily OHLCV merged with client-type history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The ``history`` columns plus the twelve ``buy_*``/``sell_*``
        client-type columns.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.

    Examples:
        >>> IranQuant().full_history("فولاد").tail()
    """
    return full_history(symbol_or_inscode, adjust=adjust, engine=engine)

client_type

client_type(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch retail/institutional client-type history only.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date, jdate and the twelve buy_*/sell_*

DataFrame

client-type columns.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the payload is malformed.

Examples:

>>> IranQuant().client_type("فولاد").tail()
Source code in src/iranquant/__init__.py
def client_type(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch retail/institutional client-type history only.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date``, ``jdate`` and the twelve ``buy_*``/``sell_*``
        client-type columns.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the payload is malformed.

    Examples:
        >>> IranQuant().client_type("فولاد").tail()
    """
    return client_type(symbol_or_inscode, engine=engine)

market_watch

market_watch(*, engine: Engine = 'pandas') -> DataFrame

Fetch the live market-wide snapshot in one request.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per symbol with the MarketWatch columns described in

DataFrame

func:iranquant.market_watch.

Raises:

Type Description
NetworkError

If the endpoint cannot be reached.

ParseError

If the response body is not valid JSON.

Examples:

>>> IranQuant().market_watch().head()
Source code in src/iranquant/__init__.py
def market_watch(self, *, engine: Engine = "pandas") -> DataFrame:
    """Fetch the live market-wide snapshot in one request.

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

    Returns:
        One row per symbol with the MarketWatch columns described in
        :func:`iranquant.market_watch`.

    Raises:
        NetworkError: If the endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> IranQuant().market_watch().head()
    """
    return market_watch(engine=engine)

order_book

order_book(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch the best-limit order book (levels 1..5).

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns n, qmd, zmd, pmd, pmo, zmo and

DataFrame

qmo.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

Examples:

>>> IranQuant().order_book("فولاد").head()
Source code in src/iranquant/__init__.py
def order_book(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch the best-limit order book (levels 1..5).

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``n``, ``qmd``, ``zmd``, ``pmd``, ``pmo``, ``zmo`` and
        ``qmo``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.

    Examples:
        >>> IranQuant().order_book("فولاد").head()
    """
    return order_book(symbol_or_inscode, engine=engine)

intraday_trades

intraday_trades(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch intraday OHLCV bars for the current/last session.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns time, open, high, low, close and

DataFrame

volume.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

Examples:

>>> IranQuant().intraday_trades("فولاد").tail()
Source code in src/iranquant/__init__.py
def intraday_trades(
    self,
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch intraday OHLCV bars for the current/last session.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``time``, ``open``, ``high``, ``low``, ``close`` and
        ``volume``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.

    Examples:
        >>> IranQuant().intraday_trades("فولاد").tail()
    """
    return intraday_trades(symbol_or_inscode, engine=engine)

indices_live

indices_live(*, engine: Engine = 'pandas') -> DataFrame

Fetch live overall, equal-weight and sector index snapshots.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized index columns described in

DataFrame

func:iranquant.indices_live.

Raises:

Type Description
NetworkError

If no index data can be fetched.

Examples:

>>> IranQuant().indices_live().head()
Source code in src/iranquant/__init__.py
def indices_live(self, *, engine: Engine = "pandas") -> DataFrame:
    """Fetch live overall, equal-weight and sector index snapshots.

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

    Returns:
        Standardized index columns described in
        :func:`iranquant.indices_live`.

    Raises:
        NetworkError: If no index data can be fetched.

    Examples:
        >>> IranQuant().indices_live().head()
    """
    return indices_live(engine=engine)

index_history

index_history(
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Fetch historical daily values for an index code.

Parameters:

Name Type Description Default
index_code str

TSETMC index code. Defaults to the overall index.

OVERALL_INDEX_CODE
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized index columns plus raw upstream fields, sorted by

DataFrame

date.

Raises:

Type Description
NetworkError

If both the B2 and B1 endpoints fail.

ParseError

If a body is not valid JSON.

Examples:

>>> IranQuant().index_history().tail()
Source code in src/iranquant/__init__.py
def index_history(
    self,
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch historical daily values for an index code.

    Args:
        index_code: TSETMC index code.  Defaults to the overall index.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Standardized index columns plus raw upstream fields, sorted by
        date.

    Raises:
        NetworkError: If both the B2 and B1 endpoints fail.
        ParseError: If a body is not valid JSON.

    Examples:
        >>> IranQuant().index_history().tail()
    """
    return index_history(index_code, engine=engine)
codal_search(
    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,
) -> CodalSearchResponse

Search Codal announcements.

Parameters:

Name Type Description Default
symbol str | None

Optional Persian ticker filter.

None
letter_type int

LetterType (-1 all, 58 monthly activity, 6 interim financials). Defaults to -1.

-1
category int

Category filter. Defaults to -1.

-1
page int

One-based 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

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> IranQuant().codal_search("فولاد", letter_type=58).Total
Source code in src/iranquant/__init__.py
def codal_search(
    self,
    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,
) -> CodalSearchResponse:
    """Search Codal announcements.

    Args:
        symbol: Optional Persian ticker filter.
        letter_type: ``LetterType`` (``-1`` all, ``58`` monthly activity,
            ``6`` interim financials).  Defaults to ``-1``.
        category: ``Category`` filter.  Defaults to ``-1``.
        page: One-based 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``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.

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

    Examples:
        >>> IranQuant().codal_search("فولاد", letter_type=58).Total
    """
    return codal_search(
        symbol=symbol,
        letter_type=letter_type,
        category=category,
        page=page,
        audited=audited,
        not_audited=not_audited,
        mains=mains,
        childs=childs,
    )

monthly_reports

monthly_reports(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Fetch monthly activity reports (LetterType=58).

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> IranQuant().monthly_reports("فولاد").Letters[0].Title
Source code in src/iranquant/__init__.py
def monthly_reports(self, symbol: str, page: int = 1) -> CodalSearchResponse:
    """Fetch monthly activity reports (``LetterType=58``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.

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

    Examples:
        >>> IranQuant().monthly_reports("فولاد").Letters[0].Title
    """
    return monthly_reports(symbol, page=page)

financial_statements

financial_statements(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Fetch interim financial statements (LetterType=6).

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> IranQuant().financial_statements("فولاد").Total
Source code in src/iranquant/__init__.py
def financial_statements(self, symbol: str, page: int = 1) -> CodalSearchResponse:
    """Fetch interim financial statements (``LetterType=6``).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse`.

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

    Examples:
        >>> IranQuant().financial_statements("فولاد").Total
    """
    return financial_statements(symbol, page=page)

codal_report

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

Download and parse all tables of a Codal report.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

Examples:

>>> IranQuant().codal_report("/Report/123")
Source code in src/iranquant/__init__.py
def codal_report(
    self,
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Download and parse all tables of a Codal report.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

    Raises:
        NetworkError: If the report page cannot be downloaded.
        ParseError: If the page has no valid datasource JSON.

    Examples:
        >>> IranQuant().codal_report("/Report/123")
    """
    return codal_report(url_or_letter, engine=engine)

parse_codal_report

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

Download and parse all tables of a Codal report.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

Examples:

>>> tables = IranQuant().parse_codal_report("/Report/123")
Source code in src/iranquant/__init__.py
def parse_codal_report(
    self,
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Download and parse all tables of a Codal report.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

    Raises:
        NetworkError: If the report page cannot be downloaded.
        ParseError: If the page has no valid datasource JSON.

    Examples:
        >>> tables = IranQuant().parse_codal_report("/Report/123")
    """
    return parse_codal_report(url_or_letter, engine=engine)

monthly_sales_summary

monthly_sales_summary(
    symbol: str, page: int = 1
) -> dict[str, Any]

Analyze a symbol's latest monthly sales report.

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based Codal result page. Defaults to 1.

1

Returns:

Type Description
dict[str, Any]

The monthly analyzer result plus report metadata and a

dict[str, Any]

mom_change_pct computed from the previous monthly period.

Raises:

Type Description
ParseError

If no HTML monthly report is available.

NetworkError

If Codal cannot be reached.

Examples:

>>> IranQuant().monthly_sales_summary("فولاد")["yoy_change_pct"]
Source code in src/iranquant/__init__.py
def monthly_sales_summary(self, symbol: str, page: int = 1) -> dict[str, Any]:
    """Analyze a symbol's latest monthly sales report.

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based Codal result page.  Defaults to ``1``.

    Returns:
        The monthly analyzer result plus report metadata and a
        ``mom_change_pct`` computed from the previous monthly period.

    Raises:
        ParseError: If no HTML monthly report is available.
        NetworkError: If Codal cannot be reached.

    Examples:
        >>> IranQuant().monthly_sales_summary("فولاد")["yoy_change_pct"]
    """
    return monthly_sales_summary(symbol, page=page)

money_flow

money_flow(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame

Fetch full history and compute smart-money/flow analytics.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
vol_window int

Rolling volume window. Defaults to 20.

20
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus the money-flow columns described in

DataFrame

func:iranquant.quant.compute_money_flow.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

KeyError

If a required history column is missing.

ValueError

If vol_window < 1.

Examples:

>>> IranQuant().money_flow("فولاد").tail()
Source code in src/iranquant/__init__.py
def money_flow(
    self,
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch full history and compute smart-money/flow analytics.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        vol_window: Rolling volume window.  Defaults to ``20``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus the money-flow columns described in
        :func:`iranquant.quant.compute_money_flow`.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        KeyError: If a required history column is missing.
        ValueError: If ``vol_window < 1``.

    Examples:
        >>> IranQuant().money_flow("فولاد").tail()
    """
    return money_flow(
        symbol_or_inscode,
        adjust=adjust,
        vol_window=vol_window,
        engine=engine,
    )

movement_power

movement_power(
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Fetch full history and compute the movement-power score.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
windows tuple[int, int, int]

Lookback windows. Defaults to (5, 20, 60).

(5, 20, 60)
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus er_<window> and

DataFrame

movement_power_score.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

KeyError

If close is missing.

ValueError

If windows is empty or non-positive.

Examples:

>>> IranQuant().movement_power("فولاد").tail()
Source code in src/iranquant/__init__.py
def movement_power(
    self,
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Fetch full history and compute the movement-power score.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        windows: Lookback windows.  Defaults to ``(5, 20, 60)``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus ``er_<window>`` and
        ``movement_power_score``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        KeyError: If ``close`` is missing.
        ValueError: If ``windows`` is empty or non-positive.

    Examples:
        >>> IranQuant().movement_power("فولاد").tail()
    """
    return movement_power(
        symbol_or_inscode,
        windows=windows,
        adjust=adjust,
        engine=engine,
    )

screener

screener(frame: DataFrame) -> MarketScreener

Wrap a MarketWatch frame in a :class:~iranquant.MarketScreener.

Parameters:

Name Type Description Default
frame DataFrame

A MarketWatch (or batch) frame.

required

Returns:

Type Description
MarketScreener

A screener bound to frame.

Raises:

Type Description
TypeError

When a filter is run with a non-Pandas/Polars frame.

Examples:

>>> screener = IranQuant().screener(iq.market_watch())
>>> screener.filter_buy_queue().head()
Source code in src/iranquant/__init__.py
def screener(self, frame: DataFrame) -> MarketScreener:
    """Wrap a MarketWatch frame in a :class:`~iranquant.MarketScreener`.

    Args:
        frame: A MarketWatch (or batch) frame.

    Returns:
        A screener bound to ``frame``.

    Raises:
        TypeError: When a filter is run with a non-Pandas/Polars frame.

    Examples:
        >>> screener = IranQuant().screener(iq.market_watch())
        >>> screener.filter_buy_queue().head()
    """
    return MarketScreener(frame)

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,
    }

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_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,
    )

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,
    )

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()

_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

to_dataframe

to_dataframe(
    records: list[dict[str, Any]], engine: Engine = "pandas"
) -> DataFrame

Convert a list of record dictionaries to a Pandas or Polars DataFrame.

An empty records list still produces a valid (empty) DataFrame for both engines. Column order follows the key insertion order of the first record.

Parameters:

Name Type Description Default
records list[dict[str, Any]]

Row-oriented records, typically produced by the market and Codal modules. Every record should share the same keys.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Name Type Description
A DataFrame

class:pandas.DataFrame or :class:polars.DataFrame matching

DataFrame

engine.

Raises:

Type Description
ValueError

If engine is neither "pandas" nor "polars".

Examples:

>>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
   symbol   close
0   فولاد  4150.0
>>> to_dataframe([], engine="polars").height
0
Source code in src/iranquant/core/dataframe.py
def to_dataframe(records: list[dict[str, Any]], engine: Engine = "pandas") -> DataFrame:
    """Convert a list of record dictionaries to a Pandas or Polars DataFrame.

    An empty ``records`` list still produces a valid (empty) DataFrame for both
    engines.  Column order follows the key insertion order of the first record.

    Args:
        records: Row-oriented records, typically produced by the market and
            Codal modules.  Every record should share the same keys.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A :class:`pandas.DataFrame` or :class:`polars.DataFrame` matching
        ``engine``.

    Raises:
        ValueError: If ``engine`` is neither ``"pandas"`` nor ``"polars"``.

    Examples:
        >>> to_dataframe([{"symbol": "فولاد", "close": 4150.0}])
           symbol   close
        0   فولاد  4150.0
        >>> to_dataframe([], engine="polars").height
        0
    """

    if engine == "polars":
        return pl.DataFrame(records)
    if engine == "pandas":
        return cast(pd.DataFrame, pd.DataFrame(records))
    raise ValueError(f"Unsupported dataframe engine: {engine!r}")

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())

run_sync

run_sync(coro: Coroutine[Any, Any, T]) -> T

Run coro to completion from synchronous code.

A plain asyncio.run is used when no event loop is running. Inside an already-running loop (Jupyter, Colab, async applications) the coroutine is executed on a fresh loop in a background thread, which avoids the usual "asyncio.run() cannot be called from a running event loop" error.

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

An already-created coroutine object.

required

Returns:

Type Description
T

Whatever the coroutine returns.

Raises:

Type Description
BaseException

Any exception raised by the coroutine is re-raised in the calling thread.

Examples:

>>> async def answer() -> int:
...     return 42
>>> run_sync(answer())
42
Source code in src/iranquant/core/sync.py
def run_sync(coro: Coroutine[Any, Any, T]) -> T:
    """Run ``coro`` to completion from synchronous code.

    A plain ``asyncio.run`` is used when no event loop is running.  Inside an
    already-running loop (Jupyter, Colab, async applications) the coroutine is
    executed on a fresh loop in a background thread, which avoids the usual
    "asyncio.run() cannot be called from a running event loop" error.

    Args:
        coro: An already-created coroutine object.

    Returns:
        Whatever the coroutine returns.

    Raises:
        BaseException: Any exception raised by the coroutine is re-raised in
            the calling thread.

    Examples:
        >>> async def answer() -> int:
        ...     return 42
        >>> run_sync(answer())
        42
    """

    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(coro)
    return _run_in_thread(coro)

compute_money_flow

compute_money_flow(
    frame: DataFrame, vol_window: int = 20
) -> DataFrame

Add smart-money, per-capita and real/legal flow columns.

Works with both Pandas and Polars inputs and returns a frame of the same type. All monetary per-capita values are expressed in Rials (*_m variants are in million Tomans).

The required input columns are final_price, close, volume, buy_I_Volume, sell_I_Volume, buy_I_Count and sell_I_Count (all present in :func:iranquant.full_history). Columns are computed as:

  • real_buy_per_capita = buy_I_Volume * final_price / max(buy_I_Count, 1)
  • real_sell_per_capita = sell_I_Volume * final_price / max(sell_I_Count, 1)
  • buyer_power_ratio = real_buy_per_capita / max(real_sell_per_capita, 1)
  • net_real_value = (buy_I_Volume - sell_I_Volume) * final_price
  • ownership_change_pct = ((buy_I_Volume - sell_I_Volume) / max(volume, 1)) * 100
  • close_vs_final_pct = ((close - final_price) / max(final_price, 1)) * 100
  • vol_ratio = volume / rolling_mean(volume, vol_window)

smart_money_entry is True when vol_ratio >= 1.8 and buyer_power_ratio >= 1.5 and net_real_value > 0 and close >= final_price. smart_money_exit mirrors it with buyer_power_ratio <= 0.67, net_real_value < 0 and close <= final_price.

Parameters:

Name Type Description Default
frame DataFrame

A history frame. Any extra columns (including date and jdate) are preserved unchanged.

required
vol_window int

Rolling window used for the volume-ratio baseline. Must be at least 1. Defaults to 20.

20

Returns:

Type Description
DataFrame

A frame of the same engine with all input columns plus:

DataFrame
  • real_buy_per_capita (float) — Rials per retail buy order.
DataFrame
  • real_buy_per_capita_m (float) — same, in million Tomans.
DataFrame
  • real_sell_per_capita (float) — Rials per retail sell order.
DataFrame
  • real_sell_per_capita_m (float) — same, in million Tomans.
DataFrame
  • buyer_power_ratio (float) — real buy/sell power ratio.
DataFrame
  • net_real_value (float) — net real money flow in Rials.
DataFrame
  • ownership_change_pct (float) — net real volume / total volume.
DataFrame
  • close_vs_final_pct (float) — last price vs closing price.
DataFrame
  • vol_ratio (float) — volume relative to its rolling mean.
DataFrame
  • smart_money_entry (bool) — smart-money accumulation signal.
DataFrame
  • smart_money_exit (bool) — smart-money distribution signal.

Raises:

Type Description
ValueError

If vol_window < 1.

KeyError

If any required input column is missing.

Examples:

>>> flow = compute_money_flow(iq.full_history("فولاد"))
>>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail(3)

The Polars path preserves pl.DataFrame::

>>> import polars as pl
>>> flow = compute_money_flow(iq.full_history("فولاد", engine="polars"))
>>> flow.filter(pl.col("smart_money_entry")).height
Source code in src/iranquant/quant/money_flow.py
def compute_money_flow(frame: DataFrame, vol_window: int = 20) -> DataFrame:
    """Add smart-money, per-capita and real/legal flow columns.

    Works with both Pandas and Polars inputs and returns a frame of the same
    type.  All monetary per-capita values are expressed in Rials
    (``*_m`` variants are in million Tomans).

    The required input columns are ``final_price``, ``close``, ``volume``,
    ``buy_I_Volume``, ``sell_I_Volume``, ``buy_I_Count`` and ``sell_I_Count``
    (all present in :func:`iranquant.full_history`).  Columns are computed as:

    * ``real_buy_per_capita = buy_I_Volume * final_price / max(buy_I_Count, 1)``
    * ``real_sell_per_capita = sell_I_Volume * final_price / max(sell_I_Count, 1)``
    * ``buyer_power_ratio = real_buy_per_capita / max(real_sell_per_capita, 1)``
    * ``net_real_value = (buy_I_Volume - sell_I_Volume) * final_price``
    * ``ownership_change_pct = ((buy_I_Volume - sell_I_Volume) / max(volume, 1)) * 100``
    * ``close_vs_final_pct = ((close - final_price) / max(final_price, 1)) * 100``
    * ``vol_ratio = volume / rolling_mean(volume, vol_window)``

    ``smart_money_entry`` is ``True`` when ``vol_ratio >= 1.8`` **and**
    ``buyer_power_ratio >= 1.5`` **and** ``net_real_value > 0`` **and**
    ``close >= final_price``.  ``smart_money_exit`` mirrors it with
    ``buyer_power_ratio <= 0.67``, ``net_real_value < 0`` and
    ``close <= final_price``.

    Args:
        frame: A history frame.  Any extra columns (including ``date`` and
            ``jdate``) are preserved unchanged.
        vol_window: Rolling window used for the volume-ratio baseline.  Must be
            at least ``1``.  Defaults to ``20``.

    Returns:
        A frame of the same engine with all input columns plus:

        * ``real_buy_per_capita`` (``float``) — Rials per retail buy order.
        * ``real_buy_per_capita_m`` (``float``) — same, in million Tomans.
        * ``real_sell_per_capita`` (``float``) — Rials per retail sell order.
        * ``real_sell_per_capita_m`` (``float``) — same, in million Tomans.
        * ``buyer_power_ratio`` (``float``) — real buy/sell power ratio.
        * ``net_real_value`` (``float``) — net real money flow in Rials.
        * ``ownership_change_pct`` (``float``) — net real volume / total volume.
        * ``close_vs_final_pct`` (``float``) — last price vs closing price.
        * ``vol_ratio`` (``float``) — volume relative to its rolling mean.
        * ``smart_money_entry`` (``bool``) — smart-money accumulation signal.
        * ``smart_money_exit`` (``bool``) — smart-money distribution signal.

    Raises:
        ValueError: If ``vol_window < 1``.
        KeyError: If any required input column is missing.

    Examples:
        >>> flow = compute_money_flow(iq.full_history("فولاد"))
        >>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail(3)

        The Polars path preserves ``pl.DataFrame``::

        >>> import polars as pl
        >>> flow = compute_money_flow(iq.full_history("فولاد", engine="polars"))
        >>> flow.filter(pl.col("smart_money_entry")).height
    """

    if vol_window < 1:
        raise ValueError("vol_window must be >= 1")

    source = to_pandas(frame)
    missing = [column for column in _REQUIRED if column not in source.columns]
    if missing:
        raise KeyError(f"Missing required columns: {', '.join(missing)}")

    out = source.copy()
    final_price = cast(pd.Series, out["final_price"].astype(float))
    close = cast(pd.Series, out["close"].astype(float))
    volume = cast(pd.Series, out["volume"].astype(float))
    buy_i_volume = cast(pd.Series, out["buy_I_Volume"].astype(float))
    sell_i_volume = cast(pd.Series, out["sell_I_Volume"].astype(float))
    buy_i_count = cast(pd.Series, out["buy_I_Count"].astype(float))
    sell_i_count = cast(pd.Series, out["sell_I_Count"].astype(float))

    real_buy = (buy_i_volume * final_price) / buy_i_count.clip(lower=1.0)
    real_sell = (sell_i_volume * final_price) / sell_i_count.clip(lower=1.0)
    buyer_power = real_buy / real_sell.clip(lower=1.0)

    net_real_value = (buy_i_volume - sell_i_volume) * final_price
    ownership_change = ((buy_i_volume - sell_i_volume) / volume.clip(lower=1.0)) * 100.0
    close_vs_final = ((close - final_price) / final_price.clip(lower=1.0)) * 100.0

    rolling_volume = volume.rolling(vol_window, min_periods=1).mean()
    vol_ratio = (volume / rolling_volume.clip(lower=1e-9)).fillna(0.0)

    out["real_buy_per_capita"] = real_buy
    out["real_buy_per_capita_m"] = real_buy / 1e7
    out["real_sell_per_capita"] = real_sell
    out["real_sell_per_capita_m"] = real_sell / 1e7
    out["buyer_power_ratio"] = buyer_power
    out["net_real_value"] = net_real_value
    out["ownership_change_pct"] = ownership_change
    out["close_vs_final_pct"] = close_vs_final
    out["vol_ratio"] = vol_ratio
    out["smart_money_entry"] = (
        (vol_ratio >= 1.8) & (buyer_power >= 1.5) & (net_real_value > 0) & (close >= final_price)
    )
    out["smart_money_exit"] = (
        (vol_ratio >= 1.8) & (buyer_power <= 0.67) & (net_real_value < 0) & (close <= final_price)
    )
    return restore(frame, out)

compute_movement_power

compute_movement_power(
    frame: DataFrame,
    windows: tuple[int, int, int] = (5, 20, 60),
) -> DataFrame

Compute a signed multi-timeframe Kaufman efficiency power score.

For each window w the signed Kaufman efficiency ratio is::

er_w = sign(close - close.shift(w))
       * abs(close - close.shift(w))
       / rolling_sum(abs(close.diff()), w)

The score starts as a weighted sum of the signed ratios. With exactly three windows the weights are (0.5, 0.3, 0.2); otherwise all windows are equally weighted. The score is then multiplied by a volume factor (volume / rolling_mean(volume, min(windows)) clipped to [0.5, 2.0]) and, when present, a buyer-power factor (clip(buyer_power_ratio, 0.5, 3.0) / 1.5 clipped to [0.5, 1.5]), scaled by 100 and clipped to [-100, +100].

Parameters:

Name Type Description Default
frame DataFrame

A history frame containing close. volume and buyer_power_ratio (produced by :func:compute_money_flow) are optional and only modulate the score when present.

required
windows tuple[int, int, int]

One or more positive lookback windows. Defaults to (5, 20, 60).

(5, 20, 60)

Returns:

Type Description
DataFrame

A frame of the same engine with all input columns plus:

DataFrame
  • er_<window> (float) — signed efficiency ratio per window
DataFrame

(for example er_5, er_20, er_60).

DataFrame
  • movement_power_score (float) — weighted, volume- and
DataFrame

buyer-power-adjusted score in [-100, +100].

Raises:

Type Description
ValueError

If windows is empty or contains a non-positive value.

KeyError

If the close column is missing.

Examples:

>>> power = compute_movement_power(iq.full_history("فولاد"))
>>> power[["jdate", "er_5", "er_20", "movement_power_score"]].tail(3)
>>> power.sort_values("movement_power_score", ascending=False).head()
Source code in src/iranquant/quant/momentum.py
def compute_movement_power(
    frame: DataFrame,
    windows: tuple[int, int, int] = (5, 20, 60),
) -> DataFrame:
    """Compute a signed multi-timeframe Kaufman efficiency power score.

    For each window ``w`` the signed Kaufman efficiency ratio is::

        er_w = sign(close - close.shift(w))
               * abs(close - close.shift(w))
               / rolling_sum(abs(close.diff()), w)

    The score starts as a weighted sum of the signed ratios.  With exactly
    three windows the weights are ``(0.5, 0.3, 0.2)``; otherwise all windows
    are equally weighted.  The score is then multiplied by a volume factor
    (``volume / rolling_mean(volume, min(windows))`` clipped to ``[0.5, 2.0]``)
    and, when present, a buyer-power factor
    (``clip(buyer_power_ratio, 0.5, 3.0) / 1.5`` clipped to ``[0.5, 1.5]``),
    scaled by ``100`` and clipped to ``[-100, +100]``.

    Args:
        frame: A history frame containing ``close``.  ``volume`` and
            ``buyer_power_ratio`` (produced by :func:`compute_money_flow`) are
            optional and only modulate the score when present.
        windows: One or more positive lookback windows.  Defaults to
            ``(5, 20, 60)``.

    Returns:
        A frame of the same engine with all input columns plus:

        * ``er_<window>`` (``float``) — signed efficiency ratio per window
        (for example ``er_5``, ``er_20``, ``er_60``).
        * ``movement_power_score`` (``float``) — weighted, volume- and
        buyer-power-adjusted score in ``[-100, +100]``.

    Raises:
        ValueError: If ``windows`` is empty or contains a non-positive value.
        KeyError: If the ``close`` column is missing.

    Examples:
        >>> power = compute_movement_power(iq.full_history("فولاد"))
        >>> power[["jdate", "er_5", "er_20", "movement_power_score"]].tail(3)
        >>> power.sort_values("movement_power_score", ascending=False).head()
    """

    if not windows:
        raise ValueError("At least one window is required")
    if any(window < 1 for window in windows):
        raise ValueError("Windows must be positive integers")

    source = to_pandas(frame)
    if "close" not in source.columns:
        raise KeyError("Missing required column: close")
    if source.empty:
        out = source.copy()
        for window in windows:
            out[f"er_{window}"] = pd.Series(dtype=float)
        out["movement_power_score"] = pd.Series(dtype=float)
        return restore(frame, out)

    out = source.copy()
    close = cast(pd.Series, out["close"].astype(float))

    weights = [0.5, 0.3, 0.2] if len(windows) == 3 else [1.0 / len(windows)] * len(windows)

    score = pd.Series(0.0, index=out.index, dtype=float)
    for window, weight in zip(windows, weights, strict=True):
        signed = _signed_efficiency_ratio(close, window)
        out[f"er_{window}"] = signed
        score = score + (signed * weight)

    shortest = min(windows)
    if "volume" in out.columns:
        volume = cast(pd.Series, out["volume"].astype(float))
        rolling_volume = volume.rolling(shortest, min_periods=1).mean()
        volume_factor = (volume / rolling_volume.clip(lower=1e-9)).fillna(1.0)
        volume_factor = volume_factor.clip(lower=0.5, upper=2.0)
    else:
        volume_factor = pd.Series(1.0, index=out.index, dtype=float)

    if "buyer_power_ratio" in out.columns:
        buyer_power = cast(pd.Series, out["buyer_power_ratio"].astype(float))
        buyer_power = buyer_power.fillna(1.0).clip(lower=0.5, upper=3.0) / 1.5
        buyer_power = buyer_power.clip(lower=0.5, upper=1.5)
    else:
        buyer_power = pd.Series(1.0, index=out.index, dtype=float)

    power = (score * 100.0 * volume_factor * buyer_power).clip(lower=-100.0, upper=100.0)
    out["movement_power_score"] = power
    return restore(frame, out)

detect_swing_legs

detect_swing_legs(
    frame: DataFrame, reversal_pct: float = 5.0
) -> DataFrame

Detect ZigZag swing legs from the close column.

A percentage-reversal ZigZag is run over the closing prices. A leg is confirmed whenever price reverses by at least reversal_pct from the running extreme; the final, still-active leg is appended so the output always ends at the last bar. Input and output engine types match.

Parameters:

Name Type Description Default
frame DataFrame

A history frame containing close. date (used for start_date/end_date) and volume (used for volume statistics) are optional; without date positional integer indexes are used, and without volume the volume columns are 0.0/NaN.

required
reversal_pct float

Minimum reversal, in percent, required to confirm a new pivot. Must be positive. Defaults to 5.0.

5.0

Returns:

Type Description
DataFrame

One row per leg (completed legs plus the active leg) with columns:

DataFrame
  • leg_id (int) — one-based leg number.
DataFrame
  • direction (int) — 1 for up legs, -1 for down legs.
DataFrame
  • start_date / end_date (Any) — values from date, or
DataFrame

positional indexes when date is absent.

DataFrame
  • start_price / end_price (float) — pivot prices.
DataFrame
  • leg_return_pct (float) — percentage price change over the leg.
DataFrame
  • leg_bars (int) — number of bars spanned (end index - start).
DataFrame
  • leg_velocity (float) — leg_return_pct / max(leg_bars, 1).
DataFrame
  • avg_volume (float) — mean volume across the leg's bars.
DataFrame
  • leg_volume_expansion (float) — this leg's avg_volume
DataFrame

divided by the previous leg's; NaN for the first leg or when the

DataFrame

previous average is zero.

DataFrame

An empty frame with the same columns is returned for empty input or

DataFrame

when no pivots are found.

Raises:

Type Description
ValueError

If reversal_pct <= 0.

KeyError

If the close column is missing.

Examples:

>>> legs = detect_swing_legs(iq.history("فولاد"), reversal_pct=5.0)
>>> legs[["direction", "leg_return_pct", "leg_velocity"]].tail(5)
>>> legs[legs["leg_volume_expansion"] > 1.5]["direction"].tolist()
Source code in src/iranquant/quant/momentum.py
def detect_swing_legs(frame: DataFrame, reversal_pct: float = 5.0) -> DataFrame:
    """Detect ZigZag swing legs from the ``close`` column.

    A percentage-reversal ZigZag is run over the closing prices.  A leg is
    confirmed whenever price reverses by at least ``reversal_pct`` from the
    running extreme; the final, still-active leg is appended so the output
    always ends at the last bar.  Input and output engine types match.

    Args:
        frame: A history frame containing ``close``.  ``date`` (used for
            ``start_date``/``end_date``) and ``volume`` (used for volume
            statistics) are optional; without ``date`` positional integer
            indexes are used, and without ``volume`` the volume columns are
            ``0.0``/``NaN``.
        reversal_pct: Minimum reversal, in percent, required to confirm a new
            pivot.  Must be positive.  Defaults to ``5.0``.

    Returns:
        One row per leg (completed legs plus the active leg) with columns:

        * ``leg_id`` (``int``) — one-based leg number.
        * ``direction`` (``int``) — ``1`` for up legs, ``-1`` for down legs.
        * ``start_date`` / ``end_date`` (``Any``) — values from ``date``, or
        positional indexes when ``date`` is absent.
        * ``start_price`` / ``end_price`` (``float``) — pivot prices.
        * ``leg_return_pct`` (``float``) — percentage price change over the leg.
        * ``leg_bars`` (``int``) — number of bars spanned (end index - start).
        * ``leg_velocity`` (``float``) — ``leg_return_pct / max(leg_bars, 1)``.
        * ``avg_volume`` (``float``) — mean volume across the leg's bars.
        * ``leg_volume_expansion`` (``float``) — this leg's ``avg_volume``
        divided by the previous leg's; ``NaN`` for the first leg or when the
        previous average is zero.

        An empty frame with the same columns is returned for empty input or
        when no pivots are found.

    Raises:
        ValueError: If ``reversal_pct <= 0``.
        KeyError: If the ``close`` column is missing.

    Examples:
        >>> legs = detect_swing_legs(iq.history("فولاد"), reversal_pct=5.0)
        >>> legs[["direction", "leg_return_pct", "leg_velocity"]].tail(5)
        >>> legs[legs["leg_volume_expansion"] > 1.5]["direction"].tolist()
    """

    if reversal_pct <= 0:
        raise ValueError("reversal_pct must be positive")

    source = to_pandas(frame)
    if source.empty:
        return empty_like(frame, LEG_COLUMNS)
    if "close" not in source.columns:
        raise KeyError("Missing required column: close")

    closes = source["close"].astype(float).to_numpy()
    dates: list[Any] = (
        source["date"].tolist() if "date" in source.columns else list(range(len(source)))
    )
    volumes = (
        source["volume"].astype(float).to_numpy()
        if "volume" in source.columns
        else np.zeros(len(source), dtype=float)
    )

    pivots = _zigzag(closes, reversal_pct / 100.0)
    legs: list[dict[str, Any]] = []
    for leg_id in range(1, len(pivots)):
        start_index, start_price = pivots[leg_id - 1]
        end_index, end_price = pivots[leg_id]
        if end_index <= start_index:
            continue
        direction = 1 if end_price >= start_price else -1
        return_pct = ((end_price / start_price) - 1.0) * 100.0 if start_price else 0.0
        bars = end_index - start_index
        avg_volume = float(np.mean(volumes[start_index : end_index + 1]))
        legs.append(
            {
                "leg_id": leg_id,
                "direction": direction,
                "start_date": dates[start_index],
                "end_date": dates[end_index],
                "start_price": start_price,
                "end_price": end_price,
                "leg_return_pct": return_pct,
                "leg_bars": bars,
                "leg_velocity": return_pct / max(bars, 1),
                "avg_volume": avg_volume,
                "leg_volume_expansion": float("nan"),
            }
        )

    for index in range(1, len(legs)):
        previous_volume = float(legs[index - 1]["avg_volume"])
        if previous_volume > 0:
            legs[index]["leg_volume_expansion"] = float(legs[index]["avg_volume"]) / previous_volume

    if not legs:
        return empty_like(frame, LEG_COLUMNS)
    result = pd.DataFrame(legs, columns=LEG_COLUMNS)
    return restore(frame, result)

is_market_open

is_market_open(now: datetime | None = None) -> bool

Return True during Saturday-Wednesday TSETMC sessions (09:00-12:30 IRST).

Python weekday numbering is Monday=0, so the active days are 5, 6, 0, 1 and 2. The time is interpreted in Asia/Tehran (with a fixed +03:30 fallback when tzdata is unavailable).

Parameters:

Name Type Description Default
now datetime | None

Optional aware or naive datetime. Naive values are assumed to be Tehran local time. Defaults to the current instant.

None

Returns:

Type Description
bool

True when the current weekday is Saturday to Wednesday and the

bool

local time is between 09:00 and 12:30 inclusive, otherwise False.

Examples:

>>> import datetime as dt
>>> is_market_open(dt.datetime(2026, 10, 31, 10, 0))  # Saturday
True
>>> is_market_open(dt.datetime(2026, 10, 30, 13, 0))  # Friday
False
Source code in src/iranquant/stream/watcher.py
def is_market_open(now: dt.datetime | None = None) -> bool:
    """Return True during Saturday-Wednesday TSETMC sessions (09:00-12:30 IRST).

    Python weekday numbering is Monday=0, so the active days are 5, 6, 0, 1
    and 2.  The time is interpreted in ``Asia/Tehran`` (with a fixed +03:30
    fallback when tzdata is unavailable).

    Args:
        now: Optional aware or naive datetime.  Naive values are assumed to be
            Tehran local time.  Defaults to the current instant.

    Returns:
        ``True`` when the current weekday is Saturday to Wednesday and the
        local time is between 09:00 and 12:30 inclusive, otherwise ``False``.

    Examples:
        >>> import datetime as dt
        >>> is_market_open(dt.datetime(2026, 10, 31, 10, 0))  # Saturday
        True
        >>> is_market_open(dt.datetime(2026, 10, 30, 13, 0))  # Friday
        False
    """

    timezone = _tehran_timezone()
    current = now or dt.datetime.now(timezone)
    if current.tzinfo is None:
        current = current.replace(tzinfo=timezone)
    current = current.astimezone(timezone)
    if current.weekday() not in {5, 6, 0, 1, 2}:
        return False
    current_time = current.time()
    return dt.time(9, 0) <= current_time <= dt.time(12, 30)

_as_ins_code

_as_ins_code(value: str | int) -> str | None
Source code in src/iranquant/__init__.py
def _as_ins_code(value: str | int) -> str | None:
    if isinstance(value, int):
        return str(value)
    text = normalize_persian(str(value))
    return text if text.isdigit() else None

_run_with_client

_run_with_client(
    factory: Callable[[AsyncIranQuant], Awaitable[T]],
) -> T
Source code in src/iranquant/__init__.py
def _run_with_client(factory: Callable[[AsyncIranQuant], Awaitable[T]]) -> T:
    async def runner() -> T:
        async with AsyncIranQuant() as client:
            return await factory(client)

    return run_sync(runner())

search

search(
    query: str, *, engine: Engine = "pandas"
) -> DataFrame

Sync: search TSETMC instruments.

A temporary client is created and closed for the call. Safe to call inside an existing event loop (Jupyter/Colab).

Parameters:

Name Type Description Default
query str

Symbol or company-name fragment, e.g. "فولاد".

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per match with ins_code, symbol, company_name,

DataFrame

isin, shares, flow, board, last_date and

DataFrame

last_date_jdate.

Raises:

Type Description
NetworkError

If TSETMC cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> results = iq.search("فولاد")
>>> results.iloc[0]["ins_code"]
'46348559193224090'
Source code in src/iranquant/__init__.py
def search(query: str, *, engine: Engine = "pandas") -> DataFrame:
    """Sync: search TSETMC instruments.

    A temporary client is created and closed for the call.  Safe to call inside
    an existing event loop (Jupyter/Colab).

    Args:
        query: Symbol or company-name fragment, e.g. ``"فولاد"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        One row per match with ``ins_code``, ``symbol``, ``company_name``,
        ``isin``, ``shares``, ``flow``, ``board``, ``last_date`` and
        ``last_date_jdate``.

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

    Examples:
        >>> results = iq.search("فولاد")
        >>> results.iloc[0]["ins_code"]
        '46348559193224090'
    """

    return _run_with_client(lambda client: client.search(query, engine=engine))

get_inscode

get_inscode(symbol_or_inscode: str | int) -> str

Sync: resolve a symbol name or numeric code to its TSETMC insCode.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or a numeric instrument code.

required

Returns:

Type Description
str

The numeric insCode as a string. Numeric input bypasses the

str

network.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be matched.

NetworkError

If the lookup request fails.

ParseError

If the response is malformed.

Examples:

>>> iq.get_inscode("فولاد")
'46348559193224090'
Source code in src/iranquant/__init__.py
def get_inscode(symbol_or_inscode: str | int) -> str:
    """Sync: resolve a symbol name or numeric code to its TSETMC ``insCode``.

    Args:
        symbol_or_inscode: Persian ticker or a numeric instrument code.

    Returns:
        The numeric ``insCode`` as a string.  Numeric input bypasses the
        network.

    Raises:
        SymbolNotFoundError: If the symbol cannot be matched.
        NetworkError: If the lookup request fails.
        ParseError: If the response is malformed.

    Examples:
        >>> iq.get_inscode("فولاد")
        '46348559193224090'
    """

    return _run_with_client(lambda client: client.resolve(symbol_or_inscode))

history

history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Sync: daily OHLCV history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date (datetime.date), jdate (str), open,

DataFrame

high, low, close, final_price, prev_price,

DataFrame

volume, value and trades (all float), sorted by date.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If TSETMC cannot be reached.

ParseError

If the payload is malformed.

Examples:

>>> frame = iq.history("فولاد", adjust="all")
>>> frame.tail(3)[["jdate", "close"]]
Source code in src/iranquant/__init__.py
def history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: daily OHLCV history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date`` (``datetime.date``), ``jdate`` (``str``), ``open``,
        ``high``, ``low``, ``close``, ``final_price``, ``prev_price``,
        ``volume``, ``value`` and ``trades`` (all ``float``), sorted by date.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If TSETMC cannot be reached.
        ParseError: If the payload is malformed.

    Examples:
        >>> frame = iq.history("فولاد", adjust="all")
        >>> frame.tail(3)[["jdate", "close"]]
    """

    return _run_with_client(
        lambda client: client.history(symbol_or_inscode, adjust=adjust, engine=engine)
    )

full_history

full_history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Sync: daily OHLCV merged with client-type history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

"none", "all" (default) or "capital_only".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Name Type Description
The DataFrame

func:history columns plus buy_I_Volume, buy_N_Volume,

DataFrame

buy_I_Value, buy_N_Value, buy_N_Count, buy_I_Count,

DataFrame

sell_I_Volume, sell_N_Volume, sell_I_Value,

DataFrame

sell_N_Value, sell_N_Count and sell_I_Count.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

Examples:

>>> frame = iq.full_history("فولاد")
>>> frame[["jdate", "buy_I_Volume", "sell_N_Count"]].tail()
Source code in src/iranquant/__init__.py
def full_history(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: daily OHLCV merged with client-type history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: ``"none"``, ``"all"`` (default) or ``"capital_only"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The :func:`history` columns plus ``buy_I_Volume``, ``buy_N_Volume``,
        ``buy_I_Value``, ``buy_N_Value``, ``buy_N_Count``, ``buy_I_Count``,
        ``sell_I_Volume``, ``sell_N_Volume``, ``sell_I_Value``,
        ``sell_N_Value``, ``sell_N_Count`` and ``sell_I_Count``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.

    Examples:
        >>> frame = iq.full_history("فولاد")
        >>> frame[["jdate", "buy_I_Volume", "sell_N_Count"]].tail()
    """

    return _run_with_client(
        lambda client: client.full_history(symbol_or_inscode, adjust=adjust, engine=engine)
    )

client_type

client_type(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Sync: retail/institutional client-type history.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns date, jdate, buy_I_Volume, buy_N_Volume,

DataFrame

buy_I_Value, buy_N_Value, buy_N_Count, buy_I_Count,

DataFrame

sell_I_Volume, sell_N_Volume, sell_I_Value,

DataFrame

sell_N_Value, sell_N_Count and sell_I_Count.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the payload is malformed.

Examples:

>>> frame = iq.client_type("فولاد")
>>> frame[["date", "buy_I_Volume", "sell_I_Volume"]].tail()
Source code in src/iranquant/__init__.py
def client_type(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: retail/institutional client-type history.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``date``, ``jdate``, ``buy_I_Volume``, ``buy_N_Volume``,
        ``buy_I_Value``, ``buy_N_Value``, ``buy_N_Count``, ``buy_I_Count``,
        ``sell_I_Volume``, ``sell_N_Volume``, ``sell_I_Value``,
        ``sell_N_Value``, ``sell_N_Count`` and ``sell_I_Count``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the payload is malformed.

    Examples:
        >>> frame = iq.client_type("فولاد")
        >>> frame[["date", "buy_I_Volume", "sell_I_Volume"]].tail()
    """

    return _run_with_client(lambda client: client.client_type(symbol_or_inscode, engine=engine))

market_watch

market_watch(*, engine: Engine = 'pandas') -> DataFrame

Sync: live market-wide snapshot.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

One row per symbol with ins_code, symbol, company_name,

DataFrame

eps, pe, open, high, low, close,

DataFrame

final_price, prev_price, volume, value, trades,

DataFrame

tmax, tmin, total_shares and order_book.

Raises:

Type Description
NetworkError

If the MarketWatch endpoint cannot be reached.

ParseError

If the response body is not valid JSON.

Examples:

>>> market = iq.market_watch()
>>> market[["symbol", "close", "tmax"]].head()
Source code in src/iranquant/__init__.py
def market_watch(*, engine: Engine = "pandas") -> DataFrame:
    """Sync: live market-wide snapshot.

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

    Returns:
        One row per symbol with ``ins_code``, ``symbol``, ``company_name``,
        ``eps``, ``pe``, ``open``, ``high``, ``low``, ``close``,
        ``final_price``, ``prev_price``, ``volume``, ``value``, ``trades``,
        ``tmax``, ``tmin``, ``total_shares`` and ``order_book``.

    Raises:
        NetworkError: If the MarketWatch endpoint cannot be reached.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> market = iq.market_watch()
        >>> market[["symbol", "close", "tmax"]].head()
    """

    return _run_with_client(lambda client: client.market_watch(engine=engine))

order_book

order_book(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Sync: best-limit order book.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns n, qmd, zmd, pmd, pmo, zmo and

DataFrame

qmo sorted by level.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the response body is not valid JSON.

Examples:

>>> book = iq.order_book("فولاد")
>>> book[["pmd", "zmd", "pmo", "zmo"]].head()
Source code in src/iranquant/__init__.py
def order_book(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: best-limit order book.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``n``, ``qmd``, ``zmd``, ``pmd``, ``pmo``, ``zmo`` and
        ``qmo`` sorted by level.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> book = iq.order_book("فولاد")
        >>> book[["pmd", "zmd", "pmo", "zmo"]].head()
    """

    return _run_with_client(lambda client: client.order_book(symbol_or_inscode, engine=engine))

intraday_trades

intraday_trades(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Sync: intraday OHLCV bars for the current/last session.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Columns time (datetime.time | None), open, high,

DataFrame

low, close and volume.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If the request fails.

ParseError

If the response body is not valid JSON.

Examples:

>>> bars = iq.intraday_trades("فولاد")
>>> bars[["time", "close", "volume"]].tail()
Source code in src/iranquant/__init__.py
def intraday_trades(
    symbol_or_inscode: str | int,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: intraday OHLCV bars for the current/last session.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Columns ``time`` (``datetime.time | None``), ``open``, ``high``,
        ``low``, ``close`` and ``volume``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If the request fails.
        ParseError: If the response body is not valid JSON.

    Examples:
        >>> bars = iq.intraday_trades("فولاد")
        >>> bars[["time", "close", "volume"]].tail()
    """

    return _run_with_client(lambda client: client.intraday_trades(symbol_or_inscode, engine=engine))

indices_live

indices_live(*, engine: Engine = 'pandas') -> DataFrame

Sync: live index snapshots.

Parameters:

Name Type Description Default
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized columns index_code, name, index_value,

DataFrame

change, change_pct, date, jdate and time.

Raises:

Type Description
NetworkError

If no index data can be fetched.

Examples:

>>> indices = iq.indices_live()
>>> indices[["name", "index_value", "change_pct"]].head()
Source code in src/iranquant/__init__.py
def indices_live(*, engine: Engine = "pandas") -> DataFrame:
    """Sync: live index snapshots.

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

    Returns:
        Standardized columns ``index_code``, ``name``, ``index_value``,
        ``change``, ``change_pct``, ``date``, ``jdate`` and ``time``.

    Raises:
        NetworkError: If no index data can be fetched.

    Examples:
        >>> indices = iq.indices_live()
        >>> indices[["name", "index_value", "change_pct"]].head()
    """

    return _run_with_client(lambda client: client.indices_live(engine=engine))

index_history

index_history(
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame

Sync: index daily history.

Parameters:

Name Type Description Default
index_code str

TSETMC index code. Defaults to the overall index.

OVERALL_INDEX_CODE
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

Standardized index columns plus raw upstream fields, sorted by date.

Raises:

Type Description
NetworkError

If both the B2 and B1 endpoints fail.

ParseError

If a body is not valid JSON.

Examples:

>>> history = iq.index_history()
>>> history[["date", "index_value"]].tail()
Source code in src/iranquant/__init__.py
def index_history(
    index_code: str = OVERALL_INDEX_CODE,
    *,
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: index daily history.

    Args:
        index_code: TSETMC index code.  Defaults to the overall index.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        Standardized index columns plus raw upstream fields, sorted by date.

    Raises:
        NetworkError: If both the B2 and B1 endpoints fail.
        ParseError: If a body is not valid JSON.

    Examples:
        >>> history = iq.index_history()
        >>> history[["date", "index_value"]].tail()
    """

    return _run_with_client(lambda client: client.index_history(index_code, engine=engine))
codal_search(
    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,
) -> CodalSearchResponse

Sync: search Codal announcements.

Parameters:

Name Type Description Default
symbol str | None

Optional Persian ticker filter.

None
letter_type int

Codal LetterType (-1 all, 58 monthly activity, 6 interim financials). Defaults to -1.

-1
category int

Codal Category filter. Defaults to -1.

-1
page int

One-based 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

Returns:

Name Type Description
A CodalSearchResponse

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

CodalSearchResponse

URLs.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = iq.codal_search("فولاد", letter_type=58)
>>> reports.Total
Source code in src/iranquant/__init__.py
def codal_search(
    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,
) -> CodalSearchResponse:
    """Sync: search Codal announcements.

    Args:
        symbol: Optional Persian ticker filter.
        letter_type: Codal ``LetterType`` (``-1`` all, ``58`` monthly activity,
            ``6`` interim financials).  Defaults to ``-1``.
        category: Codal ``Category`` filter.  Defaults to ``-1``.
        page: One-based 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``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` with absolute
        URLs.

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

    Examples:
        >>> reports = iq.codal_search("فولاد", letter_type=58)
        >>> reports.Total
    """

    return _run_with_client(
        lambda client: client.codal_search(
            symbol=symbol,
            letter_type=letter_type,
            category=category,
            page=page,
            audited=audited,
            not_audited=not_audited,
            mains=mains,
            childs=childs,
        )
    )

monthly_reports

monthly_reports(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Sync: monthly activity reports (گزارش فعالیت ماهانه).

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse with

CodalSearchResponse

LetterType=58 results.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> reports = iq.monthly_reports("فولاد")
>>> tables = iq.codal_report(reports.Letters[0])
Source code in src/iranquant/__init__.py
def monthly_reports(symbol: str, page: int = 1) -> CodalSearchResponse:
    """Sync: monthly activity reports (گزارش فعالیت ماهانه).

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` with
        ``LetterType=58`` results.

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

    Examples:
        >>> reports = iq.monthly_reports("فولاد")
        >>> tables = iq.codal_report(reports.Letters[0])
    """

    return _run_with_client(lambda client: client.monthly_reports(symbol, page=page))

financial_statements

financial_statements(
    symbol: str, page: int = 1
) -> CodalSearchResponse

Sync: interim financial statements.

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based page. Defaults to 1.

1

Returns:

Name Type Description
A CodalSearchResponse

class:~iranquant.models.codal.CodalSearchResponse with

CodalSearchResponse

LetterType=6 results.

Raises:

Type Description
NetworkError

If Codal cannot be reached.

ParseError

If the response is malformed.

Examples:

>>> statements = iq.financial_statements("فولاد")
>>> statements.Letters[0].Title
Source code in src/iranquant/__init__.py
def financial_statements(symbol: str, page: int = 1) -> CodalSearchResponse:
    """Sync: interim financial statements.

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based page.  Defaults to ``1``.

    Returns:
        A :class:`~iranquant.models.codal.CodalSearchResponse` with
        ``LetterType=6`` results.

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

    Examples:
        >>> statements = iq.financial_statements("فولاد")
        >>> statements.Letters[0].Title
    """

    return _run_with_client(lambda client: client.financial_statements(symbol, page=page))

codal_report

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

Sync: download and parse all tables of a Codal report.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

ValueError

If engine is unsupported.

Examples:

>>> tables = iq.codal_report("/Report/123")
>>> {name: table.shape for name, table in tables.items()}
Source code in src/iranquant/__init__.py
def codal_report(
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Sync: download and parse all tables of a Codal report.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

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

    Examples:
        >>> tables = iq.codal_report("/Report/123")
        >>> {name: table.shape for name, table in tables.items()}
    """

    return _run_with_client(lambda client: client.codal_report(url_or_letter, engine=engine))

parse_codal_report

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

Sync: download and parse all tables of a Codal report.

This is an explicit, discoverable alias for :func:codal_report; both return the same mapping. A temporary client is created and closed for the call, and it is safe to use inside a running event loop.

Parameters:

Name Type Description Default
url_or_letter str | CodalLetter

Report URL or a CodalLetter with Url.

required
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
dict[str, Any]

A mapping of "<sheet title> - <table title>" to DataFrames.

Raises:

Type Description
NetworkError

If the report page cannot be downloaded.

ParseError

If the page has no valid datasource JSON.

ValueError

If engine is unsupported.

Examples:

>>> letter = iq.monthly_reports("فولاد").Letters[0]
>>> tables = iq.parse_codal_report(letter)
>>> summary = iq.analyze_monthly_sales(tables)
Source code in src/iranquant/__init__.py
def parse_codal_report(
    url_or_letter: str | CodalLetter,
    *,
    engine: Engine = "pandas",
) -> dict[str, Any]:
    """Sync: download and parse all tables of a Codal report.

    This is an explicit, discoverable alias for :func:`codal_report`; both
    return the same mapping.  A temporary client is created and closed for the
    call, and it is safe to use inside a running event loop.

    Args:
        url_or_letter: Report URL or a ``CodalLetter`` with ``Url``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        A mapping of ``"<sheet title> - <table title>"`` to DataFrames.

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

    Examples:
        >>> letter = iq.monthly_reports("فولاد").Letters[0]
        >>> tables = iq.parse_codal_report(letter)
        >>> summary = iq.analyze_monthly_sales(tables)
    """

    return _run_with_client(lambda client: client.parse_codal_report(url_or_letter, engine=engine))

monthly_sales_summary

monthly_sales_summary(
    symbol: str, page: int = 1
) -> dict[str, Any]

Sync: analyze a symbol's latest monthly sales report.

Fetches the newest LetterType=58 report and compares its current month with the previous distinct monthly period. Values are in million Rials.

Parameters:

Name Type Description Default
symbol str

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

required
page int

One-based Codal result page. Defaults to 1.

1

Returns:

Type Description
dict[str, Any]

The dictionary produced by

dict[str, Any]

func:~iranquant.codal.monthly.analyze_monthly_sales plus

dict[str, Any]

symbol, tracing_no, title, prev_month_tracing_no and a

dict[str, Any]

mom_change_pct computed from the previous report.

Raises:

Type Description
ParseError

If no HTML monthly report is available.

NetworkError

If Codal cannot be reached.

ValueError

If the report has no usable tables.

Examples:

>>> summary = iq.monthly_sales_summary("فولاد")
>>> summary["current_month_sales"]
662639489.0
>>> summary["yoy_change_pct"]
Source code in src/iranquant/__init__.py
def monthly_sales_summary(symbol: str, page: int = 1) -> dict[str, Any]:
    """Sync: analyze a symbol's latest monthly sales report.

    Fetches the newest ``LetterType=58`` report and compares its current month
    with the previous distinct monthly period.  Values are in million Rials.

    Args:
        symbol: Persian ticker, e.g. ``"فولاد"``.
        page: One-based Codal result page.  Defaults to ``1``.

    Returns:
        The dictionary produced by
        :func:`~iranquant.codal.monthly.analyze_monthly_sales` plus
        ``symbol``, ``tracing_no``, ``title``, ``prev_month_tracing_no`` and a
        ``mom_change_pct`` computed from the previous report.

    Raises:
        ParseError: If no HTML monthly report is available.
        NetworkError: If Codal cannot be reached.
        ValueError: If the report has no usable tables.

    Examples:
        >>> summary = iq.monthly_sales_summary("فولاد")
        >>> summary["current_month_sales"]
        662639489.0
        >>> summary["yoy_change_pct"]
    """

    return _run_with_client(lambda client: client.monthly_sales_summary(symbol, page=page))

money_flow

money_flow(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame

Sync: fetch full history and compute smart-money/flow analytics.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
vol_window int

Rolling volume window. Defaults to 20.

20
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus the money-flow columns described in

DataFrame

func:iranquant.quant.compute_money_flow.

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

KeyError

If a required history column is missing.

ValueError

If vol_window < 1.

Examples:

>>> flow = iq.money_flow("فولاد")
>>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail()
Source code in src/iranquant/__init__.py
def money_flow(
    symbol_or_inscode: str | int,
    *,
    adjust: AdjustMode = "all",
    vol_window: int = 20,
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: fetch full history and compute smart-money/flow analytics.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        vol_window: Rolling volume window.  Defaults to ``20``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus the money-flow columns described in
        :func:`iranquant.quant.compute_money_flow`.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.
        KeyError: If a required history column is missing.
        ValueError: If ``vol_window < 1``.

    Examples:
        >>> flow = iq.money_flow("فولاد")
        >>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail()
    """

    return _run_with_client(
        lambda client: client.money_flow(
            symbol_or_inscode,
            adjust=adjust,
            vol_window=vol_window,
            engine=engine,
        )
    )

movement_power

movement_power(
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame

Sync: fetch full history and compute the movement-power score.

Parameters:

Name Type Description Default
symbol_or_inscode str | int

Persian ticker or numeric insCode.

required
windows tuple[int, int, int]

Lookback windows. Defaults to (5, 20, 60).

(5, 20, 60)
adjust AdjustMode

Price adjustment mode. Defaults to "all".

'all'
engine Engine

"pandas" (default) or "polars".

'pandas'

Returns:

Type Description
DataFrame

The full-history columns plus er_<window> columns and

DataFrame

movement_power_score in [-100, +100].

Raises:

Type Description
SymbolNotFoundError

If the symbol cannot be resolved.

NetworkError

If a request fails.

ParseError

If a payload is malformed.

KeyError

If close is missing.

ValueError

If windows is empty or non-positive.

Examples:

>>> power = iq.movement_power("فولاد")
>>> power[["jdate", "er_5", "movement_power_score"]].tail()
Source code in src/iranquant/__init__.py
def movement_power(
    symbol_or_inscode: str | int,
    *,
    windows: tuple[int, int, int] = (5, 20, 60),
    adjust: AdjustMode = "all",
    engine: Engine = "pandas",
) -> DataFrame:
    """Sync: fetch full history and compute the movement-power score.

    Args:
        symbol_or_inscode: Persian ticker or numeric ``insCode``.
        windows: Lookback windows.  Defaults to ``(5, 20, 60)``.
        adjust: Price adjustment mode.  Defaults to ``"all"``.
        engine: ``"pandas"`` (default) or ``"polars"``.

    Returns:
        The full-history columns plus ``er_<window>`` columns and
        ``movement_power_score`` in ``[-100, +100]``.

    Raises:
        SymbolNotFoundError: If the symbol cannot be resolved.
        NetworkError: If a request fails.
        ParseError: If a payload is malformed.
        KeyError: If ``close`` is missing.
        ValueError: If ``windows`` is empty or non-positive.

    Examples:
        >>> power = iq.movement_power("فولاد")
        >>> power[["jdate", "er_5", "movement_power_score"]].tail()
    """

    return _run_with_client(
        lambda client: client.movement_power(
            symbol_or_inscode,
            windows=windows,
            adjust=adjust,
            engine=engine,
        )
    )