Skip to main content

A Python package for Smart Money Concepts (SMC) analysis and stock screening

Project description

SMC Screener ๐Ÿ“ˆ

A Python package for Smart Money Concepts (SMC) analysis and stock screening, designed to identify key market levels such as swing highs/lows, order blocks, fair value gaps (FVGs), and premium/discount zones.

Features โœจ

  • SMC Analysis: Identifies swing highs/lows, order blocks, FVGs, and market structure breaks using yfinance data. ๐Ÿ“Š
  • Stock Screener: Screens stocks near key SMC levels based on a proximity percentage. ๐Ÿ”
  • Visualization: Generates candlestick charts with SMC levels using matplotlib. ๐Ÿ“‰
  • Output Options: Saves results to CSV files and/or Google Sheets. ๐Ÿ“„๐Ÿ“‘
  • Interactive CLI: Choose tasks (analysis, screener, or both) and stock lists (e.g., Nifty 50, F&O). ๐Ÿ–ฅ๏ธ

Installation ๐Ÿš€

  1. Install via pip:

    pip install smc-screener
    
  2. Install Dependencies: The package requires the following Python libraries:

    • yfinance>=0.2.44
    • pandas>=2.2.2
    • numpy>=1.26.4
    • matplotlib>=3.9.2
    • gspread>=6.1.2 (optional, for Google Sheets)
    • oauth2client>=4.1.3 (optional, for Google Sheets)
    • tqdm>=4.66.5

    Install them manually if needed:

    pip install yfinance pandas numpy matplotlib gspread oauth2client tqdm
    
  3. Google Sheets Setup (optional, for output_format="google_sheets" or "both") ๐Ÿ“‘:

    • Create a Google Cloud project and enable the Google Sheets API and Google Drive API. ๐Ÿ”ง
    • Create a service account and download the JSON credentials file. ๐Ÿ”‘
    • Save the JSON file as Credentials/credentials.json in your project directory.
    • Share your Google Sheet with the service accountโ€™s email (found in the JSON file) with edit access.
    • Update the spreadsheet_id in main_pipeline.py with your Google Sheet ID (from the URL: https://docs.google.com/spreadsheets/d/<SPREADSHEET_ID>/edit).

Usage ๐Ÿ› ๏ธ

Command-Line Interface

Run the package directly from the command line:

smc-screener

This launches an interactive CLI where you can:

  • Select a task: SMC Analysis, SMC Screener, or both. ๐Ÿ”„
  • Choose a stock list: Nifty Top 10, Nifty 50, F&O, or Nifty 500. ๐Ÿ“‹

Example interaction:

Select the task to run:
1. SMC Analysis
2. SMC Screener
3. Both (Analysis + Screener)
Enter your choice (1, 2, or 3): 3

Select the stock list to process:
1. Nifty Top 10
2. Nifty 50
3. F&O
4. Nifty 500
Enter your choice (1, 2, 3, or 4): 1

Selected stock list: Nifty Top 10 (10 stocks)
Step 1: Running SMC Analysis... ๐Ÿ“Š
Step 2: Running SMC Screener... ๐Ÿ”
Task 'both' completed for Nifty Top 10! ๐ŸŽ‰
nifty_500       = ["360ONE.NS", "ABB.NS", "APLAPOLLO.NS"]                 # add more stocks here

Programmatic Usage

Run the pipeline programmatically:

import asyncio
import os
from smc_trading.smc_analysis import main as main_analysis
from smc_trading.smc_screener import main as main_screener

async def run_full_pipeline():
    # Create analysis directory
    os.makedirs("analysis", exist_ok=True)

    # Define stock code lists for each option
    indices         = ["^NSEI", "^NSEBANK", "^CNXIT", "^CNXAUTO", "^CNXFMCG", "^CNXMETAL", "^CNXPHARMA", "^CNXREALTY", "^CNXENERGY", "^CNXMEDIA"]

    nifty_top_10    = ["HDFCBANK.NS", "ICICIBANK.NS", "RELIANCE.NS", "INFY.NS", "BHARTIARTL.NS", "LT.NS", "ITC.NS", "SBIN.NS", "AXISBANK.NS", "TCS.NS"]

    nifty_50        = ["360ONE.NS", "ABB.NS", "APLAPOLLO.NS"]                 # add more stocks here

    fn_o_stocks     = ["360ONE.NS", "ABB.NS", "APLAPOLLO.NS"]                 # add more stocks here

    nifty_500       = ["360ONE.NS", "ABB.NS", "APLAPOLLO.NS"]                 # add more stocks here
    
    csv_column_mapping = {
        'OPEN_PRICE': 'open',
        'HIGH_PRICE': 'high',
        'LOW_PRICE': 'low',
        'CLOSE_PRICE': 'close',
        'DATE1': 'Date'
    }

    spreadsheet_id  = "YOUR_SPREADSHEET_ID" # Replace with your Sheet ID

    csv_directory   = "Stocks"
    fetch_csv_data  = False

    period          = "max"                 #   "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y","5y", "10y", "ytd", "max"
    interval        = "1d"                  #   "1m", "2m", "5m", "15m", "30m", "60m"/"1h", "90m",      "1d", "5d", "1wk", "1mo", "3mo"
    auto_adjust     = False                 # Raw prices โ€” unadjusted for splits/dividends.
    visualize       = False                 # If True, plots SMC charts; False skips to save time.
    print_details   = False                 # If True, logs detailed analysis/screener info; False for minimal output.
    output_format   = "csv"                 # Save to csv, google_sheets, or both for analysis and screener results.
    clear           = True                  # Clears existing CSVs and Google Sheets before saving new data.

    use_colab       = False                 # if goole colab use True otherwise False

    distance_percentage = 2.0                       # % threshold for screener to find stocks near SMC levels.
    output_csv          = "screener_results.csv"    # File path for screener results CSV.

    while True:
        print("\n๐Ÿ“Œ Select the task to run:")
        print("   1๏ธโƒฃ  SMC Analysis")
        print("   2๏ธโƒฃ  SMC Screener")
        print("   3๏ธโƒฃ  Both (Analysis + Screener)")
        print("   0๏ธโƒฃ  Exit")
        try:
            task_choice = input("\n๐Ÿ‘‰ Enter your choice (1, 2, 3, or 0 to exit): ").strip().lower()
            if task_choice in ["1", "2", "3"]:
                break
            elif task_choice == "0" or task_choice == "exit":
                print("\n๐Ÿ›‘ Exiting program.")
                return
            print("โŒ Invalid choice. Please enter 1, 2, 3, or 0.")
        except KeyboardInterrupt:
            print("\n๐Ÿ›‘ Exiting program.")
            return

    # Map task
    task = {"1": "analysis", "2": "screener", "3": "both"}[task_choice]

    stock_codes, stock_list_name = None, None

    # Only ask stock list if Analysis or Both is selected
    if task in ["analysis", "both"]:
        while True:
            print("\n๐Ÿ“Š Select the stock list to process:")
            print("   1๏ธโƒฃ  Nifty Top 10")
            print("   2๏ธโƒฃ  Nifty 50")
            print("   3๏ธโƒฃ  F&O")
            print("   4๏ธโƒฃ  Nifty 500")
            print("   5๏ธโƒฃ  Indices")
            print("   0๏ธโƒฃ  Back to task selection")
            try:
                stock_choice = input("\n๐Ÿ‘‰ Enter your choice (1, 2, 3, 4, 5, or 0 to go back): ").strip().lower()
                if stock_choice in ["1", "2", "3", "4", "5"]:
                    break
                elif stock_choice == "0" or stock_choice == "exit":
                    print("\n๐Ÿ”™ Returning to task selection.")
                    return await run_full_pipeline()  # Go back to task selection
                print("โŒ Invalid choice. Please enter 1, 2, 3, 4, 5, or 0.")
            except KeyboardInterrupt:
                print("\n๐Ÿ›‘ Exiting program.")
                return

        # Map stock list
        stock_codes = {
            "1": nifty_top_10,
            "2": nifty_50,
            "3": fn_o_stocks,
            "4": nifty_500,
            "5": indices
        }[stock_choice]
        stock_list_name = {
            "1": "Nifty Top 10",
            "2": "Nifty 50",
            "3": "F&O",
            "4": "Nifty 500",
            "5": "Indices"
        }[stock_choice]

        print(f"\nโœ… Selected Stocks or Indices list: *{stock_list_name}* ({len(stock_codes)} No. of Stocks or Indices)")

    # Execute selected task(s)
    if task in ["analysis", "both"]:
        print("\n๐Ÿš€ Running SMC Analysis...")
        failed_symbols = await main_analysis(
            stock_codes         = stock_codes,
            csv_directory       = csv_directory,
            fetch_csv_data      = fetch_csv_data,
            csv_column_mapping  = csv_column_mapping,
            spreadsheet_id      = spreadsheet_id,
            period              = period,
            interval            = interval,
            auto_adjust         = auto_adjust,
            visualize           = visualize,
            print_details       = print_details,
            clear               = clear,
            output_format       = output_format,
            use_colab           = use_colab
        )
        print("๐Ÿ“ˆ Analysis completed successfully!")

    if task in ["screener", "both"]:
        print("\n๐Ÿ”Ž Running SMC Screener...")
        main_screener(
            proximity_percentage    = distance_percentage,
            output_csv              = output_csv,
            spreadsheet_id          = spreadsheet_id,
            output_format           = output_format,
            clear                   = clear,
            print_details           = print_details,
            use_colab               = use_colab
        )
        print("๐Ÿ“Š Screener completed successfully!")

    # Final message
    if stock_list_name:
        print(f"\n๐ŸŽฏ Task *{task.upper()}* completed for *{stock_list_name}*! ๐ŸŽ‰")
    else:
        print(f"\n๐ŸŽฏ Task *{task.upper()}* completed successfully! ๐ŸŽ‰")

    # Report failed symbols
    if 'failed_symbols' in locals() and failed_symbols:
        print("\nโš ๏ธ Failed to fetch data for the following symbols:")
        for symbol in failed_symbols:
            print(f"   - {symbol}")

if __name__ == "__main__":
    asyncio.run(run_full_pipeline())

Customizing Parameters

Edit main_pipeline.py to customize:

  • Stock Lists: Modify nifty_top_10, nifty_50, fn_o_stocks, or nifty_500. ๐Ÿ“‹
  • Period/Interval: Change period (e.g., "1y", "max") and interval (e.g., "1d", "1h") for yfinance data. โณ
  • Output Format: Set output_format to "csv", "google_sheets", or "both". ๐Ÿ“„
  • Proximity Percentage: Adjust proximity_percentage (default 2.0) for the screener. ๐Ÿ“
  • Visualization: Set visualize=True for charts or False for faster execution. ๐Ÿ“‰
  • Clear Output: Set clear=True to overwrite existing CSV files or Google Sheets. ๐Ÿ—‘๏ธ

Output ๐Ÿ“ˆ

  • SMC Analysis:
    • CSV: Saves to analysis/smc_analysis_summaries.csv (summary data) and analysis/smc_analysis_levels.csv (key levels). ๐Ÿ“„
    • Google Sheets: Saves to Summaries and Levels worksheets (if enabled). ๐Ÿ“‘
    • Visualization: Candlestick charts with SMC levels (if visualize=True). ๐Ÿ“‰
  • SMC Screener:
    • CSV: Saves to screener_results.csv with stocks near SMC levels. ๐Ÿ“„
    • Google Sheets: Saves to Screener_Results worksheet (if enabled). ๐Ÿ“‘
    • Console: Displays a table of stocks near key levels. ๐Ÿ–ฅ๏ธ

Project Structure ๐Ÿ› ๏ธ

smc_trading/
โ”œโ”€โ”€ smc_trading/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ smc_analysis.py
โ”‚   โ”œโ”€โ”€ smc_screener.py
โ”‚   โ””โ”€โ”€ main_pipeline.py
โ”œโ”€โ”€ Credentials/
โ”‚   โ””โ”€โ”€ credentials.json
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ LICENSE
โ””โ”€โ”€ requirements.txt

yfinance Period & Interval Reference ๐Ÿ“…

  • Period: "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"
  • Interval: "1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"
  • Restrictions:
    • "1m" interval: Only last 7 days max.
    • Intraday intervals ("1m", "1h", etc.): period โ‰ค 60d.
    • Daily/weekly/monthly: Longer periods allowed.

Troubleshooting ๐Ÿž

  • yfinance Rate Limits: ๐Ÿ•’
  • Google Sheets Errors: Verify Credentials/credentials.json and share the Google Sheet with the service account. ๐Ÿ”‘
  • No Data: Check ticker validity (e.g., RELIANCE.NS). Use yf.Ticker("TICKER").info to verify. ๐Ÿ“Š
  • Visualization Issues: Ensure matplotlib is installed and visualize=True. ๐Ÿ“‰
  • Screener Empty: Run SMC Analysis first to generate smc_analysis_levels.csv and smc_analysis_summaries.csv. ๐Ÿ”

License ๐Ÿ“œ

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing ๐Ÿค

Contributions are welcome! Please submit a pull request or open an issue on the repository.

Happy trading! ๐ŸŽ‰

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

smc_screener-0.0.9.tar.gz (30.9 kB view details)

Uploaded Source

Built Distribution

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

smc_screener-0.0.9-py3-none-any.whl (32.9 kB view details)

Uploaded Python 3

File details

Details for the file smc_screener-0.0.9.tar.gz.

File metadata

  • Download URL: smc_screener-0.0.9.tar.gz
  • Upload date:
  • Size: 30.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.1

File hashes

Hashes for smc_screener-0.0.9.tar.gz
Algorithm Hash digest
SHA256 3fe9cb268fa2ab934beac74dc0798cf1ed40419660cf5a8f8e4e5ad4a8cf3722
MD5 29bd23d8b0e553ee2d02f8a28218d862
BLAKE2b-256 0a18ebaf58ec5095e5ff58e16f3702406ac8869fdc59997037bbba9fe42c6fce

See more details on using hashes here.

File details

Details for the file smc_screener-0.0.9-py3-none-any.whl.

File metadata

  • Download URL: smc_screener-0.0.9-py3-none-any.whl
  • Upload date:
  • Size: 32.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.1

File hashes

Hashes for smc_screener-0.0.9-py3-none-any.whl
Algorithm Hash digest
SHA256 5a71f84e164d5e4b5891a221318fab7e13cefa70fe2de02ee47be58b384c121d
MD5 d37ee59b7002533b04ce04387814dfb6
BLAKE2b-256 f43f993054be5198249333492e73b569cd0ea381c37a60018fa3b07f847d853b

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