Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

---

## [0.8.0] — 2026-11-13

### Added

- `badge` and `ex_flag` on `/screener` rows, `/stocks/{symbol}/quote` and `/indices/{name}` constituents (from psxdata 1.5.0). `ex_flag` is the corporate-action badge PSX shows next to a ticker (`XD` ex-dividend, `XB` ex-bonus, `XR` ex-rights), or `null`; `badge` is any badge (e.g. `NC`). Tickers stay plain.

### Changed

- Upgrade to psxdata 1.5.0 (GitHub release archive).

---

## [0.7.1] — 2026-11-13

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion api/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.7.1"
__version__ = "0.8.0"
2 changes: 1 addition & 1 deletion api/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# API layer dependencies — installs psxdata from PyPI + FastAPI stack
psxdata @ https://github.com/psxdata/psxdata/archive/refs/tags/v1.4.0.zip # TODO: back to psxdata==1.4.0 once on PyPI
psxdata @ https://github.com/psxdata/psxdata/archive/refs/tags/v1.5.0.zip # TODO: back to psxdata==1.5.0 once on PyPI
fastapi[standard]>=0.142.0,<0.143
opentelemetry-sdk>=1.45,<1.46
uvicorn[standard]~=0.23
Expand Down
5 changes: 4 additions & 1 deletion api/routers/indices.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def get_index(

rows: list[IndexConstituentRow] = []
if not df.empty:
df = df.where(pd.notna(df), other=None)
# object dtype first so nullable string columns (badge, ex_flag) give None
df = df.astype(object).where(pd.notna(df), other=None)
for record in df.to_dict("records"):
rows.append(
IndexConstituentRow(
Expand All @@ -57,6 +58,8 @@ def get_index(
market_cap_m=record.get("market_cap_m", 0.0),
freefloat_m=record.get("freefloat_m"),
shares_m=record.get("shares_m"),
badge=record.get("badge"),
ex_flag=record.get("ex_flag"),
)
)
return IndexConstituentResponse(
Expand Down
45 changes: 45 additions & 0 deletions api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ class QuoteData(BaseModel):
default=None,
description="Sector name for sector_code, e.g. \"FERTILIZER\"; null if unknown.",
)
badge: str | None = Field(
default=None,
description=(
"Badge PSX shows next to the ticker (XD, XB, XR, NC, ...; several joined with +); "
"null if none."
),
)
ex_flag: str | None = Field(
default=None,
description=(
"Corporate-action badge only: XD ex-dividend, XB ex-bonus, XR ex-rights; "
"null otherwise. "
"A stock that goes ex drops by about the dividend or entitlement without a real loss."
),
)


class QuoteResponse(BaseModel):
Expand Down Expand Up @@ -133,6 +148,21 @@ class IndexConstituentRow(BaseModel):
market_cap_m: float
freefloat_m: float | None = None
shares_m: float | None = None
badge: str | None = Field(
default=None,
description=(
"Badge PSX shows next to the ticker (XD, XB, XR, NC, ...; several joined with +); "
"null if none."
),
)
ex_flag: str | None = Field(
default=None,
description=(
"Corporate-action badge only: XD ex-dividend, XB ex-bonus, XR ex-rights; "
"null otherwise. "
"A stock that goes ex drops by about the dividend or entitlement without a real loss."
),
)


class IndexConstituentResponse(BaseModel):
Expand Down Expand Up @@ -191,6 +221,21 @@ class ScreenerRow(BaseModel):
default=None,
description="Sector name for sector_code, e.g. \"FERTILIZER\"; null if unknown.",
)
badge: str | None = Field(
default=None,
description=(
"Badge PSX shows next to the ticker (XD, XB, XR, NC, ...; several joined with +); "
"null if none."
),
)
ex_flag: str | None = Field(
default=None,
description=(
"Corporate-action badge only: XD ex-dividend, XB ex-bonus, XR ex-rights; "
"null otherwise. "
"A stock that goes ex drops by about the dividend or entitlement without a real loss."
),
)


class ScreenerResponse(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ readme = "README.md"
requires-python = ">=3.11"
license = {file = "LICENSE.md"}
dependencies = [
"psxdata[socks] @ https://github.com/psxdata/psxdata/archive/refs/tags/v1.4.0.zip", # TODO: back to ==1.4.0 once on PyPI
"psxdata[socks] @ https://github.com/psxdata/psxdata/archive/refs/tags/v1.5.0.zip", # TODO: back to ==1.5.0 once on PyPI
"fastapi[standard]>=0.142.0,<0.143",
"opentelemetry-sdk>=1.45,<1.46",
"uvicorn[standard]>=0.23",
Expand Down
18 changes: 18 additions & 0 deletions tests/api/test_indices.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,21 @@ def test_get_index_psx_unavailable_returns_503(client: TestClient) -> None:
resp = client.get("/indices/KSE100")
assert resp.status_code == 503
assert resp.json()["error"]["code"] == "psx_unavailable"


def test_index_constituents_include_ex_flag(client: TestClient) -> None:
"""badge/ex_flag (StringDtype from psxdata >= 1.5.0) pass through; <NA> becomes null."""
df = pd.DataFrame({
"symbol": ["ABL", "LUCK"],
"current_index": [1.0, 1.0],
"idx_weight": [1.0, 1.0],
"idx_point": [1.0, 1.0],
"market_cap_m": [1.0, 1.0],
"badge": pd.array(["XD", pd.NA], dtype="string"),
"ex_flag": pd.array(["XD", pd.NA], dtype="string"),
})
with patch("psxdata.indices", return_value=df):
resp = client.get("/indices/KSE100")
rows = {r["symbol"]: r for r in resp.json()["data"]}
assert rows["ABL"]["ex_flag"] == "XD" and rows["ABL"]["badge"] == "XD"
assert rows["LUCK"]["ex_flag"] is None and rows["LUCK"]["badge"] is None
3 changes: 2 additions & 1 deletion tests/api/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ def test_hit_is_served_without_contacting_proxy(self, client, make_passthrough):
def test_hit_on_data_cached_by_another_caller(self, client, make_passthrough, tmp_path):
make_passthrough(resolver=refuse_network, connector=refuse_network)
PSXClient(cache_dir=str(tmp_path / "cache"))._cache.set(
"screener_snapshot", _screener_df().assign(sector_code="0007", sector_name="X")
"screener_snapshot",
_screener_df().assign(sector_code="0007", sector_name="X", badge=None, ex_flag=None),
)
with fake_psx(ScreenerScraper, _screener_df()) as reached:
resp = _proxied(client, "/stocks/ENGRO/quote")
Expand Down
13 changes: 13 additions & 0 deletions tests/api/test_screener.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,16 @@ def test_list_screener_includes_sector_code_and_name(client: TestClient) -> None
rows = {r["symbol"]: r for r in resp.json()["data"]}
assert (rows["FFC"]["sector_code"], rows["FFC"]["sector_name"]) == ("0809", "FERTILIZER")
assert rows["PIAA"]["sector_code"] is None and rows["PIAA"]["sector_name"] is None


def test_list_screener_includes_ex_flag(client: TestClient) -> None:
df = pd.DataFrame({
"symbol": ["ABL", "AAL"],
"price": [171.7, 1.0],
"badge": pd.array(["XD", "NC"], dtype="string"),
"ex_flag": pd.array(["XD", pd.NA], dtype="string"),
})
with patch("psxdata.screener", return_value=df):
rows = {r["symbol"]: r for r in client.get("/screener").json()["data"]}
assert (rows["ABL"]["badge"], rows["ABL"]["ex_flag"]) == ("XD", "XD")
assert (rows["AAL"]["badge"], rows["AAL"]["ex_flag"]) == ("NC", None)
10 changes: 10 additions & 0 deletions tests/api/test_stocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ def test_quote_includes_sector_code_and_name(client: TestClient) -> None:
assert resp.json()["data"]["sector_name"] is None


def test_quote_includes_ex_flag(client: TestClient) -> None:
df = pd.DataFrame({
"symbol": ["ABL"], "price": [171.7],
"badge": pd.array(["XD"], dtype="string"), "ex_flag": pd.array(["XD"], dtype="string"),
})
with patch("psxdata.quote", return_value=df):
data = client.get("/stocks/ABL/quote").json()["data"]
assert (data["badge"], data["ex_flag"]) == ("XD", "XD")


def test_quote_returns_404_for_unknown_symbol(client: TestClient) -> None:
screener = pd.DataFrame({"symbol": ["ENGRO", "LUCKXD"], "price": [481.99, 1100.0]})
with (
Expand Down
Loading