pypsx-toolkit — Pakistan Stock Exchange Data Library
A clean, simple Python library to fetch and analyze Pakistan Stock Exchange (PSX) market data. Get real-time market data, historical prices, and powerful analysis tools all in one package — no authentication required.
Installation
pip install pypsx-toolkit
Try it in a notebook
Quick Start
Basic Usage - Get Stock Information
import pypsx_toolkit
# Create a ticker object for any stock symbol
ticker = pypsx_toolkit.PSXTicker("OGDC") # or use pypsx_toolkit.Ticker("OGDC")
# Get company information
info = ticker.info
print(f"Company: {info.get('Sector')}")
print(f"Current Price: {info.get('Current')}")
# Get comprehensive snapshot data (OHLCV, bid/ask, circuit breaker, ranges, ratios, etc.)
snapshot = ticker.snapshot
print(f"Open: {snapshot.get('REG', {}).get('Open')}")
print(f"High: {snapshot.get('REG', {}).get('High')}")
print(f"52-Week Range: {snapshot.get('REG', {}).get('52-WEEK RANGE ^')}")
print(f"P/E Ratio: {snapshot.get('REG', {}).get('P/E Ratio (TTM) **')}")
# Get market watch data for this stock
market_data = ticker.market_watch()
print(market_data)
# Get historical price data (1 year)
history = ticker.history(period="1y", interval="1d")
print(history.head())
# Get recent intraday trades (last 2 days)
intraday = ticker.intraday()
print(intraday.head())
Market Data
import pypsx_toolkit
# Get full market watch (all stocks)
market_watch = pypsx_toolkit.market_watch()
print(f"Total stocks in market watch: {len(market_watch)}")
# Get top performers
performers = pypsx_toolkit.top_performers()
print("Top Gainers:")
print(performers["top_gainers"].head())
print("Top Decliners:")
print(performers["top_decliners"].head())
print("Most Active:")
print(performers["top_actives"].head())
# Get sector summary
sectors = pypsx_toolkit.sector_summary()
print(sectors.head())
# Get all available stock symbols
# get_symbols() returns a list of clean symbols (without suffixes XD, NC, XR)
symbols_list = pypsx_toolkit.get_symbols()
print(f"Total symbols: {len(symbols_list)}")
Historical Data
import pypsx_toolkit
# Get 1 year of historical data for a stock
ticker = pypsx_toolkit.PSXTicker("OGDC")
history = ticker.history(period="1y", interval="1d")
# Get full OHLCV data for specific date range
full_data = ticker.get_historical(start_date="2024-01-01", end_date="2024-12-31")
print(full_data.head())
# Download multiple symbols at once
df = pypsx_toolkit.download(["OGDC", "PPL", "KEL"], period="6mo", interval="1d")
print(df.head())
Indices and Sectors
import pypsx_toolkit
# Get all indices overview
indices = pypsx_toolkit.get_indices()
print(indices.head())
# Get constituents of an index (e.g., KSE100)
kse100 = pypsx_toolkit.index_constituents("KSE100")
print(f"KSE100 has {len(kse100)} constituents")
print(kse100.head())
# Get sector information
sectors = pypsx_toolkit.sector_summary()
print(sectors.head())
# Get complete indices breakdown with statistics
indices_breakdown = pypsx_toolkit.get_indices_breakdown()
print(f"Total indices: {indices_breakdown['total_indices']}")
print(f"Total unique symbols: {indices_breakdown['unique_symbols']}")
for idx, count, stats in indices_breakdown['indices'][:5]:
print(f"{idx}: {count} symbols (Current: {stats.get('current', 'N/A')})")
# Get complete sector breakdown with company counts and averages
sector_breakdown = pypsx_toolkit.get_sector_breakdown()
print(f"\nTotal sectors: {sector_breakdown['total_sectors']}")
print(f"Total companies: {sector_breakdown['total_companies']}")
for sector in sector_breakdown['sectors'][:5]:
name = sector['name']
count = sector['company_count']
avg_price = sector['averages'].get('current', 'N/A')
print(f"{name}: {count} companies (Avg Price: {avg_price})")
Main Features
1. Stock Information (PSXTicker)
Create a ticker object for any stock symbol:
ticker = pypsx_toolkit.PSXTicker("OGDC")
Available Properties:
ticker.info- Get company information (price, sector, volume, etc.)ticker.snapshot- Get comprehensive snapshot data from all tabs (OHLCV, bid/ask, circuit breaker, ranges, ratios, etc.)
Available Methods:
ticker.market_watch()- Get current market watch row for this stockticker.sector()- Get sector-level informationticker.history(period="1y", interval="1d")- Get historical dataticker.intraday()- Get intraday trades (last ~2 days)ticker.get_historical(start_date, end_date)- Get full OHLCV data for date rangeticker.dividends()- Get dividend information (external source)ticker.announcements()- Get company announcementsticker.orderbook()- Get trading board data (bid/ask prices)
2. Market Data Functions
# Full market watch
market_watch = pypsx_toolkit.market_watch()
# Top performers
performers = pypsx_toolkit.top_performers() # Returns dict with "top_gainers", "top_decliners", "top_actives"
# Sector summary
sectors = pypsx_toolkit.sector_summary()
# Trading board (order book)
orderbook = pypsx_toolkit.trading_board()
# Get detailed quote data for a symbol (OHLCV, bid/ask, PE ratio, 52-week range, etc.)
quote = pypsx_toolkit.get_quote("OGDC")
print(quote)
# Get quotes for multiple symbols
quotes = pypsx_toolkit.get_quote_batch(["OGDC", "PPL", "KEL"])
for symbol, quote_df in quotes.items():
if quote_df is not None:
print(f"{symbol}: {quote_df}")
# Get company fundamentals (business description, financials, ratios, equity profile)
fundamentals = pypsx_toolkit.get_company_fundamentals("OGDC")
print(fundamentals.head())
# Returns DataFrame with CATEGORY, METRIC, VALUE columns
# Categories include: Profile, Governance, Financials Annual, Financials Quarterly, Ratios, Equity Profile
# Get all symbols
symbols = pypsx_toolkit.get_symbols()
3. Batch Downloads
# Download multiple symbols at once
df = pypsx_toolkit.download(["OGDC", "PPL", "KEL"], period="1y", interval="1d")
print(df.head())
# Get intraday data for multiple symbols
intraday_multi = pypsx_toolkit.get_intraday_multiple(["OGDC", "PPL"])
print(intraday_multi.head())
Charting
The library doesn't ship built-in chart helpers — plot any DataFrame it returns directly with matplotlib:
import matplotlib.pyplot as plt
import pypsx_toolkit
df = pypsx_toolkit.PSXTicker("OGDC").history(period="1y", interval="1d")
fig, ax = plt.subplots(figsize=(11, 4))
ax.plot(df.index, df["CLOSE"], color="tab:blue", linewidth=1)
ax.set_title("OGDC — 1Y Close Price")
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
Analysis and Statistics
PyPSX Toolkit includes comprehensive analysis tools for stock data, available from pypsx_toolkit.analysis.
Statistical Analysis
from pypsx_toolkit.analysis import returns, volatility, correlation, sharpe_ratio
ticker = pypsx_toolkit.PSXTicker("OGDC")
df = ticker.history(period="1y")
# Calculate returns
rets = returns(df)
print(rets.head())
# Calculate volatility
vol = volatility(df)
print(vol.head())
# Calculate Sharpe ratio
sharpe = sharpe_ratio(df)
print(f"Sharpe Ratio: {sharpe:.3f}")
Technical Indicators
from pypsx_toolkit.analysis import moving_average, rsi, macd, bollinger_bands, exponential_moving_average
ticker = pypsx_toolkit.PSXTicker("OGDC")
df = ticker.history(period="1y")
# Moving averages
df['SMA20'] = moving_average(df, window=20)
df['EMA12'] = exponential_moving_average(df, window=12)
# RSI (supports both 'period' and 'window' parameter names)
df['RSI'] = rsi(df, period=14)
# MACD
macd_line, signal, histogram = macd(df)
df['MACD'] = macd_line
df['Signal'] = signal
# Bollinger Bands
ma, upper, lower = bollinger_bands(df, window=20)
df['BB_Upper'] = upper
df['BB_Lower'] = lower
Automated Insights
from pypsx_toolkit.analysis import interpret_stock, quick_analysis
ticker = pypsx_toolkit.PSXTicker("OGDC")
df = ticker.history(period="1y")
# Generate comprehensive insights
insights = interpret_stock(df, "OGDC")
print("Insights:")
for insight in insights['insights']:
print(f" - {insight}")
# Quick analysis
analysis = quick_analysis(df, "OGDC")
print(f"Trading Signal: {analysis['trading_signal']}")
print(f"Sharpe Ratio: {analysis['key_metrics']['sharpe_ratio']:.3f}")
print(f"Max Drawdown: {analysis['key_metrics']['max_drawdown']:.3f}")
print(f"Total Return: {analysis['key_metrics']['total_return']:.2%}")
# Get trading signals directly
from pypsx_toolkit.analysis import generate_trading_signals
signals = generate_trading_signals(df, "OGDC")
print(f"Primary Signal: {signals['primary_signal']}")
print(f"Confidence: {signals['confidence']:.2%}")
Available Analysis Functions:
All analysis functions are available from pypsx_toolkit.analysis:
- Statistics:
returns(),volatility(),correlation(),beta(),correlation_matrix() - Indicators:
moving_average(),rsi(),macd(),bollinger_bands(),stochastic(),williams_r(),atr(),adx(),cci(),obv(),vwap() - Performance:
sharpe_ratio(),sortino_ratio(),calmar_ratio(),drawdown(),max_drawdown(),information_ratio(),treynor_ratio() - Insights:
interpret_stock(),quick_analysis(),portfolio_analysis(),market_sentiment_analysis(),generate_trading_signals()
Import them like: from pypsx_toolkit.analysis import sharpe_ratio, rsi
Market Analysis and Breakdowns
Indices Breakdown
Get a comprehensive breakdown of all PSX indices with constituent counts and statistics:
import pypsx_toolkit
# Get indices breakdown
breakdown = pypsx_toolkit.get_indices_breakdown()
print(f"Total Indices: {breakdown['total_indices']}")
print(f"Total Symbols Analyzed: {breakdown['total_symbols_analyzed']}")
print(f"Unique Symbols: {breakdown['unique_symbols']}")
# Print breakdown
for idx, count, stats in breakdown['indices']:
current = stats.get('current', 'N/A')
change_pct = stats.get('percentage_change', 'N/A')
print(f"{idx}: {count} symbols (Current: {current}, Change: {change_pct}%)")
Output includes:
- Total number of indices
- Constituent count for each index
- Index statistics (Current value, Change, Change %)
- Total symbols analyzed (with duplicates across indices)
- Unique symbols across all indices
Sector Breakdown
Get a comprehensive breakdown of all PSX sectors with company counts and computed averages:
import pypsx_toolkit
# Get sector breakdown
breakdown = pypsx_toolkit.get_sector_breakdown()
print(f"Total Sectors: {breakdown['total_sectors']}")
print(f"Total Companies: {breakdown['total_companies']}")
# Print breakdown
for sector in breakdown['sectors'][:10]: # Top 10 sectors
name = sector['name']
count = sector['company_count']
code = sector['code']
avg_price = sector['averages'].get('current', 0)
avg_change = sector['averages'].get('change_%', 0)
advances = sector['advances']
declines = sector['declines']
print(f"{name} (Code: {code}):")
print(f" Companies: {count}")
print(f" Avg Price: {avg_price:.2f}")
print(f" Avg Change %: {avg_change:.2f}%")
print(f" Advances: {advances}, Declines: {declines}")
print()
Output includes:
- Total number of sectors
- Company count per sector
- Average prices, volumes, changes per sector
- Sector-level statistics (advances, declines, turnover)
- Total companies across all sectors
Advanced Usage
Company Information
import pypsx_toolkit
ticker = pypsx_toolkit.PSXTicker("OGDC")
# Get detailed quote data (includes OHLCV, bid/ask prices, PE ratio, 52-week range, VAR, etc.)
quote = pypsx_toolkit.get_quote("OGDC")
print(quote)
# Output includes: OPEN, HIGH, LOW, VOLUME, BID_PRICE, ASK_PRICE, PE_RATIO, VAR, HAIRCUT, etc.
# Get quotes for multiple symbols
quotes = pypsx_toolkit.get_quote_batch(["OGDC", "PPL", "KEL"])
for symbol, quote_df in quotes.items():
if quote_df is not None:
print(f"{symbol} Quote:")
print(quote_df)
# Get company fundamentals (business description, financials, ratios, equity profile)
fundamentals = pypsx_toolkit.get_company_fundamentals("OGDC")
print(fundamentals.head())
# Get comprehensive snapshot data from all tabs (most holistic approach)
snapshot = pypsx_toolkit.get_snapshot("BOP")
print(snapshot['REG']) # REG tab contains: OHLCV, circuit breaker, ranges, bid/ask, ratios, etc.
# Or use ticker.snapshot property:
ticker = pypsx_toolkit.PSXTicker("BOP")
snap = ticker.snapshot
print(f"Open: {snap['REG']['Open']}")
print(f"52-Week Range: {snap['REG']['52-WEEK RANGE ^']}")
# Get announcements
announcements = ticker.announcements()
print(announcements.head())
# Get dividends
dividends = ticker.dividends()
print(dividends)
# Get order book
orderbook = ticker.orderbook()
print(orderbook)
Custom Date Ranges
ticker = pypsx_toolkit.PSXTicker("OGDC")
# Get historical data for specific date range
historical = ticker.get_historical(
start_date="2024-01-01",
end_date="2024-12-31"
)
print(historical.head())
Examples
Example 1: Find Top Volume Stocks
import pypsx_toolkit
# Get market watch
mw = pypsx_toolkit.market_watch()
# Sort by volume and get top 5
top_volume = mw.nlargest(5, "Volume")[['Current', 'Change', 'Volume']]
print(top_volume)
Example 2: Compare Stock Performance
import pypsx_toolkit
import matplotlib.pyplot as plt
symbols = ["OGDC", "PPL", "KEL"]
fig, ax = plt.subplots(figsize=(11, 4))
for symbol in symbols:
df = pypsx_toolkit.PSXTicker(symbol).history(period="6mo", interval="1d")
ax.plot(df.index, df["CLOSE"] / df["CLOSE"].iloc[0], label=symbol)
ax.set_title("Normalized Close Price — 6 Months")
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
Example 3: Technical Analysis
import pypsx_toolkit
from pypsx_toolkit.analysis import rsi, macd, bollinger_bands
ticker = pypsx_toolkit.PSXTicker("OGDC")
df = ticker.history(period="1y")
# Add technical indicators
df['RSI'] = rsi(df, period=14)
macd_line, signal, _ = macd(df)
df['MACD'] = macd_line
df['Signal'] = signal
ma, upper, lower = bollinger_bands(df)
df['BB_Upper'] = upper
df['BB_Lower'] = lower
# Simple trading signal (SMA crossover)
df['SMA20'] = df['CLOSE'].rolling(20).mean()
df['SMA50'] = df['CLOSE'].rolling(50).mean()
df['Signal'] = (df['SMA20'] > df['SMA50']).astype(int)
print(df[['CLOSE', 'RSI', 'MACD', 'Signal']].tail())
Example 4: Portfolio Analysis
import pypsx_toolkit
from pypsx_toolkit.analysis import portfolio_analysis
# Create a portfolio
portfolio = {
"OGDC": pypsx_toolkit.PSXTicker("OGDC").history(period="1y"),
"PPL": pypsx_toolkit.PSXTicker("PPL").history(period="1y"),
"KEL": pypsx_toolkit.PSXTicker("KEL").history(period="1y"),
}
# Analyze portfolio
analysis = portfolio_analysis(portfolio)
print(f"Avg Correlation: {analysis['portfolio_metrics']['avg_correlation']:.3f}")
print(f"Avg Volatility: {analysis['portfolio_metrics']['avg_volatility']:.3f}")
print(f"Best Performer: {analysis['portfolio_metrics']['best_performer']}")
print(f"Market Sentiment: {analysis['market_sentiment']} ({analysis['sentiment_strength']})")
for insight in analysis["portfolio_insights"]:
print(f" - {insight}")
API Reference
PSXTicker Class
ticker = pypsx_toolkit.PSXTicker(symbol: str)
# Properties
ticker.info # Dict with company info
ticker.snapshot # Dict with comprehensive snapshot data from all tabs
ticker.fast_info # Quick metrics dict
# Methods
ticker.history(period="1y", interval="1d") # Historical data
ticker.intraday() # Intraday trades
ticker.get_historical(start_date, end_date) # Full OHLCV data
ticker.market_watch() # Market watch row
ticker.sector() # Sector information
ticker.orderbook() # Trading board data
ticker.dividends() # DataFrame with dividends
ticker.announcements() # DataFrame with announcements
Market Functions
pypsx_toolkit.market_watch() # Full market watch DataFrame
pypsx_toolkit.top_performers() # Dict: {top_gainers, top_decliners, top_actives}
pypsx_toolkit.sector_summary() # Sector summary DataFrame
pypsx_toolkit.get_indices() # Indices overview DataFrame
pypsx_toolkit.get_indices_breakdown() # Complete indices breakdown with counts and stats
pypsx_toolkit.get_sector_breakdown() # Complete sector breakdown with company counts and averages
pypsx_toolkit.get_symbols() # List of all stock symbols
pypsx_toolkit.trading_board() # Trading board DataFrame
# Quote functions - Get detailed quote data (OHLCV, bid/ask, PE ratio, 52-week range, etc.)
pypsx_toolkit.get_quote(symbol) # Get detailed quote for a single symbol
pypsx_toolkit.get_quote_batch(symbols) # Get quotes for multiple symbols (returns dict)
# Company fundamentals - Get comprehensive company data (business description, financials, ratios, etc.)
pypsx_toolkit.get_company_fundamentals(symbol) # Get company fundamentals (returns DataFrame)
# Snapshot - Get comprehensive snapshot data from all tabs (most holistic approach)
pypsx_toolkit.get_snapshot(symbol) # Get snapshot data from all tabs (returns dict with tab names as keys)
# Or use ticker.snapshot property for easier access
Download Functions
pypsx_toolkit.download(symbols, period="1y", interval="1d") # Batch download
pypsx_toolkit.get_intraday_multiple(symbols) # Multiple intraday
pypsx_toolkit.get_historical(symbol, start_date, end_date) # Historical OHLCV
Backward Compatibility
The library maintains backward compatibility:
pypsx_toolkit.Tickeris an alias forpypsx_toolkit.PSXTickerpypsx_toolkit.PSXSymbolis also available (legacy)
Notes
- Dividends: PSX doesn't provide a dividends endpoint. The
dividendsproperty uses an external data source. - Data Availability: Some data may not be available when the market is closed.
- Symbol Names: Use official PSX symbols (e.g., "OGDC", "PPL", "KEL").
License
Proprietary — All rights reserved. Unauthorized use, copying, or distribution is prohibited.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 10.9 MB
- Tags: CPython 3.10, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d9e8cc817131dfe763511723ef82f102d8c1e8325963f5dbeaf39fa30a50b1b9
|
|
| MD5 |
5e796ce5c7b139bcf1d84c29885cb943
|
|
| BLAKE2b-256 |
cdef147697a315c407b5ae14d82f93ee712d6defae0061f271d717bd0396442a
|
Provenance
The following attestation bundles were made for pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:
Publisher:
workflow.yml on pypsx/libraries
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -
Subject digest:
d9e8cc817131dfe763511723ef82f102d8c1e8325963f5dbeaf39fa30a50b1b9 - Sigstore transparency entry: 2280311884
- Sigstore integration time:
-
Permalink:
pypsx/libraries@1e13f1d033b23684b93edb05595d131b4b2d7a8b -
Branch / Tag:
refs/heads/main - Owner: https://github.com/pypsx
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@1e13f1d033b23684b93edb05595d131b4b2d7a8b -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 10.9 MB
- Tags: CPython 3.10, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c5f8a05d971a0d39a9319f972cbb5acca2864548e981d6024c397ae191dcb2fb
|
|
| MD5 |
b96d46bbcfe6f9b0f28ca9cfa57ada89
|
|
| BLAKE2b-256 |
cff352fbef6ff13c49efe9975c8ddaee1d641de957ce5c23ba1f4f2cc859f0f7
|
Provenance
The following attestation bundles were made for pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:
Publisher:
workflow.yml on pypsx/libraries
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pypsx_toolkit-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl -
Subject digest:
c5f8a05d971a0d39a9319f972cbb5acca2864548e981d6024c397ae191dcb2fb - Sigstore transparency entry: 2280311842
- Sigstore integration time:
-
Permalink:
pypsx/libraries@1e13f1d033b23684b93edb05595d131b4b2d7a8b -
Branch / Tag:
refs/heads/main - Owner: https://github.com/pypsx
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@1e13f1d033b23684b93edb05595d131b4b2d7a8b -
Trigger Event:
workflow_dispatch
-
Statement type: