CoolFace
Apppublic

ykfin/Halal-Screener

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
App README

Halal Stock Screener API

A comprehensive Sharia-compliant stock screening service that evaluates stocks based on AAOIFI (Accounting and Auditing Organization for Islamic Financial Institutions) standards and AI-powered ethical analysis.

Features

Financial Screening (AAOIFI Standards)

  • Debt to Market Cap Ratio: Total debt / Market cap < 30%
  • Interest/Non-compliant Income Ratio: Interest income / Total revenue < 5%
  • Illiquid Assets Ratio: (Receivables + Cash) / Total assets < 50%

Ethical Screening (AI-Powered)

  • Prohibited business activities detection (alcohol, gambling, pork, conventional finance, weapons, adult entertainment, tobacco)
  • Political involvement verification (critical check for direct, indirect, matching programs, product/service support)
  • Corporate governance assessment
  • Controversy and ESG analysis
  • Full research traceability with step-by-step documentation

Quick Start

Prerequisites

  • Python 3.11+
  • uv package manager
  • OpenAI API key (for ethical screening)

Installation

  1. 1.Clone the repository:
bash
git clone https://github.com/yourusername/halal-screener.git
cd halal-screener
  1. 1.Install dependencies using uv:
bash
uv sync
  1. 1.Create environment file:
bash
cp .env.example .env
  1. 1.Edit .env and add your API keys:
env
OPENAI_API_KEY=your_openai_api_key_here

Running the API

bash
uv run uvicorn app.main:app --reload

The API will be available at http://localhost:8000

API Documentation

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI JSON: http://localhost:8000/openapi.json

API Endpoints

Screen a Single Stock

http
POST /api/screen/stock
Content-Type: application/json

{
  "ticker": "AAPL",
  "force_refresh": false
}

Screen Multiple Stocks

http
POST /api/screen/batch
Content-Type: application/json

{
  "tickers": ["AAPL", "MSFT", "GOOGL"],
  "force_refresh": false
}

Get Cached Result

http
GET /api/screen/{ticker_symbol}?screen_if_missing=true

Response Format

json
{
  "ticker": "AAPL",
  "company_name": "Apple Inc.",
  "screening_date": "2026-01-06T...",
  "overall_compliance": "COMPLIANT",
  "rules_based_screening": {
    "passed": true,
    "tests": [
      {
        "rule": "Debt to Market Cap Ratio",
        "standard": "< 30% (AAOIFI)",
        "actual": "3.33%",
        "passed": true,
        "data_source": "Yahoo Finance",
        "retrieved_at": "2026-01-06T..."
      }
    ],
    "data_availability": "complete",
    "notes": []
  },
  "ethical_screening": {
    "passed": true,
    "analysis": "Detailed AI analysis...",
    "concerns": [],
    "sources": ["https://..."],
    "research_trace": [
      {
        "step": 1,
        "action": "Analyzed business model",
        "findings": "...",
        "tool_used": "analyze_business_model"
      }
    ],
    "political_involvement_check": {
      "donations_found": false,
      "details": "No evidence of political involvement"
    }
  },
  "final_decision": {
    "recommendation": "COMPLIANT",
    "confidence": "HIGH",
    "summary": "Brief explanation",
    "detailed_reasoning": "Full explanation with all factors"
  },
  "disclaimer": "This is an automated screening tool..."
}

Configuration

Environment VariableDescriptionDefault
OPENAI_API_KEYOpenAI API key for ethical screeningRequired
OPENAI_MODELOpenAI model to usegpt-4o
REDIS_URLRedis connection URL (optional)None
API_HOSTAPI host address0.0.0.0
API_PORTAPI port8000
RATE_LIMIT_REQUESTSMax requests per window100
RATE_LIMIT_WINDOW_SECONDSRate limit window3600
CACHE_TTL_SECONDSCache TTL86400 (24h)
LOG_LEVELLogging levelINFO

Running Tests

bash
uv run pytest tests/ -v

With coverage:

bash
uv run pytest tests/ -v --cov=app --cov-report=html

Project Structure

halal-screener/
├── app/
│   ├── __init__.py
│   ├── main.py              # FastAPI application entry point
│   ├── config.py            # Configuration settings
│   ├── models.py            # Pydantic models
│   ├── routers/
│   │   ├── __init__.py
│   │   └── screening.py     # Screening API endpoints
│   ├── services/
│   │   ├── __init__.py
│   │   ├── cache_service.py       # Caching service
│   │   ├── financial_screener.py  # AAOIFI screening
│   │   ├── ethical_screener.py    # AI ethical screening
│   │   └── screening_service.py   # Main orchestration
│   └── middleware/
│       ├── __init__.py
│       └── rate_limit.py    # Rate limiting
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   ├── test_api.py
│   ├── test_cache_service.py
│   ├── test_ethical_screener.py
│   ├── test_financial_screener.py
│   └── test_models.py
├── pyproject.toml
├── .env.example
└── README.md

AAOIFI Standards Applied

This API implements the following AAOIFI-based screening criteria:

  1. 1.Debt Screening: Companies must have total debt less than 30% of market capitalization
  2. 2.Interest Income Screening: Interest and other non-compliant income must be less than 5% of total revenue
  3. 3.Illiquid Assets Screening: Liquid assets (cash + receivables) must be less than 50% of total assets

Political Involvement Policy

The ethical screening specifically checks for any form of political involvement or support, including:

  • Direct monetary donations
  • Indirect donations through intermediaries
  • Employee matching donation programs
  • Product or service donations
  • Partnerships with politically involved organizations

Note: Conducting regular business operations is allowed. Only direct donations or material support for controversial political causes are flagged.

Important Disclaimers

⚠️ This is an automated screening tool and NOT a religious ruling (fatwa).

  • Results are based on publicly available financial data and AI analysis
  • Users should consult qualified Islamic scholars for final investment decisions
  • Data accuracy depends on third-party sources and may contain errors
  • The screening does not constitute financial or religious advice

Data Sources

  • Financial Data: Yahoo Finance API
  • Ethical Analysis: OpenAI GPT-4
  • Company Information: Public filings, news sources, company websites

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting pull requests.

Support

For issues and feature requests, please use the GitHub issue tracker