> ## Documentation Index
> Fetch the complete documentation index at: https://docs.psxdata.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Client & core functions

> API reference for PSXClient and all psxdata module-level functions.

# Client & core functions

`psxdata` exposes two usage patterns. You can call module-level convenience functions
directly — no class instantiation needed — or create a `PSXClient` instance when you
need a dedicated cache directory or want to manage the client lifetime explicitly.

```python theme={null}
# Module-level (recommended for scripts and notebooks)
import psxdata

df = psxdata.stocks("ENGRO", start="2024-01-01", end="2024-12-31")
q  = psxdata.quote("ENGRO")

# Class-based (useful when you need a custom cache path)
from psxdata import PSXClient

client = PSXClient(cache_dir="/tmp/my-cache/")
df = client.stocks("ENGRO", start="2024-01-01")
```

Both patterns share the same underlying scrapers and caching logic. All functions that
accept a `cache` parameter respect a 15-minute TTL for intraday data; historical rows
(before today) are cached indefinitely.

***

## PSXClient

Public Python API for Pakistan Stock Exchange data. All scrapers are instantiated once
in `__init__` and reused across calls. Caching is managed by the client — scrapers
never touch the cache directly.

```python theme={null}
from psxdata import PSXClient

client = PSXClient()
df = client.stocks("ENGRO", start="2024-01-01")
```

### Constructor

**cache\_dir** `str` (default: \~/.psxdata/cache/)

Path to the on-disk cache directory. A tilde (`~`) is expanded to the current user's
home directory. The directory is created automatically if it does not exist.

**proxy** `str | dict[str, str] | None` (default: None)

