### Install tradingview-screener Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Install the package using pip. This is the first step before using any of its functionalities. ```bash pip install tradingview-screener ``` -------------------------------- ### Install rookiepy for Cookie Management Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Install the rookiepy library using pip. This library helps in loading browser session cookies. ```bash pip install rookiepy ``` -------------------------------- ### Verify Update Mode with TradingView Screener Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Run this query to get an overview of the 'update_mode' for each exchange. This helps understand the data refresh rate. ```python from tradingview_screener import Query _, df = Query().select('exchange', 'update_mode').limit(1_000_000).get_scanner_data() df = df.groupby('exchange')['update_mode'].value_counts() print(df) ``` -------------------------------- ### Example Usage of get_scanner_data_raw Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Demonstrates how to select specific fields and limit the results when fetching raw scanner data. ```python >>> Query().select('close', 'volume').limit(5).get_scanner_data_raw() { 'totalCount': 17559, 'data': [ {'s': 'NASDAQ:NVDA', 'd': [116.14, 312636630]}, {'s': 'AMEX:SPY', 'd': [542.04, 52331224]}, {'s': 'NASDAQ:QQQ', 'd': [462.58, 40084156]}, {'s': 'NASDAQ:TSLA', 'd': [207.83, 76247251]}, {'s': 'NASDAQ:SBUX', 'd': [95.9, 157211696]}, ], } ``` -------------------------------- ### Example Query Configuration Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Represents a complete query configuration, including filter expressions, sorting parameters, and range settings. This is the internal JSON structure used by the API. ```python {'filter': {'operation': {'operator': 'and', 'operands': [{'expression': {'left': 'type', 'operation': 'equal', 'right': 'fund'}}, {'expression': {'left': 'typespecs', 'operation': 'has_none_of', 'right': ['etf', 'mutual', 'closedend']}}]}}, 'sort': {'sortBy': 'market_cap_basic', 'sortOrder': 'desc'}, 'range': DEFAULT_RANGE.copy(), 'ignore_unknown_fields': False} ``` -------------------------------- ### Screener Functions for Different Asset Classes Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Examples of using specific screener functions for stocks, crypto, and options. These functions return a Query object that can be further customized. ```python from tradingview_screener import stocks, crypto, options # top stocks by market cap in Italy stocks('italy').limit(5).get_scanner_data() # top CEX crypto pairs by 24 h volume crypto().limit(5).get_scanner_data() # AAPL options chain options('NASDAQ:AAPL').limit(5).get_scanner_data() ``` -------------------------------- ### Set Index and Get Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Demonstrates how to scan equities that are part of a specific index. This is useful for analyzing performance within major market indices. ```python >>> Query().set_index('SYML:SP;SPX').get_scanner_data() ``` -------------------------------- ### Select Markets and Get Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Demonstrates how to select specific markets and retrieve scanner data. This is useful for filtering results to particular financial markets. ```python >>> (Query() ... .select('close', 'market') ... .set_markets('cfd', 'crypto', 'forex', 'futures') ... .get_scanner_data()) ``` -------------------------------- ### Basic Stock Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html A simple example to select basic stock information like name, close price, volume, and market cap. The result is limited to 50 rows by default. ```python from tradingview_screener import Query x = (Query() .select('name', 'close', 'volume', 'market_cap_basic') .get_scanner_data()) print(x) ``` -------------------------------- ### Combining conditions with AND Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Illustrates using the `where2` method with the `And` operator to combine multiple filtering conditions. This example sets the market to 'crypto' and filters by exchange. ```python Query() .set_markets('crypto') .where2( And( col('exchange').isin(['UNISWAP3POLYGON', 'VERSEETH', 'a', 'fffffffff']) ) ) ``` -------------------------------- ### Advanced Options Chain Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html An example of querying the options screener with specific filters for expiration date and sorting by strike price. This demonstrates chaining methods on the Query object returned by screener functions. ```python from tradingview_screener import options, col (options('NASDAQ:AAPL') .select('name', 'close', 'ask', 'bid', 'expiration', 'volume') .where(col('expiration') == 20260427) # 2026/4/27 .order_by('strike') .limit(10) .get_scanner_data()) ``` -------------------------------- ### Query with WHERE Clause Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Filters the scanner data based on specified conditions. This example selects stocks where the 'close' price is greater than or equal to 350. ```python >>> (Query() ... .select('close', 'volume', '52 Week High') ... .where(Column('close') >= 350) ... .get_scanner_data()) (159, ticker close volume price_52_week_high 0 AMEX:SPY 410.68 107367671 459.44 1 NASDAQ:NVDA 405.00 41677185 502.66 2 NYSE:BRK.A 503375.05 7910 566569.97 3 AMEX:IVV 412.55 5604525 461.88 4 AMEX:VOO 377.32 5638752 422.15 .. ... ... ... ... 45 NASDAQ:EQIX 710.39 338549 821.63 46 NYSE:MCK 448.03 527406 465.90 47 NYSE:MTD 976.25 241733 1615.97 48 NASDAQ:CTAS 496.41 464631 525.37 49 NASDAQ:ROP 475.57 450141 508.90 [50 rows x 4 columns]) ``` -------------------------------- ### Select Screener Data for a Single Market Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Query the screener for data from a specific market, such as 'italy'. This example demonstrates selecting columns and retrieving scanner data for the specified market. ```python >>> columns = ['close', 'market', 'country', 'currency'] >>> (Query() ... .select(*columns) ... .set_markets('italy') ... .get_scanner_data()) (2346, ticker close market country currency 0 MIL:UCG 23.9150 italy Italy EUR 1 MIL:ISP 2.4910 italy Italy EUR 2 MIL:STLAM 17.9420 italy Netherlands EUR 3 MIL:ENEL 6.0330 italy Italy EUR 4 MIL:ENI 15.4800 italy Italy EUR .. ... ... ... ... ... 45 MIL:UNI 5.1440 italy Italy EUR 46 MIL:3OIS 0.4311 italy Ireland EUR 47 MIL:3SIL 35.2300 italy Ireland EUR 48 MIL:IWDE 69.1300 italy Ireland EUR 49 MIL:QQQS 19.2840 italy Ireland EUR [50 rows x 5 columns]) ``` -------------------------------- ### Set Query Offset Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Sets the starting point for results in the query, used for pagination. ```python def offset(self, offset: int) -> Self: self.query.setdefault('range', DEFAULT_RANGE.copy())[0] = offset return self ``` -------------------------------- ### Set market to Italy and get scanner data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Selects specified columns and queries data only from the 'italy' market. This is useful for country-specific financial analysis. ```python columns = ['close', 'market', 'country', 'currency'] (Query() .select(*columns) .set_markets('italy') .get_scanner_data()) ``` -------------------------------- ### Set multiple markets and get scanner data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Selects specified columns and queries data from multiple markets including 'america', 'israel', 'hongkong', and 'switzerland'. This allows for broader market analysis across different regions. ```python columns = ['close', 'market', 'country', 'currency'] (Query() .select(*columns) .set_markets('america', 'israel', 'hongkong', 'switzerland') .get_scanner_data()) ``` -------------------------------- ### Select Screener Data for Different Financial Instruments Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Query the screener for data across various financial instruments such as 'cfd', 'crypto', 'forex', and 'futures'. This example demonstrates selecting only the 'close' and 'market' columns. ```python >>> (Query() ... .select('close', 'market') ... .set_markets('cfd', 'crypto', 'forex', 'futures') ... .get_scanner_data()) (118076, ticker ... market 0 UNISWAP3ETH:JUSTICEUSDT ... crypto 1 UNISWAP3ETH:UAHGUSDT ... crypto 2 UNISWAP3ETH:KENDUWETH ... crypto 3 UNISWAP3ETH:MATICSTMATIC ... crypto 4 UNISWAP3ETH:WETHETHM ... crypto .. ... ... ... 45 UNISWAP:MUSICAIWETH_1F5304.USD ... crypto 46 CRYPTOCAP:FIL ... cfd 47 CRYPTOCAP:SUI ... cfd 48 CRYPTOCAP:ARBI ... cfd 49 CRYPTOCAP:OP ... cfd [50 rows x 3 columns]) ``` -------------------------------- ### Set Multiple Indices and Get Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Shows how to query data for multiple indices simultaneously. This is useful for comparing performance across different national or global indices. ```python >>> Query().set_index('SYML:NSE;NIFTY', 'SYML:TVC;UKX').get_scanner_data() ``` -------------------------------- ### Set Tickers and Get Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Shows how to set specific tickers to retrieve information on. This method resets markets and sets the URL market to 'global'. Use this when you know the exact symbols you are interested in. ```python >>> q = Query().select('name', 'market', 'close', 'volume', 'VWAP', 'MACD.macd') >>> q.set_tickers('NASDAQ:TSLA').get_scanner_data() ``` -------------------------------- ### Example Filter Operation Dictionary Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Illustrates the structure of a dictionary used to define a filter operation, including the left operand, operation type, and right operand. ```python {'expression': {'left': 'type', 'operation': 'equal', 'right': 'fund'}} ``` -------------------------------- ### Example Raw Scanner Data Response Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Illustrates the structure of the raw JSON data returned by get_scanner_data_raw, including total count and a list of matching symbols with their data. ```json { 'totalCount': 17559, 'data': [ {'s': 'NASDAQ:NVDA', 'd': [116.14, 312636630]}, {'s': 'AMEX:SPY', 'd': [542.04, 52331224]}, {'s': 'NASDAQ:QQQ', 'd': [462.58, 40084156]}, {'s': 'NASDAQ:TSLA', 'd': [207.83, 76247251]}, {'s': 'NASDAQ:SBUX', 'd': [95.9, 157211696]}, ], } ``` -------------------------------- ### Basic Query with Default Columns Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Performs a simple query to get scanner data with default columns (name, close, volume, market_cap_basic). Returns a tuple containing the record count and a pandas DataFrame. ```python >>> from tradingview_screener import Query >>> Query().get_scanner_data() (18060, ticker name close volume market_cap_basic 0 AMEX:SPY SPY 410.68 107367671 NaN 1 NASDAQ:QQQ QQQ 345.31 63475390 NaN 2 NASDAQ:TSLA TSLA 207.30 94879471 6.589904e+11 3 NASDAQ:NVDA NVDA 405.00 41677185 1.000350e+12 4 NASDAQ:AMZN AMZN 127.74 125309313 1.310658e+12 .. ... ... ... ... ... 45 NYSE:UNH UNH 524.66 2585616 4.859952e+11 46 NASDAQ:DXCM DXCM 89.29 14954605 3.449933e+10 47 NYSE:MA MA 364.08 3624883 3.429080e+11 48 NYSE:ABBV ABBV 138.93 9427212 2.452179e+11 49 AMEX:XLK XLK 161.12 8115780 NaN [50 rows x 5 columns]) ``` -------------------------------- ### Column Initialization Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Shows how to initialize a Column object with a given field name. This is the first step to using any of the Column's methods for querying. ```python col = Column('close') ``` -------------------------------- ### Python: Define 'below_pct' filter operation with example Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Returns a filter operation dictionary to check if a column's value is below a certain percentage of another column's value. Includes an example for usage. ```python def below_pct(self, column: Column | str, pct: float) -> FilterOperationDict: return { 'left': self.name, 'operation': 'below%', 'right': [self._extract_name(column), pct], } ``` ```python Column('close').below_pct('VWAP', 1.03) ``` -------------------------------- ### Python: Define 'above_pct' filter operation with examples Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Returns a filter operation dictionary to check if a column's value is above a certain percentage of another column's value. Includes examples for usage. ```python def above_pct(self, column: Column | str, pct: float) -> FilterOperationDict: return { 'left': self.name, 'operation': 'above%', 'right': [self._extract_name(column), pct], } ``` ```python Column('close').above_pct('VWAP', 1.03) ``` ```python Column('close').above_pct('price_52_week_low', 2.5) ``` -------------------------------- ### Basic Column Comparisons Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Demonstrates basic comparison operations for Column objects against values or other columns. ```python >>> Column('close') > 2.5 >>> Column('High.All') <= 'high' >>> Column('high') > 'VWAP' >>> Column('high') > Column('VWAP') # same thing as above >>> Column('is_primary') == True >>> Column('exchange') != 'OTC' ``` -------------------------------- ### Column Initialization and Basic Comparisons Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Initializes a Column object and demonstrates basic comparison operations like greater than, less than, equal to, and not equal to. ```python >>> Column('typespecs').has_none_of(['reit', 'etn', 'etf']) ``` ```python >>> Column('description').like('apple') # the same as `description LIKE '%apple%'` ``` ```python >>> Column('premarket_change').not_empty() # same as `Column('premarket_change') != None` ``` ```python >>> Column('earnings_release_next_trading_date_fq').in_day_range(0, 0) # same day ``` ```python def __init__(self, name: str) -> None: self.name = name ``` ```python def __gt__(self, other) -> FilterOperationDict: return {'left': self.name, 'operation': 'greater', 'right': self._extract_name(other)} ``` ```python def __ge__(self, other) -> FilterOperationDict: return {'left': self.name, 'operation': 'egreater', 'right': self._extract_name(other)} ``` ```python def __lt__(self, other) -> FilterOperationDict: return {'left': self.name, 'operation': 'less', 'right': self._extract_name(other)} ``` ```python def __le__(self, other) -> FilterOperationDict: return {'left': self.name, 'operation': 'eless', 'right': self._extract_name(other)} ``` ```python def __eq__(self, other) -> FilterOperationDict: # pyright: ignore [reportIncompatibleMethodOverride] return {'left': self.name, 'operation': 'equal', 'right': self._extract_name(other)} ``` ```python def __ne__(self, other) -> FilterOperationDict: # pyright: ignore [reportIncompatibleMethodOverride] return {'left': self.name, 'operation': 'nequal', 'right': self._extract_name(other)} ``` -------------------------------- ### Date Range Filter Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Example of filtering for values within a specific day range, such as the same day. ```python >>> Column('earnings_release_next_trading_date_fq').in_day_range(0, 0) # same day ``` -------------------------------- ### String Matching and Empty Checks Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Shows how to perform string matching (like, not_like) and check for non-empty fields. ```python >>> Column('description').like('apple') # the same as `description LIKE '%apple%'` >>> Column('premarket_change').not_empty() # same as `Column('premarket_change') != None` ``` -------------------------------- ### Percentage-Based Column Comparisons Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Shows how to perform percentage-based comparisons using methods like `above_pct`, `below_pct`, and `between_pct`. These are useful for relative value checks. ```python Column('close').above_pct('VWAP', 1.03) Column('close').above_pct('price_52_week_low', 2.5) Column('close').below_pct('VWAP', 1.03) Column('close').between_pct('EMA200', 1.2, 1.5) Column('close').not_between_pct('EMA200', 1.2, 1.5) ``` -------------------------------- ### Set Multiple Markets and Tickers Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Illustrates setting multiple markets and then specifying tickers from those markets. This is useful for a broad scan across different regions or asset types. ```python >>> (Query() ... .set_markets('america', 'italy', 'vietnam') ... .set_tickers('NYSE:GME', 'AMEX:SPY', 'MIL:RACE', 'HOSE:VIX') ... .get_scanner_data()) ``` -------------------------------- ### Select Columns, Filter, Order, and Limit Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html This snippet shows how to build a query to select specific columns, apply multiple filter conditions, order the results by volume in descending order, and limit the output to 50 items. It's useful for creating custom stock screening criteria. ```python top_50_bullish = ( Query() .select('name', 'close', 'volume', 'relative_volume_10d_calc') .where( Column('market_cap_basic').between(1_000_000, 50_000_000), Column('relative_volume_10d_calc') > 1.2, Column('MACD.macd') >= Column('MACD.signal') ) .order_by('volume', ascending=False) .limit(50) ) ``` -------------------------------- ### Filter by Single Index Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Use set_index to scan equities within a specified index like the S&P 500. This example demonstrates filtering by 'SYML:SP;SPX'. ```python 607 def set_index(self, *indexes: str) -> Self: 608 """ 609 Scan only the equities that are in the given index (or indexes). 610 611 Note that this resets the markets and sets the URL market to `global`. 612 613 Examples: 614 615 >>> Query().set_index('SYML:SP;SPX').get_scanner_data() 616 (503, 617 ticker name close volume market_cap_basic 618 0 NASDAQ:NVDA NVDA 1208.88 41238122 2.973644e+12 619 1 NASDAQ:AAPL AAPL 196.89 53103705 3.019127e+12 620 2 NASDAQ:TSLA TSLA 177.48 56244929 5.660185e+11 621 3 NASDAQ:AMD AMD 167.87 44795240 2.713306e+11 622 4 NASDAQ:MSFT MSFT 423.85 13621485 3.150183e+12 623 5 NASDAQ:AMZN AMZN 184.30 28021473 1.917941e+12 624 6 NASDAQ:META META 492.96 9379199 1.250410e+12 625 7 NASDAQ:GOOGL GOOGL 174.46 19660698 2.164346e+12 626 8 NASDAQ:SMCI SMCI 769.11 3444852 4.503641e+10 627 9 NASDAQ:GOOG GOOG 175.95 14716134 2.164346e+12 628 10 NASDAQ:AVGO AVGO 1406.64 1785876 6.518669e+11) 629 630 You can set multiple indices as well, like the NIFTY 50 and UK 100 Index. 631 >>> Query().set_index('SYML:NSE;NIFTY', 'SYML:TVC;UKX').get_scanner_data() 632 (150, 633 ticker name close volume market_cap_basic 633 0 NSE:INFY INFY 1533.600000 24075302 7.623654e+10 634 1 LSE:AZN AZN 12556.000000 2903032 2.489770e+11 635 2 NSE:HDFCBANK HDFCBANK 1573.350000 18356108 1.432600e+11 636 3 NSE:RELIANCE RELIANCE 2939.899900 9279348 2.381518e+11 637 4 LSE:LSEG LSEG 9432.000000 2321053 6.395329e+10 638 5 NSE:BAJFINANCE BAJFINANCE 7191.399900 2984052 5.329685e+10 639 6 LSE:BARC BARC 217.250000 96238723 4.133010e+10 640 7 NSE:SBIN SBIN 829.950010 25061284 8.869327e+10 641 8 NSE:LT LT 3532.500000 5879660 5.816100e+10 642 9 LSE:SHEL SHEL 2732.500000 7448315 2.210064e+11) 643 644 You can find the full list of indices in [`constants.INDICES`](constants.html#INDICES), 645 just note that the syntax is 646 `SYML:{source};{symbol}`. 647 648 :param indexes: One or more strings representing the financial indexes to filter by 649 :return: An instance of the `Query` class with the filter applied 650 """ 651 self.query.setdefault('preset', 'index_components_market_pages') 652 self.query.setdefault('symbols', {})['symbolset'] = list(indexes) 653 # reset markets list and URL to `/global` 654 self.set_markets() 655 return self ``` -------------------------------- ### Forex Screener Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Configures a screener for forex currency pairs, sorted by traded value descending. Requires 'tradingview_screener' and 'URL' to be imported. ```python 186def forex() -> Query: """ Screener for forex currency pairs, sorted by traded value descending. """ q = Query() q.url = URL.format(market='forex') q.query = { 'markets': ['forex'], 'symbols': {}, 'options': {'lang': 'en'}, 'columns': ['name', 'close', 'volume', 'currency'], 'sort': {'sortBy': 'Value.Traded', 'sortOrder': 'desc'}, 'range': DEFAULT_RANGE.copy(), 'ignore_unknown_fields': False, } return q ``` -------------------------------- ### Order query results by close ascending Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Applies sorting to query results by 'close' price in ascending order. Use this to see assets with lower closing prices first. ```python Query().order_by('close', ascending=True) ``` -------------------------------- ### Example Complex Filter with AND/OR Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Shows a more complex filter structure combining 'and' and 'or' operators with nested expressions. This is part of the internal query construction logic. ```python {'operation': {'operator': 'and', 'operands': [{'expression': {'left': 'type', 'operation': 'equal', 'right': 'fund'}}, {'expression': {'left': 'typespecs', 'operation': 'has_none_of', 'right': ['etf', 'mutual', 'closedend']}}]}} ``` -------------------------------- ### Get Scanner Data as DataFrame Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Fetches scanner data and returns it as a Pandas DataFrame along with the total count of matching rows. Supports forwarding of `requests.post()` arguments. ```python def get_scanner_data(self, **kwargs) -> tuple[int, pd.DataFrame]: import pandas as pd json_obj = self.get_scanner_data_raw(**kwargs) rows_count = json_obj['totalCount'] if '/scan2' in self.url: columns = ['ticker', *json_obj['fields']] rows = json_obj.get('symbols') if rows: df = pd.DataFrame(([row['s'], *row['f']] for row in rows), columns=columns) else: df = pd.DataFrame([], columns=columns) else: rows = json_obj['data'] columns = ['ticker', *self.query.get('columns', ())] # pyright: ignore [reportArgumentType] df = pd.DataFrame(([row['s'], *row['d']] for row in rows), columns=columns) return rows_count, df ``` -------------------------------- ### Basic Column Comparisons Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Demonstrates basic comparison operations like greater than, less than, equal to, and not equal to on Column objects. These can be used with string literals or other Column objects. ```python Column('close') > 2.5 Column('High.All') <= 'high' Column('high') > 'VWAP' Column('high') > Column('VWAP') Column('is_primary') == True Column('exchange') != 'OTC' ``` -------------------------------- ### Get Scanner Data as DataFrame Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Retrieves scanner data from the API and converts it into a pandas DataFrame for easier analysis. It also returns the total count of matching rows. ```python import pandas as pd json_obj = self.get_scanner_data_raw(**kwargs) rows_count = json_obj['totalCount'] ``` -------------------------------- ### Advanced Stock Query with Filters Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Demonstrates an advanced query with multiple filtering conditions including market cap range, relative volume, and MACD indicator. It also shows how to set the number of results and skip records. ```python from tradingview_screener import Query, col (Query() .select('name', 'close', 'close|1', 'close|5', 'volume', 'relative_volume_10d_calc') .where( col('market_cap_basic').between(1_000_000, 50_000_000), col('relative_volume_10d_calc') > 1.2, col('MACD.macd|1') >= col('MACD.signal|1') # 1 minute MACD ) .order_by('volume', ascending=False) .offset(5) .limit(25) .get_scanner_data()) ``` -------------------------------- ### Get Raw Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Performs a POST request to the TradingView API and returns the raw JSON response. Allows forwarding of `requests.post()` arguments like headers or timeouts. ```python def get_scanner_data_raw(self, **kwargs) -> tradingview_screener.models.ScreenerDict | tradingview_screener.models.ScreenerDictV2: self.query.setdefault('range', DEFAULT_RANGE.copy()) kwargs.setdefault('headers', HEADERS) kwargs.setdefault('timeout', 20) r = requests.post(self.url, json=self.query, **kwargs) if not r.ok: # add the body to the error message for debugging purposes r.reason += f'\n Body: {r.text}\n' r.raise_for_status() return r.json() ``` -------------------------------- ### Column Initialization Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Constructor for the Column class, initializing a column with its name. ```python def __init__(self, name: str) -> None: self.name = name ``` -------------------------------- ### Get Raw Scanner Data Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Performs a POST request to the TradingView API and returns the raw JSON response. Allows forwarding of requests.post() arguments like headers and timeouts. ```python self.query.setdefault('range', DEFAULT_RANGE.copy()) kwargs.setdefault('headers', HEADERS) kwargs.setdefault('timeout', 20) r = requests.post(self.url, json=self.query, **kwargs) if not r.ok: # add the body to the error message for debugging purposes r.reason += f'\n Body: {r.text}\n' r.raise_for_status() return r.json() ``` -------------------------------- ### Query with Selected Columns Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Shows how to customize the query to select specific columns beyond the default set. This allows for fetching more granular data points for analysis. ```python Query().select('open', 'high', 'low', 'VWAP', 'MACD.macd', 'RSI', 'Price to Earnings Ratio (TTM)').get_scanner_data() ``` -------------------------------- ### DEX Crypto Screener Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Configures a screener for decentralized exchange (DEX) spot crypto pairs priced in USD, sorted by 24h transaction count descending. Requires 'tradingview_screener' and 'URL' to be imported. ```python 98def crypto_dex() -> Query: """ Screener for decentralised-exchange (DEX) spot pairs priced in USD, sorted by 24 h transaction count descending. """ q = Query() q.url = URL.format(market='crypto') q.query = { 'markets': ['crypto'], 'symbols': {}, 'options': {'lang': 'en'}, 'columns': [ 'ticker-view', 'blockchain-id.tr', 'blockchain-id', 'exchange.tr', 'provider-id', 'close', 'type', 'typespecs', 'pricescale', 'minmov', 'fractional', 'minmove2', 'currency', '24h_close_change|5', 'dex_txs_count_24h', 'dex_trading_volume_24h', 'dex_txs_count_uniq_24h', 'dex_total_liquidity', 'fully_diluted_value', 'TechRating_1D', 'TechRating_1D.tr', ], 'filter2': { 'operator': 'and', 'operands': [ { 'operation': { 'operator': 'and', 'operands': [ { 'expression': { 'left': 'centralization', 'operation': 'equal', 'right': 'dex', } }, { 'expression': { 'left': 'currency_id', 'operation': 'equal', 'right': 'USD', } }, ], } }, { 'operation': { 'operator': 'or', 'operands': [ { 'operation': { 'operator': 'and', 'operands': [ { 'expression': { 'left': 'type', 'operation': 'equal', 'right': 'spot', } } ], } } ], } }, ], }, 'sort': {'sortBy': 'dex_txs_count_24h', 'sortOrder': 'desc'}, 'range': DEFAULT_RANGE.copy(), 'ignore_unknown_fields': False, } return q ``` -------------------------------- ### Percentage-Based Column Filters Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/column.html Shows how to use methods like above_pct, below_pct, and between_pct to filter columns based on percentage changes relative to other columns or values. ```python >>> Column('close').above_pct('VWAP', 1.03) >>> Column('close').above_pct('price_52_week_low', 2.5) >>> Column('close').below_pct('VWAP', 1.03) >>> Column('close').between_pct('EMA200', 1.2, 1.5) >>> Column('close').not_between_pct('EMA200', 1.2, 1.5) ``` -------------------------------- ### Get Scanner Data as a Pandas DataFrame Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Fetches data from the TradingView screener API and returns it as a Pandas DataFrame, along with the total count of matching rows. This method is convenient for data analysis and manipulation. ```python Query().get_scanner_data() ``` -------------------------------- ### Import Core Components and Screeners Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener.html Imports essential classes and functions from the tradingview_screener library, including Column, Query, and various screener types like stocks, forex, and crypto. ```python from __future__ import annotations from tradingview_screener.column import Column, col from tradingview_screener.query import Query, And, Or from tradingview_screener.screeners import ( bond, cfd, coin, crypto, crypto_dex, forex, futures, options, stocks, ) ``` -------------------------------- ### Combine conditions with AND Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Filters entities in the 'crypto' market where the exchange is in a specified list and the currency ID is 'USD'. ```python Query() .set_markets('crypto') .where2( And( col('exchange').isin(['UNISWAP3POLYGON', 'VERSEETH', 'a', 'fffffffff']), col('currency_id') == 'USD', ) ) ``` -------------------------------- ### Complex Filtering with AND/OR Operators Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html This example demonstrates advanced filtering capabilities using the `where2` method, allowing for complex logical combinations of conditions with AND and OR operators, including nested expressions. It's used when simple AND chaining is insufficient. ```python Query() .select('type', 'typespecs') .where2( Or( And(Column('type') == 'stock', Column('typespecs').has(['common', 'preferred'])), And(Column('type') == 'fund', Column('typespecs').has_none_of(['etf'])), Column('type') == 'dr', ) ) ``` -------------------------------- ### Options Screener Query Configuration Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Configures a query for options, specifying columns and filters. The `underlying` parameter is required to specify the asset for which options are screened. ```python def options(underlying: str) -> Query: """ :param underlying: The underlying symbol to filter by, e.g. ``'CME_MINI:ESM2026'``. """ q = Query() q.url = 'https://scanner.tradingview.com/options/scan2?label-product=options-builder' q.query = { 'columns': [ 'ask', 'bid', 'currency', 'delta', 'expiration', 'gamma', 'iv', 'option-type', 'pricescale', 'rho', 'root', 'strike', 'theoPrice', 'theta', 'vega', 'bid_iv', 'ask_iv', ], 'filter2': { 'operator': 'and', 'operands': [{'expression': {'left': 'type', 'operation': 'equal', 'right': 'option'}}], }, 'ignore_unknown_fields': False, } ``` -------------------------------- ### Get Raw Scanner Data via POST Request Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Retrieves raw JSON data from the TradingView screener API using a POST request. Supports passing custom headers and timeouts. The returned data includes total count and a list of matching symbols with their data. ```python Query().select('close', 'volume').limit(5).get_scanner_data_raw() ``` -------------------------------- ### Stocks Screener Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Returns a Query object for screening stocks. Allows specifying the market/country. ```python def stocks(market: str = 'america') -> Query: return Query(market) ``` -------------------------------- ### Set Markets for Screener Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Configures the screener query to fetch data for specified markets. If multiple markets are provided, it defaults to a 'global' market setting in the URL. ```python self.url = URL.format(market=market) self.query['markets'] = [market] ``` ```python self.url = URL.format(market='global') self.query['markets'] = list(markets) ``` -------------------------------- ### Complex Filtering with Ordering, Offset, and Limit Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Select 'name', 'close', 'volume', and 'relative_volume_10d_calc' for stocks with a market cap between 1M and 50M, relative volume > 1.2, and positive MACD. The results are ordered by volume descending, with an offset of 5 and a limit of 15. This is useful for finding specific stocks based on multiple criteria and pagination. ```python >>> (Query() ... .select('name', 'close', 'volume', 'relative_volume_10d_calc') ... .where( ... Column('market_cap_basic').between(1_000_000, 50_000_000), ... Column('relative_volume_10d_calc') > 1.2, ... Column('MACD.macd') >= Column('MACD.signal') ... ) ... .order_by('volume', ascending=False) ... .offset(5) ... .limit(15) ... .get_scanner_data()) ``` -------------------------------- ### Order query results by dividends yield descending with nulls first Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Applies sorting to query results by 'dividends_yield_current' in descending order, placing null values at the beginning. Use this to prioritize assets with high yields while keeping those with missing data at the top. ```python Query().order_by('dividends_yield_current', ascending=False, nulls_first=False) ``` -------------------------------- ### Decentralized Exchange (DEX) Crypto Pairs Screener Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Sets up a Query object for screening decentralized exchange (DEX) spot pairs priced in USD, sorted by 24-hour transaction count. Includes filters for DEX and USD currency. ```python def crypto_dex() -> Query: """ Screener for decentralised-exchange (DEX) spot pairs priced in USD, sorted by 24 h transaction count descending. """ q = Query() q.url = URL.format(market='crypto') q.query = { 'markets': ['crypto'], 'symbols': {}, 'options': {'lang': 'en'}, 'columns': [ 'ticker-view', 'blockchain-id.tr', 'blockchain-id', 'exchange.tr', 'provider-id', 'close', 'type', 'typespecs', 'pricescale', 'minmov', 'fractional', 'minmove2', 'currency', '24h_close_change|5', 'dex_txs_count_24h', 'dex_trading_volume_24h', 'dex_txs_count_uniq_24h', 'dex_total_liquidity', 'fully_diluted_value', 'TechRating_1D', 'TechRating_1D.tr', ], 'filter2': { 'operator': 'and', 'operands': [ { 'operation': { 'operator': 'and', 'operands': [ { 'expression': { 'left': 'centralization', 'operation': 'equal', 'right': 'dex', } }, { 'expression': { 'left': 'currency_id', 'operation': 'equal', 'right': 'USD', } }, ], } }, ], }, } return q ``` -------------------------------- ### Select Screener Data for Multiple Markets Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/query.html Query the screener for data from multiple specified markets like 'america', 'israel', 'hongkong', and 'switzerland'. This shows how to combine different market selections in a single query. ```python >>> (Query() ... .select(*columns) ... .set_markets('america', 'israel', 'hongkong', 'switzerland') ... .get_scanner_data()) (23964, ticker close market country currency 0 AMEX:SPY 420.1617 america United States USD 1 NASDAQ:TSLA 201.2000 america United States USD 2 NASDAQ:NVDA 416.7825 america United States USD 3 NASDAQ:AMD 106.6600 america United States USD 4 NASDAQ:QQQ 353.7985 america United States USD .. ... ... ... ... ... 45 NASDAQ:GOOGL 124.9200 america United States USD 46 HKEX:1211 233.2000 hongkong China HKD 47 TASE:ALHE 1995.0000 israel Israel ILA 48 AMEX:BIL 91.4398 america United States USD 49 NASDAQ:GOOG 126.1500 america United States USD [50 rows x 5 columns]) ``` -------------------------------- ### Crypto Coins Screener Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Initializes a Query object for screening crypto coins from CoinMarketCap, sorted by overall rank. Includes a comprehensive list of columns for detailed crypto information. ```python def coin() -> Query: """ Screener for crypto coins (CoinMarketCap universe), sorted by overall rank ascending. """ q = Query() q.url = URL.format(market='coin') q.query = { 'markets': ['coin'], 'symbols': {}, 'options': {'lang': 'en'}, 'columns': [ 'ticker-view', 'crypto_total_rank', 'close', 'type', 'typespecs', 'pricescale', 'minmov', 'fractional', 'minmove2', 'currency', '24h_close_change|5', 'market_cap_calc', 'fundamental_currency_code', '24h_vol_cmc', 'circulating_supply', '24h_vol_to_market_cap', 'socialdominance', 'crypto_common_categories.tr', 'TechRating_1D', 'TechRating_1D.tr', ], 'sort': {'sortBy': 'crypto_total_rank', 'sortOrder': 'asc'}, 'range': DEFAULT_RANGE.copy(), 'ignore_unknown_fields': False, } return q ``` -------------------------------- ### Crypto Coins Screener Query Source: https://shner-elmo.github.io/TradingView-Screener/3.2.0/tradingview_screener/screeners.html Returns a Query object for screening crypto coins from CoinMarketCap, sorted by rank. ```python def coin() -> Query: q = Query() q.url = URL.format(market='coin') q.query = { 'markets': ['coin'], 'symbols': {}, 'options': {'lang': 'en'}, 'columns': [ 'ticker-view', 'crypto_total_rank', 'close', 'type', 'typespecs', 'pricescale', 'minmov', 'fractional', 'minmove2', 'currency', '24h_close_change|5', 'market_cap_calc', 'fundamental_currency_code', '24h_vol_cmc', 'circulating_supply', '24h_vol_to_market_cap', 'socialdominance', 'crypto_common_categories.tr', 'TechRating_1D', 'TechRating_1D.tr', ], 'sort': {'sortBy': 'crypto_total_rank', 'sortOrder': 'asc'}, 'range': DEFAULT_RANGE.copy(), 'ignore_unknown_fields': False, } return q ```