Skip to main content

A Python implementation of Smart Money Concepts (SMC) for technical analysis using yfinance data.

Project description

Smart Money Concepts (SMC) Python Package

A Python package for performing Smart Money Concepts (SMC) technical analysis using historical stock data from yfinance. This package provides a comprehensive framework for detecting market structures, order blocks, fair value gaps, and other SMC components, with visualization capabilities using matplotlib.


📌 Features

  • Market Structure Analysis: Detects Break of Structure (BOS) and Change of Character (CHoCH) for swing and internal structures.
  • Order Blocks: Identifies bullish and bearish order blocks for potential institutional trading zones.
  • Fair Value Gaps (FVG): Detects price imbalances with mitigation logic.
  • Equal Highs and Lows: Marks potential reversal points with Equal Highs (EQH) and Equal Lows (EQL).
  • Premium and Discount Zones: Calculates dynamic zones based on trailing extremes.
  • Visualization: Plots candlestick charts with SMC indicators (BOS, CHoCH, order blocks, FVGs, etc.) using matplotlib.
  • Real-time Data: Fetches OHLCV data from yfinance for stocks and indices.
  • Customizable Settings: Configure analysis parameters like swing length, FVG thresholds, and visualization styles (colored or monochrome).

⚙️ Installation

From PyPI (when published)

pip install smart-money-concept

📦 Requirements

  • Python 3.8+
  • yfinance>=0.2.40
  • pandas>=2.0.0
  • numpy>=1.24.0
  • matplotlib>=3.7.0

🚀 Usage

The package provides a SmartMoneyConcepts class for analyzing market data and a command-line interface (CLI) for batch processing multiple stocks.

Python Script Example

import asyncio
from typing import List, Dict
from smart_money_concepts import SmartMoneyConcepts

async def main(stock_codes: List[str], period: str = "max", interval: str = "1d", batch_size: int = 10, delay: float = 2.0, visualize: bool = True):
    if not stock_codes:
        stock_codes = ["RELIANCE.NS"]  # Default to NSE-listed Reliance

    for i, stock_code in enumerate(stock_codes):
        print(f"\n==============================")
        print(f"🔍 Analyzing stock: {stock_code}")
        print(f"==============================")

        smc = SmartMoneyConcepts(stock_code=stock_code, period=period, interval=interval)
        
        # Retry logic for fetching data
        max_retries = 3
        for attempt in range(max_retries):
            try:
                success = await smc.fetch_ohlcv()
                if success:
                    smc.prepare_data()
                    smc.run_smc_analysis()
                    if visualize:
                        smc.visualize_smc(bars_to_show=500)
                    else:
                        smc.print_analysis_summary()  # Print summary even if visualization is skipped
                    break
                else:
                    print(f"❌ Analysis failed for {stock_code}!")
                    break
            except Exception as e:
                if "429" in str(e):  # Check for rate limit error
                    print(f"Rate limit hit for {stock_code}. Retrying ({attempt + 1}/{max_retries}) after delay...")
                    await asyncio.sleep(5)  # Wait longer for rate limit errors
                else:
                    print(f"Error for {stock_code}: {e}")
                    break
            if attempt == max_retries - 1:
                print(f"❌ Failed to fetch data for {stock_code} after {max_retries} attempts.")

        # Add delay after every batch_size stocks
        if (i + 1) % batch_size == 0 and i + 1 < len(stock_codes):
            print(f"Pausing for {delay} seconds after processing {batch_size} stocks...")
            await asyncio.sleep(delay)

if __name__ == "__main__":
    # Example stock list (use .NS for NSE-listed stocks, .BO for BSE, or others as needed)

    # Stocks
    stock_codes = ["RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS"]
    
    # Index
    # stock_codes = ["^NSEI"]
    
    asyncio.run(main(stock_codes, period="1y", interval="1d", batch_size=10, delay=2.0, visualize=True))

CLI Example

python -m smart_money_concepts.cli --stocks ^NSEI RELIANCE.NS --period 1y --interval 1d

CLI Options:

  • --stocks: List of stock codes (e.g., ^NSEI, RELIANCE.NS). Default: RELIANCE.NS.
  • --period: Data period (e.g., 1d, 1mo, 1y, max). Default: 1y.
  • --interval: Data interval (e.g., 1m, 1h, 1d). Default: 1d.
  • --batch-size: Number of stocks to process before pausing. Default: 10.
  • --delay: Delay (seconds) between batches. Default: 2.0.
  • --no-visualize: Disable visualization and print analysis summary only.

📊 Example Output

The package generates a detailed analysis summary and optional visualizations, including:

  • Candlestick charts with swing and internal structure breaks (BOS/CHoCH).
  • Order blocks, fair value gaps, and equal highs/lows.
  • Premium, equilibrium, and discount zones.

📂 Project Structure

smart_money_concepts/
├── smart_money_concepts/
│   ├── __init__.py
│   ├── smc.py
│   ├── cli.py
├── README.md
├── pyproject.toml
├── requirements.txt

🙌 Credits

This project was inspired by and builds upon the following resources:

  • Code Tech: This code is Take from YouTube tutorial by Code Tech, which provides a detailed walkthrough of building an SMC indicator in Python
  • LuxAlgo: The conceptual framework and feature set are inspired by LuxAlgo's Smart Money Concepts indicator.

🤝 Contributing

Contributions are welcome! Please submit a pull request or open an issue on the GitHub repository for bug reports, feature requests, or improvements.


⚠️ Notes

  • Rate Limits: The package uses yfinance for data fetching, which may be subject to rate limits. Built-in retry logic handles HTTP 429 errors.
  • Internet Connection: Ensure a stable internet connection for fetching market data.
  • Disclaimer: This package is for educational purposes and should not be used as financial advice. Trading involves risks, and past performance does not guarantee future results.

📬 Contact

For questions or support, please open an issue on the GitHub repository.


Additional Notes

  • Repository URL: Replace https://github.com/yourusername/smart-money-concepts with the actual GitHub repository URL once created.
  • PyPI Name: Before publishing, verify that the package name smart-money-concepts is available on PyPI. If unavailable, update pyproject.toml and the README with a unique name (e.g., smc-analysis).
  • Dependencies: Ensure requirements.txt and pyproject.toml include:
    yfinance>=0.2.40
    pandas>=2.0.0
    numpy>=1.24.0
    matplotlib>=3.7.0
    
  • CLI: The CLI script (cli.py) enables command-line usage.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smart_money_concept-0.1.1.tar.gz (16.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smart_money_concept-0.1.1-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file smart_money_concept-0.1.1.tar.gz.

File metadata

  • Download URL: smart_money_concept-0.1.1.tar.gz
  • Upload date:
  • Size: 16.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for smart_money_concept-0.1.1.tar.gz
Algorithm Hash digest
SHA256 4549e1fa5cfea7c1a23a43cb23f080adba8a2819504d2d0c574816147438440b
MD5 4d1752fbe78c68965fc6dbd8e907e755
BLAKE2b-256 3784cbf82911fe6b517350054e670b79dca6cce8f073b710f7d8e9a4e740b4d6

See more details on using hashes here.

File details

Details for the file smart_money_concept-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for smart_money_concept-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 132e27846ba1eb476047ea92d3c8240cd440080ac84e53fb7787e38d42ce861f
MD5 9b72b3feb448038b52077c51787bc4ed
BLAKE2b-256 c048bbd266c3a4b566aabcee40e30ffb16f616cad50264cc67b0d7c3132dde6c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page