What We're Building

By the end of this tutorial, you'll have a Python script that can:

  1. Screen any stock for Shariah compliance across 5 methodologies
  2. Bulk-screen an entire index (S&P 500, NASDAQ 100, etc.)
  3. Scan a portfolio and calculate aggregate compliance
  4. Pull dividend purification data
  5. Export everything to CSV

Total code: ~80 lines. Total time: ~15 minutes.

Prerequisites

Step 1: Get an API Key

First, generate a free API key. No credit card required — the free tier includes 50 tokens/month:

import requests

BASE_URL = "https://api.halalterminal.com"

# Generate a free API key
resp = requests.post(f"{BASE_URL}/api/keys/generate", json={
    "email": "dev@example.com"
})
data = resp.json()
API_KEY = data["api_key"]
print(f"Your API key: {API_KEY}")
print(f"Plan: {data['plan']}, Tokens: {data['requests_limit']}")

Save your API key — you'll use it in every subsequent request via the X-API-Key header.

Step 2: Screen a Single Stock

The /api/screen endpoint is the core of the API. It returns compliance status for all five Shariah screening methodologies in a single call:

headers = {"X-API-Key": API_KEY}

def screen_stock(symbol):
    """Screen a stock for Shariah compliance."""
    resp = requests.get(
        f"{BASE_URL}/api/screen",
        params={"symbol": symbol},
        headers=headers,
    )
    resp.raise_for_status()
    return resp.json()

# Screen Apple
result = screen_stock("AAPL")
print(f"{result['symbol']}: {result['overall_status']}")
for method, status in result["methodologies"].items():
    print(f"  {method}: {status}")
print(f"  Purification rate: {result['purification_rate']}%")

Output:

AAPL: COMPLIANT
  AAOIFI: COMPLIANT
  DJIM: COMPLIANT
  FTSE: COMPLIANT
  MSCI: COMPLIANT
  SP: COMPLIANT
  Purification rate: 0.42%
Token Costs

Each API endpoint costs a specific number of tokens. Single stock screening costs 5 tokens, so with the free plan's 50 tokens, you can screen 10 stocks per month. Upgrade to Starter ($19/mo) for 2,500 tokens or Pro ($49/mo) for 15,000 tokens. See the full cost table at /api/keys/token-costs.

Step 3: Bulk Screen an Entire Index

The /api/screen-bulk endpoint lets you screen an entire index asynchronously. Submit a list of symbols and get results for all of them:

def bulk_screen(symbols):
    """Screen multiple stocks at once."""
    resp = requests.post(
        f"{BASE_URL}/api/screen-bulk",
        json={"symbols": symbols},
        headers=headers,
    )
    resp.raise_for_status()
    return resp.json()

# Screen the FAANG stocks
faang = ["AAPL", "AMZN", "GOOGL", "META", "NFLX"]
results = bulk_screen(faang)

print(f"\nBulk screening results ({len(results['results'])} stocks):")
for stock in results["results"]:
    status = stock["overall_status"]
    emoji = "PASS" if status == "COMPLIANT" else "FAIL"
    print(f"  [{emoji}] {stock['symbol']}: {status}")

Step 4: Portfolio Compliance Scanner

The /api/portfolio/scan endpoint takes your actual holdings (with share counts) and returns per-stock compliance plus aggregate portfolio metrics:

def scan_portfolio(holdings):
    """Scan a portfolio for Shariah compliance."""
    resp = requests.post(
        f"{BASE_URL}/api/portfolio/scan",
        json={"holdings": holdings},
        headers=headers,
    )
    resp.raise_for_status()
    return resp.json()

# Define your portfolio
my_portfolio = [
    {"symbol": "AAPL", "shares": 50},
    {"symbol": "MSFT", "shares": 30},
    {"symbol": "GOOGL", "shares": 20},
    {"symbol": "JPM", "shares": 15},   # Bank - likely non-compliant
    {"symbol": "NVDA", "shares": 25},
]

portfolio = scan_portfolio(my_portfolio)
print(f"\nPortfolio Compliance Report")
print(f"{'='*40}")
print(f"Compliant holdings: {portfolio['compliant_count']}/{portfolio['total_count']}")
print(f"Compliance rate: {portfolio['compliance_rate']}%")
print(f"Portfolio purification rate: {portfolio['purification_rate']}%")
print(f"\nPer-stock breakdown:")
for stock in portfolio["holdings"]:
    status = stock["overall_status"]
    print(f"  {stock['symbol']:6s} {status}")

Step 5: Add Dividend Purification Data

For compliant holdings that pay dividends, fetch the purification details:

def get_purification(symbol):
    """Get dividend purification data for a stock."""
    resp = requests.get(
        f"{BASE_URL}/api/dividends/{symbol}/purification",
        headers=headers,
    )
    resp.raise_for_status()
    return resp.json()

# Get purification data for dividend-paying holdings
for holding in my_portfolio:
    symbol = holding["symbol"]
    try:
        purification = get_purification(symbol)
        rate = purification["purification_rate"]
        print(f"{symbol}: purification rate = {rate}%")
    except requests.HTTPError:
        print(f"{symbol}: no purification data available")

Step 6: Export Results to CSV

Finally, let's export everything into a clean CSV report:

import csv

def export_to_csv(portfolio_data, filename="shariah_report.csv"):
    """Export portfolio screening results to CSV."""
    with open(filename, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([
            "Symbol", "Status", "AAOIFI", "DJIM", "FTSE",
            "MSCI", "SP", "Purification Rate"
        ])
        for stock in portfolio_data["holdings"]:
            methods = stock.get("methodologies", {})
            writer.writerow([
                stock["symbol"],
                stock["overall_status"],
                methods.get("AAOIFI", "N/A"),
                methods.get("DJIM", "N/A"),
                methods.get("FTSE", "N/A"),
                methods.get("MSCI", "N/A"),
                methods.get("SP", "N/A"),
                stock.get("purification_rate", "N/A"),
            ])
    print(f"Report saved to {filename}")

export_to_csv(portfolio)

Endpoint Reference

Endpoint Method Tokens Description
/api/screen GET 5 Screen a single stock
/api/screen-bulk POST 50 Bulk screen multiple stocks
/api/portfolio/scan POST 25 Scan portfolio compliance
/api/dividends/{symbol}/purification GET 2 Get purification data
/api/etf/{symbol}/screening GET 10 Screen ETF holdings
/api/quote/{symbol} GET 2 Get stock quote
/api/zakat/calculate POST 5 Calculate zakat on portfolio
/api/database/search GET 1 Search stock database

Build with Halal Terminal

Halal Terminal API

58+ endpoints, 5 screening methodologies, ETF analysis, zakat calculators, and MCP tools. Free tier available.

Next Steps

You now have a working Shariah stock screener in Python. Here are some ideas to extend it:

For the full API reference with all 58+ endpoints, visit the Swagger documentation.

Important Disclaimer

Not financial advice. The information provided on this page is for educational and informational purposes only and should not be construed as financial advice, investment advice, trading advice, or any other type of advice. You should not make any financial decisions based solely on the information presented here.

Not a fatwa. Shariah compliance screening results are generated using automated data analysis based on publicly available financial data. These results do not constitute a religious ruling (fatwa) and should not be treated as one. Always consult a qualified Islamic scholar or Shariah advisor for guidance specific to your situation.

Do your own research. Past performance and current compliance status do not guarantee future results or continued compliance. Screening data may contain errors or become outdated. Always verify information independently and consult with a qualified financial advisor before making any investment decisions.