Route every PSX request made by this client, including the `X-Req-Id` token fetch,
through a proxy. Pass a single URL (`http://`, `https://`, or `socks5://`, optionally
with `user:pass@`) for all traffic, or a `requests`-style dict such as
`{"http": "http://p:8080", "https": "http://p:8443"}`. SOCKS requires
`pip install "psxdata[socks]"`. Takes precedence over the `HTTP_PROXY` /
`HTTPS_PROXY` environment variables, which still apply when `proxy` is `None`.
Credentials are never logged. Added in 1.2.0. See the
[proxy guide](https://docs.psxdata.org/sdk/guides/proxy.md).

#### Exceptions

| Exception | When raised |
| - | - |
| `ValueError` | `proxy` is malformed, has no host, uses an unsupported scheme, or is an empty dict. |
| `TypeError` | `proxy` is not a string, a dict of strings, or `None`. |
| `ImportError` | A SOCKS proxy was given without the `psxdata[socks]` extra installed. |

***

## Module-level functions

### psxdata.configure()

Configure the shared default client used by all module-level functions below. It
replaces the default client, so it applies to every later `psxdata.stocks()`,
`psxdata.quote()`, etc. call. Calling it with no arguments restores the defaults.
Added in 1.2.0.

```python theme={null}
import psxdata

psxdata.configure(proxy="socks5://127.0.0.1:1080")
df = psxdata.stocks("ENGRO")

psxdata.configure()   # back to no proxy
```

#### Parameters

**proxy** `str | dict[str, str] | None` (default: None)

Keyword-only. Proxy for every PSX request, in the same forms as the
[`PSXClient`](#constructor) `proxy` argument.

#### Exceptions

Same as the `PSXClient` constructor. If `proxy` is invalid, the current default client
is left unchanged.

***

### psxdata.stocks()

Fetch historical OHLCV data for a PSX-listed symbol.

PSX returns the full price history in a single HTTP request. The response is split at
today's boundary and stored under two cache keys:

* `{SYMBOL}_historical` — rows before today, never expires.
* `{SYMBOL}_today` — rows from today, expires after 15 minutes.

Successive calls for the same symbol within the TTL window return the cached data
without a network request.

```python theme={null}
import psxdata

df = psxdata.stocks("ENGRO", start="2024-01-01", end="2024-12-31")
print(df.head())
```

#### Parameters

**symbol** `str` *required*

PSX ticker symbol, e.g. `"ENGRO"`. Case-insensitive — converted to uppercase
internally.

**start** `date | str | None` (default: None)

Start date (inclusive). Accepts a `datetime.date`, an ISO-format string such as
`"2024-01-01"`, or `None`. `None` means the earliest available date for the symbol.

**end** `date | str | None` (default: None)

End date (inclusive). Accepts the same types as `start`. `None` means today.

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch fresh data from PSX.

#### Return value

Returns a `pd.DataFrame`. Returns an empty `DataFrame` if no data is available for the
given date range.

**date** `datetime64[ns]` *required*

Trading date.

**open** `float64` *required*

Opening price.

**high** `float64` *required*

Intraday high price.

**low** `float64` *required*

Intraday low price.

**close** `float64` *required*

Closing price.

**volume** `int64` *required*

Number of shares traded.

**is\_anomaly** `bool` *required*

`True` if the row was flagged as anomalous during scraping (e.g. zero-volume days
with unchanged prices). Useful for filtering before analysis.

#### Exceptions

| Exception | When raised |
| - | - |
| `ValueError` | `start` is after `end`. |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.quote()

Fetch the latest screener snapshot for a symbol.

The full screener (approximately 729 symbols) is fetched in a single request and cached
for 15 minutes. Successive calls for different symbols reuse the same cached screener,
so only the first call within a 15-minute window incurs a network request.

```python theme={null}
import psxdata

q = psxdata.quote("ENGRO")
print(q.T)
```

#### Parameters

**symbol** `str` *required*

PSX ticker symbol, e.g. `"ENGRO"`. Case-insensitive.

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch the full screener.

#### Return value

Returns a single-row `pd.DataFrame` with screener columns. Returns an empty `DataFrame`
if the symbol is not present in the screener.

**symbol** `object` *required*

PSX ticker symbol.

**sector** `object` *required*

Sector name as listed on PSX.

**ldcp** `float64` *required*

Last day's closing price.

**price** `float64` *required*

Current market price.

**market\_cap** `float64` *required*

Market capitalisation in PKR.

**pe\_ratio** `float64` *required*

Price-to-earnings ratio. May be `NaN` for loss-making companies.

**dividend\_yield** `float64` *required*

Trailing dividend yield as a decimal, e.g. `0.045` for 4.5 %.

**change** `float64` *required*

Absolute price change from LDCP.

**change\_pct** `float64` *required*

Percentage price change from LDCP.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.screener()

Return the full PSX screener table, unfiltered.

Shares the same `"screener_all"` cache key as `quote()`, so calling both within the same
15-minute window never results in a double network request.

```python theme={null}
import psxdata

df = psxdata.screener()
print(df.nlargest(10, "market_cap")[["symbol", "market_cap"]])
```

#### Parameters

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch the full screener.

#### Return value

Returns a `pd.DataFrame` with one row per PSX-listed symbol (approximately 729 rows).
Returns an empty `DataFrame` if PSX returns no data.

**symbol** `object` *required*

PSX ticker symbol.

**sector** `float64` *required*

Raw numeric sector code as returned by PSX — not enriched to a sector name. Join
against `psxdata.symbols()` on `sector_name` if you need the sector label.

**listed\_in** `object` *required*

Market board the symbol is listed in.

**market\_cap** `float64` *required*

Market capitalisation in PKR.

**price** `float64` *required*

Current market price.

**pe\_ratio** `float64` *required*

Price-to-earnings ratio. May be `NaN` for loss-making companies.

**dividend\_yield** `float64` *required*

Trailing dividend yield as a decimal, e.g. `0.045` for 4.5 %.

**free\_float** `float64` *required*

Free-float shares as a percentage of total shares outstanding.

**volume\_avg\_30d** `float64` *required*

30-day average trading volume.

**change\_1y\_pct** `float64` *required*

Percentage price change over the trailing 1 year.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.tickers()

Return PSX ticker symbols, optionally filtered to a named index.

```python theme={null}
import psxdata

# All listed symbols
all_tickers = psxdata.tickers()

# KSE-100 constituents only
kse100 = psxdata.tickers(index="KSE100")
print(f"KSE-100 has {len(kse100)} stocks")
```

`tickers(index="KSE100")` and `indices("KSE100")` share the same cache key
(`indices_KSE100`), so calling both methods never results in a double network request.

#### Parameters

**index** `str | None` (default: None)

Index name, e.g. `"KSE100"`. `None` returns all listed symbols. See
`psxdata/constants.py` (`INDEX_NAMES`) for the full list of valid names.

**cache** `bool` (default: True)

If `False`, bypass the local cache.

#### Return value

Returns `list[str]` — ticker strings, e.g. `["ENGRO", "LUCK", ...]`. Returns an empty
list if no symbols are found.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |
| `PSXParseError` | PSX returned 4xx for the given index name (unknown index). |

***

### psxdata.symbols()

Return all listed PSX symbols with sector names.

Reuses the `symbols_all` cache key shared with `tickers(index=None)`, so calling both
functions never results in a double network request.

```python theme={null}
import psxdata

df = psxdata.symbols()
print(df[df["sector_name"] == "CEMENT"]["symbol"].tolist())
```

#### Parameters

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch fresh data from PSX.

#### Return value

Returns a `pd.DataFrame`. Returns an empty `DataFrame` if PSX returns no data.

**symbol** `object` *required*

PSX ticker symbol.

**name** `object` *required*

Full company or instrument name.

**sector\_name** `object` *required*

Full sector name, e.g. `"CEMENT"`. Useful for filtering symbols by sector.

**is\_etf** `bool` *required*

`True` if the symbol is an exchange-traded fund.

**is\_debt** `bool` *required*

`True` if the symbol is a debt instrument (e.g. a TFC).

**is\_gem** `bool` *required*

`True` if the symbol is listed on the Growth Enterprise Market (GEM) board.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.indices()

Fetch constituent data for a PSX index.

Returns detailed per-stock data for every constituent of the named index, including
index weights and market capitalisation figures.

```python theme={null}
import psxdata

df = psxdata.indices("KSE100")
print(df.nlargest(10, "idx_weight")[["symbol", "idx_weight"]])
```

#### Parameters

**name** `str` *required*

Index name, e.g. `"KSE100"`. See `psxdata/constants.py` (`INDEX_NAMES`) for valid
values.

**cache** `bool` (default: True)

If `False`, bypass the local cache.

#### Return value

Returns a `pd.DataFrame`. Returns an empty `DataFrame` if PSX returns no data for the
given index name.

**symbol** `object` *required*

PSX ticker symbol.

**current\_index** `float64` *required*

Current index level contributed by this constituent.

**idx\_weight** `float64` *required*

Weight of the constituent in the index, as a percentage.

**idx\_point** `float64` *required*

Index points contributed by this constituent.

**market\_cap\_m** `float64` *required*

Market capitalisation in millions of PKR.

**freefloat\_m** `float64`

Free-float market capitalisation in millions of PKR. Present for free-float-weighted
indices (e.g. KSE100). Absent for indices that use total shares.

**shares\_m** `float64`

Total shares in millions. Present for indices that use total shares weighting. Absent
when `freefloat_m` is present.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |
| `PSXParseError` | PSX returned 4xx for the given index name (unknown index). |

***

### psxdata.sectors()

Fetch the PSX sector summary.

Returns one row per sector with advance/decline breadth and aggregate market
capitalisation figures.

```python theme={null}
import psxdata

df = psxdata.sectors()
print(df.sort_values("market_cap_b", ascending=False).head())
```

#### Parameters

**cache** `bool` (default: True)

If `False`, bypass the local cache.

#### Return value

Returns a `pd.DataFrame`.

**sector\_code** `object` *required*

Short sector identifier code used internally by PSX.

**sector\_name** `object` *required*

Full sector name.

**advance** `int64` *required*

Number of stocks that advanced (price increased) in the session.

**decline** `int64` *required*

Number of stocks that declined (price decreased) in the session.

**unchanged** `int64` *required*

Number of stocks with no price change in the session.

**turnover** `float64` *required*

Total sector turnover in PKR for the session.

**market\_cap\_b** `float64` *required*

Aggregate sector market capitalisation in billions of PKR.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.fundamentals()

Fetch the PSX financial reports filing list.

PSX returns all filings in a single request. When `symbol` is provided, the result is
filtered in memory — no additional network requests are made.

```python theme={null}
import psxdata

# All filings
df = psxdata.fundamentals()

# Filings for a specific company
df = psxdata.fundamentals("ENGRO")
print(df)
```

#### Parameters

**symbol** `str | None` (default: None)

If provided, return only filings for this ticker. Case-insensitive. `None` returns
all available filings.

**cache** `bool` (default: True)

If `False`, bypass the local cache.

#### Return value

Returns a `pd.DataFrame`. Returns an empty `DataFrame` if outside the reporting season
or if PSX returns no data.

**symbol** `object` *required*

PSX ticker symbol of the filing company.

**year** `int64` *required*

Financial year to which the filing belongs.

**type** `object` *required*

Report type, e.g. `"Annual"`, `"Half Yearly"`, `"Quarterly"`.

**period\_ended** `object` *required*

End date of the reporting period (formatted string as returned by PSX).

**posting\_date** `object` *required*

Date the filing was posted to PSX.

**posting\_time** `object` *required*

Time the filing was posted to PSX.

**document** `object` *required*

URL or filename of the filing document.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.debt\_market()

Fetch all PSX debt market instrument tables.

Returns 4 tables covering the various instrument categories listed on the
[PSX debt market page](https://www.psx.com.pk/market-data/debt-market). The page does
not include `<h2>` headings before its tables, so the keys are positional rather than
descriptive.

```python theme={null}
import psxdata

tables = psxdata.debt_market()
for key, df in tables.items():
    print(key, df.shape)
```

#### Parameters

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch from PSX.

#### Return value

Returns `dict[str, pd.DataFrame]` — a mapping of table keys to DataFrames. Returns an
empty `dict` if no tables are found on the page.

| Key | Contents |
| - | - |
| `table_0` | First debt market instrument table. |
| `table_1` | Second debt market instrument table. |
| `table_2` | Third debt market instrument table. |
| `table_3` | Fourth debt market instrument table. |

These key names are load-bearing. Do not rely on positional integer indexing —
always use the string keys `"table_0"` through `"table_3"`.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |

***

### psxdata.eligible\_scrips()

Fetch all PSX margin-trading eligible scrip tables.

Returns 9 tables covering the instrument categories listed on the
[PSX eligible scrips page](https://www.psx.com.pk/market-data/eligible-scrips). The
`<h2>` headings on that page are not direct siblings of the `<table>` elements, so
keys are positional rather than descriptive.

```python theme={null}
import psxdata

tables = psxdata.eligible_scrips()
for key, df in tables.items():
    print(key, df.shape)
```

#### Parameters

**cache** `bool` (default: True)

If `False`, bypass the local cache and always fetch from PSX.

#### Return value

Returns `dict[str, pd.DataFrame]` — a mapping of table keys to DataFrames. Returns an
empty `dict` if no tables are found on the page.

| Key | Contents |
| - | - |
| `table_0` | First eligible scrips table. |
| `table_1` | Second eligible scrips table. |
| `table_2` | Third eligible scrips table. |
| `table_3` | Fourth eligible scrips table. |
| `table_4` | Fifth eligible scrips table. |
| `table_5` | Sixth eligible scrips table. |
| `table_6` | Seventh eligible scrips table. |
| `table_7` | Eighth eligible scrips table. |
| `table_8` | Ninth eligible scrips table. |

These key names are load-bearing. Do not rely on positional integer indexing —
always use the string keys `"table_0"` through `"table_8"`.

#### Exceptions

| Exception | When raised |
| - | - |
| `PSXConnectionError` | Network failure after all retries. |
| `PSXServerError` | PSX returned a 5xx response after all retries. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.