Codal API¶
Search¶
search
¶
Codal announcement search.
__all__
module-attribute
¶
__all__ = [
"INTERIM_FINANCIAL_LETTER",
"MONTHLY_ACTIVITY_LETTER",
"get_financial_statements",
"get_monthly_reports",
"resolve_codal_url",
"search_codal",
]
AsyncHTTPClient
¶
AsyncHTTPClient(
*,
timeout: float = DEFAULT_TIMEOUT,
max_concurrency: int = MAX_CONCURRENCY,
max_retries: int = MAX_RETRIES,
retry_wait: float = RETRY_WAIT,
headers: Mapping[str, str] | None = None,
proxy: str | None = None,
trust_env: bool | None = None,
config: IranQuantConfig | None = None,
)
Small retrying wrapper around :class:httpx.AsyncClient.
Requests use a verified transport when config.verify_ssl is true. A
certificate failure is retried once over an unverified transport only when
config.allow_tls_fallback is true; the first fallback emits a
UserWarning and a log record. With fallback disabled, the failure raises
:class:~iranquant.exceptions.IranQuantConnectionError without retrying.
Environment proxy variables are ignored by default (trust_env=False) to
avoid corporate/VPN HTTP proxies breaking direct connections to domestic
Iranian hosts. Pass proxy=... to opt into an explicit proxy.
Create the pooled HTTP transports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Per-request timeout in seconds. Defaults to
:data: |
DEFAULT_TIMEOUT
|
max_concurrency
|
int
|
Maximum number of simultaneous requests enforced
by an internal :class: |
MAX_CONCURRENCY
|
max_retries
|
int
|
Total attempts per request. Defaults to
:data: |
MAX_RETRIES
|
retry_wait
|
float
|
Base wait used by the exponential retry backoff, in
seconds. Defaults to :data: |
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.
|
None
|
trust_env
|
bool | None
|
Whether to honour |
None
|
config
|
IranQuantConfig | None
|
TLS policy. Defaults to :class: |
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
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
|
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
|
False
|
Returns:
| Type | Description |
|---|---|
Response
|
The successful :class: |
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
|
Examples:
>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
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: |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The decoded JSON value (usually a |
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
aclose
async
¶
Close the primary and fallback HTTP transports.
Safe to call more than once. After closing, the instance must not be used again.
Examples:
Source code in src/iranquant/core/client.py
__aenter__
async
¶
__aexit__
async
¶
ParseError
¶
Bases: IranQuantError
Raised when a remote payload cannot be parsed into the expected shape.
Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven
or hEven values, and missing var datasource blocks.
CodalLetter
¶
Bases: CodalBaseModel
CodalSearchResponse
¶
Bases: CodalBaseModel
A page of Codal search results with Pythonic container behavior.
The wire-format field names (Total, Page, Letters) are kept for
compatibility, and lowercase aliases (total, page, letters) are
provided for idiomatic code. The object is also iterable, indexable and
sized, and can be exported directly to a DataFrame.
Examples:
>>> response = iq.monthly_reports("فولاد")
>>> len(response) == response.total
True
>>> response[0].Symbol
'فولاد'
>>> response.to_dataframe()[["Symbol", "TracingNo"]].head()
__len__
¶
__iter__
¶
__getitem__
¶
to_dataframe
¶
Export the letters to a Pandas or Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
Literal['pandas', 'polars']
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
Any
|
One row per letter with the declared :class: |
Any
|
columns (including nested extra fields is intentionally avoided so |
Any
|
the schema stays stable). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> frame = iq.monthly_reports("فولاد").to_dataframe()
>>> frame[["Symbol", "TracingNo", "Title"]].head()
Source code in src/iranquant/models/codal.py
resolve_codal_url
¶
Make a Codal link absolute (/foo -> https://codal.ir/foo).
Protocol-relative links (//cdn...) become HTTPS, root-relative links
are prefixed with :data:iranquant.config.CODAL_BASE, and absolute URLs
are returned unchanged. Empty strings stay empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A raw Codal URL as returned by the search API. |
required |
Returns:
| Type | Description |
|---|---|
str
|
An absolute URL suitable for :class: |
Examples:
>>> resolve_codal_url("/Report/123")
'https://codal.ir/Report/123'
>>> resolve_codal_url("//cdn.codal.ir/a.pdf")
'https://cdn.codal.ir/a.pdf'
Source code in src/iranquant/codal/search.py
_resolve_letter_urls
¶
Source code in src/iranquant/codal/search.py
_search
async
¶
_search(
client: AsyncHTTPClient,
*,
symbol: str | None,
letter_type: int,
category: int,
page: int,
audited: bool,
not_audited: bool,
mains: bool,
childs: bool,
) -> CodalSearchResponse
Source code in src/iranquant/codal/search.py
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 |
-1
|
category
|
int
|
Codal |
-1
|
page
|
int
|
One-based result page. Defaults to |
1
|
audited
|
bool
|
Include audited reports. Defaults to |
True
|
not_audited
|
bool
|
Include unaudited reports. Defaults to |
True
|
mains
|
bool
|
Include parent-company reports. Defaults to |
True
|
childs
|
bool
|
Include subsidiary reports. Defaults to |
True
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CodalSearchResponse
|
class: |
CodalSearchResponse
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If |
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
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
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
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CodalSearchResponse
|
class: |
CodalSearchResponse
|
|
|
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
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
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CodalSearchResponse
|
class: |
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
Datasource parser¶
parser
¶
Extract and reconstruct Codal var datasource report tables.
_DATASOURCE_PATTERN
module-attribute
¶
_DATASOURCE_PATTERN = re.compile(
"var\\s+datasource\\s*=\\s*(\\{.*?\\})\\s*;\\s*</script>",
re.DOTALL,
)
_DATASOURCE_MARKER
module-attribute
¶
_HEADER_HINTS
module-attribute
¶
__all__
module-attribute
¶
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: |
DEFAULT_TIMEOUT
|
max_concurrency
|
int
|
Maximum number of simultaneous requests enforced
by an internal :class: |
MAX_CONCURRENCY
|
max_retries
|
int
|
Total attempts per request. Defaults to
:data: |
MAX_RETRIES
|
retry_wait
|
float
|
Base wait used by the exponential retry backoff, in
seconds. Defaults to :data: |
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.
|
None
|
trust_env
|
bool | None
|
Whether to honour |
None
|
config
|
IranQuantConfig | None
|
TLS policy. Defaults to :class: |
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
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
|
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
|
False
|
Returns:
| Type | Description |
|---|---|
Response
|
The successful :class: |
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
|
Examples:
>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
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: |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The decoded JSON value (usually a |
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
aclose
async
¶
Close the primary and fallback HTTP transports.
Safe to call more than once. After closing, the instance must not be used again.
Examples:
Source code in src/iranquant/core/client.py
__aenter__
async
¶
__aexit__
async
¶
ParseError
¶
Bases: IranQuantError
Raised when a remote payload cannot be parsed into the expected shape.
Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven
or hEven values, and missing var datasource blocks.
CodalDatasource
¶
Bases: CodalBaseModel
CodalLetter
¶
Bases: CodalBaseModel
resolve_codal_url
¶
Make a Codal link absolute (/foo -> https://codal.ir/foo).
Protocol-relative links (//cdn...) become HTTPS, root-relative links
are prefixed with :data:iranquant.config.CODAL_BASE, and absolute URLs
are returned unchanged. Empty strings stay empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A raw Codal URL as returned by the search API. |
required |
Returns:
| Type | Description |
|---|---|
str
|
An absolute URL suitable for :class: |
Examples:
>>> resolve_codal_url("/Report/123")
'https://codal.ir/Report/123'
>>> resolve_codal_url("//cdn.codal.ir/a.pdf")
'https://cdn.codal.ir/a.pdf'
Source code in src/iranquant/codal/search.py
normalize_persian
¶
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:
Source code in src/iranquant/core/normalizer.py
_extract_balanced_object
¶
Source code in src/iranquant/codal/parser.py
extract_datasource_json
¶
Extract the var datasource = {...} JSON object from a report page.
A fast regex is tried first; if the JSON contains nested braces inside strings or is followed by more JavaScript, a brace-balanced scanner is used as a fallback. Braces inside quoted strings are handled correctly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
The full HTML source of a Codal report page. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The decoded datasource object, usually containing a |
Raises:
| Type | Description |
|---|---|
ParseError
|
If no |
Examples:
>>> html = '<script>var datasource = {"sheets": []};</script>'
>>> extract_datasource_json(html)
{'sheets': []}
Source code in src/iranquant/codal/parser.py
_special_to_ascii
¶
_parse_number
¶
Source code in src/iranquant/codal/parser.py
_clean_value
¶
Source code in src/iranquant/codal/parser.py
_is_number
¶
_label
¶
_dedupe_columns
¶
Source code in src/iranquant/codal/parser.py
_normalize_column
¶
Source code in src/iranquant/codal/parser.py
_row_looks_like_header
¶
_reconstruct_table
¶
Source code in src/iranquant/codal/parser.py
_normalize_all_columns
¶
_build_frame
¶
Source code in src/iranquant/codal/parser.py
parse_codal_tables
¶
Reconstruct every visible table in a Codal datasource object.
Cells are grouped by rowSequence/columnSequence, invisible cells are
dropped, header rows are detected (from rowType/cellGroupName hints
or a text-only first row), and multi-row headers are joined with " - ".
Persian/Arabic digits, thousands separators, ٫ decimals, unicode minus
and accounting parentheses ((1,200) -> -1200.0) are normalized.
Duplicate column labels get _2, _3 suffixes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasource
|
dict[str, Any]
|
A decoded datasource object, e.g. from
:func: |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary mapping |
dict[str, Any]
|
DataFrame. Persistently duplicated keys are suffixed with |
dict[str, Any]
|
|
dict[str, Any]
|
are numeric ( |
dict[str, Any]
|
cells are |
Raises:
| Type | Description |
|---|---|
ParseError
|
If the datasource does not match the expected structure. |
ValueError
|
If |
Examples:
>>> datasource = extract_datasource_json(html)
>>> tables = parse_codal_tables(datasource, engine="pandas")
>>> next(iter(tables))
'گزارش فعالیت ماهانه - تولید و فروش'
Source code in src/iranquant/codal/parser.py
_fetch_and_parse
async
¶
Source code in src/iranquant/codal/parser.py
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
|
required |
engine
|
Engine
|
|
'pandas'
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The dictionary produced by :func: |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the report page cannot be downloaded. |
ParseError
|
If the page has no valid |
ValueError
|
If |
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
Monthly sales analyzer¶
monthly
¶
Monthly Codal sales analysis (LetterType=58).
The analyzer understands the standard گزارش فعالیت ماهانه - تولید و فروش
table: a product section followed by summary rows such as جمع فروش داخلی,
جمع فروش صادراتی, جمع درآمد ارائه خدمات and a final جمع row. It
returns the current-month, year-to-date and prior-year values in million Rials
(the unit used by Codal) together with Month-over-Month and Year-over-Year
growth percentages.
_DATE_PATTERN
module-attribute
¶
_MONTH_HINTS
module-attribute
¶
_YTD_HINTS
module-attribute
¶
_PRIOR_YEAR_HINTS
module-attribute
¶
_TOTAL_LABELS
module-attribute
¶
_CATEGORY_LABELS
module-attribute
¶
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: |
DEFAULT_TIMEOUT
|
max_concurrency
|
int
|
Maximum number of simultaneous requests enforced
by an internal :class: |
MAX_CONCURRENCY
|
max_retries
|
int
|
Total attempts per request. Defaults to
:data: |
MAX_RETRIES
|
retry_wait
|
float
|
Base wait used by the exponential retry backoff, in
seconds. Defaults to :data: |
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.
|
None
|
trust_env
|
bool | None
|
Whether to honour |
None
|
config
|
IranQuantConfig | None
|
TLS policy. Defaults to :class: |
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
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
|
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
|
False
|
Returns:
| Type | Description |
|---|---|
Response
|
The successful :class: |
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
|
Examples:
>>> response = await client.get("https://cdn.tsetmc.com/api/BestLimits/1")
>>> response.status_code
200
Source code in src/iranquant/core/client.py
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: |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The decoded JSON value (usually a |
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
aclose
async
¶
Close the primary and fallback HTTP transports.
Safe to call more than once. After closing, the instance must not be used again.
Examples:
Source code in src/iranquant/core/client.py
__aenter__
async
¶
__aexit__
async
¶
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:
ParseError
¶
Bases: IranQuantError
Raised when a remote payload cannot be parsed into the expected shape.
Covers invalid JSON, unexpected TSETMC/Codal schemas, malformed dEven
or hEven values, and missing var datasource blocks.
_Block
dataclass
¶
_Block(
start: int,
end: int,
kind: str,
date: tuple[int, int, int] | None,
corrected: bool,
label: str,
amount_index: int,
)
A contiguous group of columns describing one reporting period.
fetch_and_parse_report
async
¶
fetch_and_parse_report(
url_or_letter: str | CodalLetter,
engine: Engine = "pandas",
*,
client: AsyncHTTPClient | None = None,
) -> dict[str, Any]
Download a Codal report page and parse all of its datasource tables.
Relative URLs (including those on :class:~iranquant.models.codal.CodalLetter)
are resolved with :func:~iranquant.codal.search.resolve_codal_url before
the request is made.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url_or_letter
|
str | CodalLetter
|
Either an absolute/relative report URL or a
|
required |
engine
|
Engine
|
|
'pandas'
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The dictionary produced by :func: |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the report page cannot be downloaded. |
ParseError
|
If the page has no valid |
ValueError
|
If |
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
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
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CodalSearchResponse
|
class: |
CodalSearchResponse
|
|
|
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
normalize_persian
¶
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:
Source code in src/iranquant/core/normalizer.py
_is_missing
¶
_label
¶
_to_number
¶
Source code in src/iranquant/codal/monthly.py
_as_pandas
¶
Source code in src/iranquant/codal/monthly.py
_numeric_cells
¶
_select_table
¶
Pick the production & sales table, falling back to the most numeric one.
Source code in src/iranquant/codal/monthly.py
_parse_date
¶
_build_blocks
¶
Source code in src/iranquant/codal/monthly.py
_pick_period_blocks
¶
_pick_period_blocks(
blocks: list[_Block],
) -> tuple[
_Block | None,
_Block | None,
_Block | None,
_Block | None,
]
Return (current_month, previous_month, current_ytd, previous_ytd).
Source code in src/iranquant/codal/monthly.py
_pct_change
¶
_row_value
¶
_pick_total_row
¶
Source code in src/iranquant/codal/monthly.py
_aggregate
¶
_aggregate(
frame: DataFrame,
total_row: int | None,
category_rows: list[int],
column: int,
) -> float | None
Source code in src/iranquant/codal/monthly.py
analyze_monthly_sales
¶
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: |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
_letter_period
¶
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
|
client
|
AsyncHTTPClient | None
|
Optional shared :class: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The dictionary from :func: |
dict[str, Any]
|
|
dict[str, Any]
|
|
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
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |