tvscreener Documentation

repository·main·Indexed 22 days ago

https://github.com/deepentropy/tvscreener

A Python library for retrieving and filtering market data from the TradingView™ Screener. It provides a type-safe, fluent API to query Stocks, Crypto, Forex, Bonds, Futures, and Coins, returning results as Pandas DataFrames. Features include support for over 13,000 fields, technical indicator customization with specific time intervals, market/index filtering, and Model Context Protocol (MCP) support for AI assistants.

Tokens
37.8K
Snippets
164
Records
180
Agent score
75%

What's inside tvscreener

  1. Use method chaining for fluent queries

    main

    Most configuration methods in the screener API return self, allowing you to build complex queries using a fluent, chained syntax.

    df = (
        StockScreener()
        .select(StockField.NAME, StockField.PRICE)
        .where(StockField.PRICE > 100)
        .sort_by(StockField.VOLUME, ascending=False)
        .set_range(0, 50)
        .get()
    )
  2. Use multi-timeframe analysis with CoinField

    main

    You can perform multi-timeframe analysis by using the .with_interval(minutes) method on a CoinField. This allows you to compare indicators (like RSI) from different timeframes within a single query.

    Note: The interval is specified in minutes (e.g., '240' for 4-hour).

    cs = CoinScreener()
    
    # Daily RSI moderate
    cs.where(CoinField.RELATIVE_STRENGTH_INDEX_14.between(40, 60))
    
    # 4-hour RSI oversold
    rsi_4h = CoinField.RELATIVE_STRENGTH_INDEX_14.with_interval('240')
    cs.where(rsi_4h < 35)
    
    cs.select(
        CoinField.NAME,
        CoinField.PRICE,
        CoinField.RELATIVE_STRENGTH_INDEX_14,
        rsi_4h
    )
    
    df = cs.get()
  3. Identify which fields support intervals

    main

    Not all fields can be used with .with_interval().

    Supported Fields (Technical Indicators):

    • RSI, MACD, Stochastic, CCI, etc.
    • Moving averages (SMA, EMA)
    • Bollinger Bands
    • ATR, ADX
    • Volume indicators

    Unsupported Fields (Fundamental Data): Fundamental fields are point-in-time values and do not support intervals:

    • P/E, P/B, Market Cap
    • Revenue, Earnings, Margins
    • Dividend data
  4. Filter logic and field types in tvscreener

    main

    When building queries (either via the Code Generator or directly in Python), the available operators depend on the data type of the field being filtered:

    • Numeric Fields: Support comparison operators such as >, <, >=, <=, and between.
    • Text Fields: Support equality == and membership isin operators.

    It is recommended to start with simple filters and verify results before adding complex multi-condition queries.

  5. Use Pythonic filtering with where()

    main

    Instead of string-based queries, tvscreener allows you to use standard Python comparison operators (>, <, >=, <=, ==, !=) directly on field objects within the .where() method. You can also use helper methods like .between(low, high) on field objects.

    # Example of Pythonic comparison
    ss.where(StockField.PRICE > 50)
    
    # Example of range filtering
    ss.where(StockField.PE_RATIO_TTM.between(10, 25))
  6. Chain multiple filters with AND logic

    main

    When using StockScreener.where(), all added filters are combined using AND logic. A stock must satisfy every condition to be included in the results returned by .get().

    Note that filters are validated against the screener type (e.g., you cannot use CryptoField with a StockScreener).

    from tvscreener import StockScreener, StockField
    
    ss = StockScreener()
    
    # All conditions must be true (AND logic)
    ss.where(StockField.PRICE > 50)
    ss.where(StockField.PRICE < 500)
    ss.where(StockField.VOLUME >= 1_000_000)
    ss.where(StockField.PE_RATIO_TTM.between(10, 30))
    
    df = ss.get()  # Returns stocks matching ALL conditions
  7. Compare CoinScreener and CryptoScreener

    main

    Choose the correct screener based on your data requirements:

    FeatureCoinScreenerCryptoScreener
    Data SourceCoinGecko-styleTradingView exchanges
    FocusCoins/tokensTrading pairs
    MetricsMarket cap, supplyExchange volume

    Use CoinScreener for fundamental coin metrics and CryptoScreener for technical analysis of specific exchange trading pairs.

  8. Filter, Sort, and Select data with CryptoScreener

    main

    Use the following methods to build complex queries on the CryptoScreener instance:

    • .where(condition): Filters the results based on a boolean condition (e.g., CryptoField.VOLUME > 10_000_000). Supports Pythonic comparison syntax.
    • .sort_by(field, ascending=True/False): Sorts the results by a specific CryptoField.
    • .set_range(start, end): Limits the number of results returned (e.g., 0 to 100).
    • .select(*fields): Limits the columns returned in the resulting DataFrame. Use .select_all() to include all available fields.
    • .get(): Executes the query and returns a pandas DataFrame.
    cs = CryptoScreener()
    cs.where(CryptoField.CHANGE_PERCENT > 10)
    cs.sort_by(CryptoField.CHANGE_PERCENT, ascending=False)
    cs.set_range(0, 50)
    df = cs.get()
  9. Filter, sort, and select bond data

    main

    Use the following methods on a BondScreener instance to refine your query before calling .get():

    • .where(condition): Apply filters using Pythonic comparison syntax (e.g., BondField.YIELD < 4).
    • .sort_by(field, ascending=True/False): Sort the results by a specific field.
    • .set_range(start, end): Limit the number of results returned (pagination/slicing).
    • .select(*fields): Specify only the columns you want in the resulting DataFrame.
    • .select_all(): Select all available fields (~201 columns).
    # Example: RSI Analysis
    bs = BondScreener()
    bs.where(BondField.RELATIVE_STRENGTH_INDEX_14 < 40)
    bs.select(
        BondField.NAME,
        BondField.YIELD,
        BondField.RELATIVE_STRENGTH_INDEX_14
    )
    
    df = bs.get()
  10. Stop a streaming session

    main

    Since stream() is an infinite iterator, you must implement a mechanism to stop it. You can stop the stream using:

    1. Keyboard Interrupt: Wrap the loop in a try/except KeyboardInterrupt block to handle Ctrl+C gracefully.
    2. Update Count: Use a counter to break the loop after a specific number of updates.
    3. Conditional Logic: Inspect the yielded DataFrame and break when a specific market condition is met (e.g., a price drop threshold).
    # Stop after N updates
    count = 0
    max_updates = 10
    for df in ss.stream(interval=5):
        count += 1
        if count >= max_updates:
            break
    
    # Stop on condition (e.g., stock drops > 10%)
    for df in ss.stream(interval=5):
        if (df['change'] < -10).any():
            print("Alert: Stock dropped >10%!")
            break
  11. Discover and use technical indicator fields

    main

    The library includes over 13,000 fields. You can search for fields by name or label, or retrieve specific categories like technical indicators or recommendations.

    Technical indicators can be customized with specific time intervals using the .with_interval(interval) method. Supported intervals include: 1, 5, 15, 30, 60, 120, 240, 1D, 1W, 1M.

    from tvscreener import StockScreener, StockField
    
    # Search fields by name
    rsi_fields = StockField.search("rsi")
    
    # Get all technical indicator fields
    technicals = StockField.technicals()
    
    # Use a technical field with a specific interval (e.g., 1-hour)
    rsi_1h = StockField.RELATIVE_STRENGTH_INDEX_14.with_interval("60")
    
    ss = StockScreener()
    ss.specific_fields = [
        StockField.NAME,
        StockField.PRICE,
        rsi_1h
    ]
    df = ss.get()