Market API¶
Low-level asynchronous market functions. Use them with a shared
iranquant.core.client.AsyncHTTPClient, or through
iranquant.AsyncIranQuant / the synchronous wrappers.
Symbols¶
symbol
¶
Symbol search and instrument-code resolution with in-memory caching.
SYMBOL_SEARCH_URL
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.
SymbolNotFoundError
¶
Bases: IranQuantError
Raised when a symbol cannot be resolved to a TSETMC instrument code.
Examples:
InstrumentSearchItem
¶
Bases: TSETMCBaseModel
InstrumentSearchResponse
¶
Bases: TSETMCBaseModel
int_to_date_optional
¶
Convert a TSETMC dEven to a date, returning None for sentinels.
Values such as 0 and 1 are emitted for inactive/expired instruments
and placeholder rows. Anything outside [19000101, 21001231] — or not a
valid calendar date — yields None instead of raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int | None
|
An eight-digit Gregorian date encoded as an integer, or |
required |
Returns:
| Type | Description |
|---|---|
date | None
|
The decoded :class: |
date | None
|
values. |
Examples:
>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
int_to_jdate_optional
¶
Jalali counterpart of :func:int_to_date_optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int | None
|
An eight-digit Gregorian date encoded as an integer, or |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The Jalali date as |
Examples:
Source code in src/iranquant/core/normalizer.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
instrument_to_dict
¶
Standardize a search result into a user-facing record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
InstrumentSearchItem
|
A raw :class: |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with the following keys: |
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]
|
|
Examples:
Source code in src/iranquant/market/symbol.py
search_symbol
async
¶
Search TSETMC instruments by symbol or company name.
The query is Persian-normalized before it is sent. Results are memoized in-process by normalized query, so repeated searches do not hit the network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
query
|
str
|
Symbol or company-name fragment, e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[InstrumentSearchItem]
|
Matching instruments. An empty query returns an empty list without a |
list[InstrumentSearchItem]
|
request. |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If |
ParseError
|
If the response does not match the expected schema. |
Examples:
Source code in src/iranquant/market/symbol.py
_is_active
¶
get_inscode
async
¶
Resolve a symbol to its TSETMC instrument code (insCode).
Matching is done on normalized lVal18AFC values. Instruments with an
active flow (1, 2 or 4) are preferred; ties are broken by the newest
lastDate. Results are cached in-process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
symbol
|
str
|
Persian ticker, e.g. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The numeric |
Raises:
| Type | Description |
|---|---|
SymbolNotFoundError
|
If the symbol is empty or no exact normalized match exists. |
NetworkError
|
If the search request fails. |
ParseError
|
If the search response is malformed. |
Examples:
Source code in src/iranquant/market/symbol.py
clear_cache
¶
Clear the in-memory symbol caches (mainly useful in tests).
Clears both the search-results cache and the insCode resolution cache
for the current process.
Examples:
Source code in src/iranquant/market/symbol.py
History and adjustment¶
history
¶
Daily OHLCV, client-type history and backward price adjustment.
CLIENT_TYPE_HISTORY_URL
module-attribute
¶
DAILY_HISTORY_URL
module-attribute
¶
SHARE_CHANGE_URL
module-attribute
¶
PRICE_COLUMNS
module-attribute
¶
HISTORY_COLUMNS
module-attribute
¶
HISTORY_COLUMNS = [
"date",
"jdate",
"open",
"high",
"low",
"close",
"final_price",
"prev_price",
"volume",
"value",
"trades",
]
CLIENT_TYPE_COLUMNS
module-attribute
¶
CLIENT_TYPE_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",
"sell_I_Count",
]
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.
ClientTypeResponse
¶
Bases: TSETMCBaseModel
ClosingPriceDailyResponse
¶
Bases: TSETMCBaseModel
InstrumentDPS
¶
Bases: TSETMCBaseModel
InstrumentDPSResponse
¶
Bases: TSETMCBaseModel
InstrumentShareChange
¶
Bases: TSETMCBaseModel
InstrumentShareChangeResponse
¶
Bases: TSETMCBaseModel
to_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'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
DataFrame
|
class: |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
int_to_date
¶
Convert a TSETMC dEven integer (e.g. 20261028) to a date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int
|
An eight-digit Gregorian date encoded as an integer. |
required |
Returns:
| Type | Description |
|---|---|
date
|
The corresponding :class: |
Raises:
| Type | Description |
|---|---|
ParseError
|
If the value is longer than eight digits or is not a valid calendar date. |
Examples:
Source code in src/iranquant/core/normalizer.py
int_to_date_optional
¶
Convert a TSETMC dEven to a date, returning None for sentinels.
Values such as 0 and 1 are emitted for inactive/expired instruments
and placeholder rows. Anything outside [19000101, 21001231] — or not a
valid calendar date — yields None instead of raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int | None
|
An eight-digit Gregorian date encoded as an integer, or |
required |
Returns:
| Type | Description |
|---|---|
date | None
|
The decoded :class: |
date | None
|
values. |
Examples:
>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
int_to_jdate
¶
Convert a TSETMC dEven integer to a Jalali YYYY-MM-DD string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int
|
An eight-digit Gregorian date encoded as an integer. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The Jalali (Solar Hijri) date as a zero-padded |
Raises:
| Type | Description |
|---|---|
ParseError
|
If |
Examples:
Source code in src/iranquant/core/normalizer.py
_validate
¶
apply_gap_adjustment
¶
Backward-adjust prices using the priceYesterday gap ratio.
priceYesterday on day t already reflects any dividend or capital
increase applied between t-1 and t, while final_price on day t-1
is unadjusted. The cumulative factor is therefore computed backwards from
the newest day (factor 1.0) and applied to all price columns.
For i = n-2 ... 0 the per-day ratio is
r[i] = prev_price[i+1] / final_price[i] and the cumulative factor is
F[i] = F[i+1] * r[i]. Every column in PRICE_COLUMNS
(open, high, low, close, final_price, prev_price)
is multiplied by F[i]. The input list is never mutated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list[dict[str, Any]]
|
Chronologically ascending daily records produced by
:func: |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
A new list of copied records with adjusted float prices. Records with |
list[dict[str, Any]]
|
fewer than two rows are returned as shallow copies. |
Examples:
>>> rows = [
... {"final_price": 100.0, "prev_price": 100.0, "open": 100.0,
... "high": 100.0, "low": 100.0, "close": 100.0},
... {"final_price": 100.0, "prev_price": 90.0, "open": 100.0,
... "high": 100.0, "low": 100.0, "close": 100.0},
... ]
>>> apply_gap_adjustment(rows)[0]["final_price"]
90.0
Source code in src/iranquant/market/history.py
apply_capital_adjustment
¶
apply_capital_adjustment(
records: list[dict[str, Any]],
share_changes: list[InstrumentShareChange],
) -> list[dict[str, Any]]
Adjust prices backwards for capital increases only.
For an increase from numberOfShareOld to numberOfShareNew the
historical prices preceding the event are multiplied by
old / new (the theoretical ex-rights ratio).
Events with non-positive share counts or an invalid dEven are ignored.
A record exactly on the event date is not adjusted; only strictly earlier
records are. The input list is never mutated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list[dict[str, Any]]
|
Chronologically ascending daily records with a
|
required |
share_changes
|
list[InstrumentShareChange]
|
Corporate-action events from
:func: |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
A new list of copied records whose |
list[dict[str, Any]]
|
cumulative |
Examples:
>>> event = InstrumentShareChange(
... dEven=20261028, numberOfShareOld=100.0, numberOfShareNew=200.0
... )
>>> apply_capital_adjustment(records, [event])[0]["open"]
50.0
Source code in src/iranquant/market/history.py
get_share_changes
async
¶
Fetch the capital-increase history of an instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
Returns:
| Type | Description |
|---|---|
list[InstrumentShareChange]
|
Share-change events, each exposing |
list[InstrumentShareChange]
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the endpoint cannot be reached. |
ParseError
|
If the payload does not match the expected schema. |
Examples:
get_dps
async
¶
Fetch dividend-per-share (DPS) events for an instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
Returns:
| Type | Description |
|---|---|
list[InstrumentDPS]
|
DPS events with |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the endpoint cannot be reached. |
ParseError
|
If the payload does not match the expected schema. |
Examples:
Source code in src/iranquant/market/history.py
_daily_records
async
¶
_daily_records(
client: AsyncHTTPClient,
ins_code: str,
*,
adjust: AdjustMode,
) -> list[dict[str, Any]]
Source code in src/iranquant/market/history.py
_empty_frame
¶
Source code in src/iranquant/market/history.py
_client_type_records
¶
Source code in src/iranquant/market/history.py
get_daily_history
async
¶
get_daily_history(
client: AsyncHTTPClient,
ins_code: str,
*,
adjust: AdjustMode = "all",
engine: Engine = "pandas",
) -> DataFrame
Fetch standardized daily OHLCV history for an instrument.
Sentinel dates (dEven below 19000101) and placeholder rows with no
volume and no trades are dropped, then rows are sorted by date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
adjust
|
AdjustMode
|
Price adjustment mode.
|
'all'
|
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with one row per trading day and the following columns: |
DataFrame
|
============== ================= ===================================== |
DataFrame
|
Column Type Description |
DataFrame
|
============== ================= ===================================== |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
============== ================= ===================================== |
DataFrame
|
An empty frame with the same columns is returned when no valid rows |
DataFrame
|
remain. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NetworkError
|
If TSETMC cannot be reached. |
ParseError
|
If the payload does not match the expected schema. |
Examples:
>>> frame = await get_daily_history(client, "46348559193224090")
>>> frame.columns.tolist()[:5]
['date', 'jdate', 'open', 'high', 'low']
>>> frame = await get_daily_history(
... client, "46348559193224090", adjust="none", engine="polars"
... )
Source code in src/iranquant/market/history.py
get_client_type_history
async
¶
get_client_type_history(
client: AsyncHTTPClient,
ins_code: str,
*,
engine: Engine = "pandas",
) -> DataFrame
Fetch retail/institutional (حقیقی/حقوقی) client-type history.
I columns describe individual/retail (حقیقی) activity and N columns
describe institutional/legal (حقوقی) activity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame sorted by |
DataFrame
|
================= ================= ================================== |
DataFrame
|
Column Type Description |
DataFrame
|
================= ================= ================================== |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
================= ================= ================================== |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If TSETMC cannot be reached. |
ParseError
|
If the payload does not match the expected schema. |
ValueError
|
If |
Examples:
>>> frame = await get_client_type_history(client, "46348559193224090")
>>> frame[["date", "buy_I_Volume", "sell_N_Count"]].tail(1)
Source code in src/iranquant/market/history.py
get_full_history
async
¶
get_full_history(
client: AsyncHTTPClient,
ins_code: str,
*,
adjust: AdjustMode = "all",
engine: Engine = "pandas",
) -> DataFrame
Merge daily OHLCV with client-type history on the trading date.
The two requests are performed sequentially and merged with an outer join
on date (so dates missing from either source are retained), then sorted
ascending. The client-type jdate column is dropped, leaving a single
jdate from the OHLCV frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
adjust
|
AdjustMode
|
Price adjustment mode, identical to
:func: |
'all'
|
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with the eleven :func: |
DataFrame
|
the twelve client-type columns below ( |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
When both sources are empty an empty frame is returned. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NetworkError
|
If either request fails. |
ParseError
|
If either payload is malformed. |
Examples:
>>> frame = await get_full_history(client, "46348559193224090")
>>> {"open", "final_price", "buy_I_Volume"} <= set(frame.columns)
True
Source code in src/iranquant/market/history.py
Live data¶
live
¶
Live market data: MarketWatch, order book and intraday trades.
MARKET_WATCH_URL
module-attribute
¶
MARKET_WATCH_URL = (
TSETMC_CDN
+ "/api/ClosingPrice/GetMarketWatch"
+ "?market=0&industrialGroup="
+ "&paperTypes[0]=1&paperTypes[1]=2&paperTypes[2]=8"
+ "&showTraded=false&withBestLimits=true"
)
TRADE_INTRADAY_URL
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
¶
BestLimitResponse
¶
Bases: TSETMCBaseModel
MarketWatchResponse
¶
Bases: TSETMCBaseModel
TradeIntraDayResponse
¶
Bases: TSETMCBaseModel
to_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'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
DataFrame
|
class: |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
int_to_time_optional
¶
Convert a TSETMC hEven to a time, returning None when invalid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_even
|
int | None
|
A |
required |
Returns:
| Type | Description |
|---|---|
time | None
|
The decoded :class: |
time | None
|
valid time between |
Examples:
Source code in src/iranquant/core/normalizer.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
_first_value
¶
Return the first value that is not None (older/newer field names).
get_market_watch
async
¶
Fetch the entire market snapshot in a single request.
The request is sent verbatim (raw=True) so the bracketed
paperTypes[0]=1 query is never percent-encoded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per symbol with the following columns: |
DataFrame
|
================= ========================== ======================= |
DataFrame
|
Column Type Description |
DataFrame
|
================= ========================== ======================= |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
================= ========================== ======================= |
DataFrame
|
|
DataFrame
|
|
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 get_market_watch(client)
>>> market[["symbol", "close", "tmax"]].head()
>>> book = market.iloc[0]["order_book"]
>>> book[0]["zmd"] # best bid volume
Source code in src/iranquant/market/live.py
get_order_book
async
¶
get_order_book(
client: AsyncHTTPClient,
ins_code: str,
*,
engine: Engine = "pandas",
) -> DataFrame
Fetch the best-limit order book (levels 1..5) for an instrument.
Rows are sorted by level number. The d/o suffixes mean demand
(buy) and offer (sell) respectively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with one row per visible level and these columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the endpoint cannot be reached. |
ParseError
|
If the response body is not valid JSON. |
ValidationError
|
If the payload does not match the schema. |
Examples:
>>> book = await get_order_book(client, "46348559193224090")
>>> book.iloc[0][["pmd", "zmd", "pmo", "zmo"]]
Source code in src/iranquant/market/live.py
get_intraday_trades
async
¶
get_intraday_trades(
client: AsyncHTTPClient,
ins_code: str,
*,
engine: Engine = "pandas",
) -> DataFrame
Fetch intraday OHLCV bars for the current/last trading session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
ins_code
|
str
|
TSETMC instrument code. |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per intraday bar, in server order, with these columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
NetworkError
|
If the endpoint cannot be reached. |
ParseError
|
If the response body is not valid JSON. |
ValidationError
|
If the payload does not match the schema. |
Examples:
>>> bars = await get_intraday_trades(client, "46348559193224090")
>>> bars[["time", "close", "volume"]].tail()
Source code in src/iranquant/market/live.py
Indices¶
index
¶
Live and historical index data (overall, equal-weight and sector indices).
INDEX_B1_HISTORY_URL
module-attribute
¶
INDEX_B2_HISTORY_URL
module-attribute
¶
INDEX_SECTORS_LIVE_URL
module-attribute
¶
MARKET_OVERVIEW_URL
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
¶
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.
to_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'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
DataFrame
|
class: |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
int_to_date_optional
¶
Convert a TSETMC dEven to a date, returning None for sentinels.
Values such as 0 and 1 are emitted for inactive/expired instruments
and placeholder rows. Anything outside [19000101, 21001231] — or not a
valid calendar date — yields None instead of raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int | None
|
An eight-digit Gregorian date encoded as an integer, or |
required |
Returns:
| Type | Description |
|---|---|
date | None
|
The decoded :class: |
date | None
|
values. |
Examples:
>>> int_to_date_optional(20261028)
datetime.date(2026, 10, 28)
>>> int_to_date_optional(0) is None
True
Source code in src/iranquant/core/normalizer.py
int_to_jdate_optional
¶
Jalali counterpart of :func:int_to_date_optional.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_even
|
int | None
|
An eight-digit Gregorian date encoded as an integer, or |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The Jalali date as |
Examples:
Source code in src/iranquant/core/normalizer.py
int_to_time_optional
¶
Convert a TSETMC hEven to a time, returning None when invalid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h_even
|
int | None
|
A |
required |
Returns:
| Type | Description |
|---|---|
time | None
|
The decoded :class: |
time | None
|
valid time between |
Examples:
Source code in src/iranquant/core/normalizer.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
_to_float
¶
_extract_items
¶
Source code in src/iranquant/market/index.py
_normalize_index
¶
Standardize an index row from either the live or history endpoints.
Source code in src/iranquant/market/index.py
get_indices_live
async
¶
Fetch live overall, equal-weight and sector index snapshots.
Uses MarketData/GetMarketOverview/1 for the overall and equal-weight
indices and Index/GetIndexB1LastAll/0/1 for sector indices. The two
requests run concurrently; if one fails but the other returns data, the
partial result is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with at least the following standardized columns: |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
Rows for the overall ( |
DataFrame
|
( |
DataFrame
|
|
DataFrame
|
extra raw TSETMC field alongside the standardized columns. |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If both requests fail and no rows can be produced. |
Examples:
>>> indices = await get_indices_live(client)
>>> indices[["index_code", "name", "index_value"]].head()
Source code in src/iranquant/market/index.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 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 173 174 | |
get_index_history
async
¶
get_index_history(
client: AsyncHTTPClient,
index_code: str = OVERALL_INDEX_CODE,
*,
engine: Engine = "pandas",
) -> DataFrame
Fetch historical daily values for an index code.
Falls back to the B1 endpoint when the B2 endpoint is unavailable. Rows
are sorted ascending by date; rows without a parseable date sort first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncHTTPClient
|
An open :class: |
required |
index_code
|
str
|
TSETMC index code. Defaults to
:data: |
OVERALL_INDEX_CODE
|
engine
|
Engine
|
|
'pandas'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with the same standardized columns as |
DataFrame
|
func: |
DataFrame
|
|
DataFrame
|
upstream fields (for example |
Raises:
| Type | Description |
|---|---|
NetworkError
|
If both the B2 and B1 endpoints fail. |
ParseError
|
If a returned body is not valid JSON. |
ValueError
|
If |
Examples:
>>> overall = await get_index_history(client)
>>> overall[["date", "index_value"]].tail()
>>> equal = await get_index_history(
... client, EQUAL_WEIGHT_INDEX_CODE, engine="polars"
... )