### Run a caching example Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Execute the example that demonstrates the built-in caching functionality. ```bash python examples/caching_example.py ``` -------------------------------- ### Install development dependencies Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Install the project and its development dependencies using pip. ```bash pip install -e .[dev,analysis] ``` -------------------------------- ### Run an async parallel fetching example Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Execute the example demonstrating asynchronous fetching of multiple countries in parallel. ```bash python examples/async_parallel_fetching.py ``` -------------------------------- ### Run a basic RSS usage example Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Execute the basic RSS feed download example script. ```bash python examples/basic_rss_usage.py ``` -------------------------------- ### Install trendspyg with CLI support Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Install the trendspyg package with command-line interface support. Alternatively, install with analysis features. ```bash pip install trendspyg[cli] ``` ```bash pip install trendspyg[cli,analysis] ``` -------------------------------- ### Install trendspyg with CLI Support Source: https://github.com/flack0x/trendspyg/blob/main/README.md Install the trendspyg library with command-line interface capabilities. ```bash pip install trendspyg[cli] ``` -------------------------------- ### Install trendspyg with all features Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Install the trendspyg library with all optional dependencies for CLI, analysis, and asynchronous operations. ```bash pip install trendspyg[cli,analysis,async] ``` -------------------------------- ### Install trendspyg with Async Support Source: https://github.com/flack0x/trendspyg/blob/main/README.md Install the trendspyg library with support for asynchronous operations. ```bash pip install trendspyg[async] ``` -------------------------------- ### CLI Monitoring Example Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Demonstrates how to use the TrendspyG command-line interface to monitor Google Trends in real-time. This example shows how to stream changes for new or volume-up events with a minimum volume threshold. ```APIDOC ## CLI Monitoring Example ### Description Streams one NDJSON change per line to standard output, ensuring that stdout remains pipe-clean. This command-line interface allows for real-time monitoring of Google Trends with specified filters. ### Command ```bash trendspyg watch --geo US --interval 60 --events new,volume_up --min-volume 50000 ``` ### Parameters - `--geo`: Specifies the geographic region to monitor (e.g., 'US'). - `--interval`: Sets the polling interval in seconds. - `--events`: Filters the types of trend changes to stream (e.g., 'new', 'volume_up'). - `--min-volume`: Sets the minimum volume for a trend to be considered. ### Request Example None ### Response Outputs NDJSON formatted trend changes to stdout. ``` -------------------------------- ### Python function example with type hints and docstring Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Example of a Python function demonstrating type hints, default arguments, and a comprehensive docstring following PEP 8 guidelines. ```python def download_google_trends_rss( geo: str = 'US', output_format: OutputFormat = 'dict' ) -> Union[List[Dict], str, 'pd.DataFrame']: """ Download Google Trends RSS feed data. Args: geo: Country/region code (e.g., 'US', 'GB') output_format: Output format ('dict', 'json', 'csv', 'dataframe') Returns: Trend data in requested format Raises: InvalidParameterError: If parameters are invalid """ ``` -------------------------------- ### Get TrendspyG Version Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Demonstrates how to import and print the installed version of the TrendspyG library using the __version__ attribute. ```python from trendspyg import __version__ print(__version__) # '0.7.0' ``` -------------------------------- ### Install Analysis/DataFrame Format Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Install the TrendspyG package with analysis support. This is required if you intend to use the 'dataframe' output format, which depends on pandas. ```bash pip install trendspyg[analysis] ``` -------------------------------- ### Install trendspyg core Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Installs the core trendspyg library, including RSS and CSV path functionalities, but without CLI, async, or DataFrame support. ```bash pip install trendspyg ``` -------------------------------- ### Show trendspyg package info Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Display information about the installed trendspyg package. ```bash trendspyg info ``` -------------------------------- ### TrendspyG Explore CLI Command Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Example usage of the 'trendspyg explore' command-line interface for keyword analysis. Options include timeframe, output format, and verbosity. ```bash trendspyg explore -k/--keyword, --timeframe, --output, --full, --quiet ``` -------------------------------- ### Check Dependencies with pip-audit Source: https://github.com/flack0x/trendspyg/blob/main/SECURITY.md Use pip-audit to check installed Python packages for known vulnerabilities. This command reads directly from the installed environment or pyproject.toml. ```bash pip install pip-audit pip-audit ``` -------------------------------- ### Get US State Codes Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Retrieves a list of US state codes available in the configuration. The first 5 codes are printed. ```python from trendspyg.config import US_STATES # Example: {'US-CA': 'California', 'US-NY': 'New York', ...} print(list(US_STATES.keys())[:5]) # ['US-AL', 'US-AK', 'US-AZ', 'US-AR', 'US-CA'] ``` -------------------------------- ### Download Google Trends RSS with Normalized Output Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Use `normalize=True` to get a `NormalizedEnvelope` for consistent data across different download methods. The `output_format` parameter is ignored when normalization is enabled. ```python from trendspyg import download_google_trends_rss env = download_google_trends_rss(geo='US', normalize=True) ``` -------------------------------- ### Get Country Codes Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Retrieves a list of country codes available in the configuration. The first 10 codes are printed. ```python from trendspyg.config import COUNTRIES # Example: {'US': 'United States', 'GB': 'United Kingdom', ...} print(list(COUNTRIES.keys())[:10]) # ['US', 'GB', 'CA', 'AU', 'IN', 'DE', 'FR', 'BR', 'MX', 'JP'] ``` -------------------------------- ### PyPI Trusted Publishing Workflow Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Configuration for PyPI Trusted Publishing using OpenID Connect (OIDC). This eliminates the need for stored tokens, requiring only a one-time trusted-publisher setup on PyPI. ```yaml publish.yml ``` -------------------------------- ### CLI: Pipe-safe JSON Output Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Examples of using the TrendspyG CLI to output JSON data that can be piped to other tools like `jq`. Demonstrates basic trend output and envelope output. ```bash trendspyg rss --geo US --output json --quiet | jq '.[0].trend' ``` ```bash trendspyg rss --geo US --output json --quiet --envelope | jq '.fetched_at, .count' ``` -------------------------------- ### Fetch Interest Over Time for a Keyword Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Get the interest over time for a specific keyword within a given region and timeframe. The result is a list of points with date, value, and partial status. ```python from trendspyg import download_google_trends_interest_over_time series = download_google_trends_interest_over_time("bitcoin", geo="US", timeframe="today 12-m") # series: list[InterestPoint] -> [{"date": ISO8601, "value": int 0-100, "is_partial": bool}, ...] ``` -------------------------------- ### Download Google Trends RSS with Normalization Source: https://github.com/flack0x/trendspyg/blob/main/README.md Use `download_google_trends_rss` with `normalize=True` to get a unified, JSON-native schema for RSS data. This is useful for agents and pipelines requiring a consistent data structure. The output includes schema version, source, geo, fetch time, count, and a list of trends. ```python from trendspyg import download_google_trends_rss env = download_google_trends_rss(geo='US', normalize=True) # {'schema_version': '1.0', 'source': 'rss', 'geo': 'US', # 'fetched_at': '2026-05-22T...Z', 'count': 10, 'trends': [...]} for t in env['trends']: print(t['rank'], t['keyword'], t['volume_min']) # volume_min is a real int ``` -------------------------------- ### Set up a Virtual Environment Source: https://github.com/flack0x/trendspyg/blob/main/SECURITY.md Create and activate a Python virtual environment to isolate project dependencies. This is a best practice for managing Python projects and their security. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install trendspyg ``` -------------------------------- ### Command Help Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Access detailed help for specific commands to understand all available options and parameters. ```bash trendspyg rss --help ``` ```bash trendspyg csv --help ``` -------------------------------- ### Run linting tools Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Check code quality and style using flake8 and mypy. ```bash flake8 trendspyg/ mypy trendspyg/ ``` -------------------------------- ### Get Normalized Google Trends RSS Data Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Use `normalize=True` to get a consistent JSON schema for RSS and CSV paths. This is recommended for agents as it simplifies data handling. ```python from trendspyg import download_google_trends_rss env = download_google_trends_rss(geo="US", normalize=True) # env: {"schema_version", "source", "geo", "fetched_at", "count", "trends": [...]} for t in env["trends"]: print(t["rank"], t["keyword"], t["volume_min"]) # volume_min is a real int ``` -------------------------------- ### Use Shared Async HTTP Sessions Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Illustrates how to use a shared aiohttp.ClientSession for multiple asynchronous requests to improve performance by reusing network connections. Requires importing aiohttp and asyncio. ```python import aiohttp async with aiohttp.ClientSession() as session: tasks = [ download_google_trends_rss_async(geo=c, session=session) for c in countries ] results = await asyncio.gather(*tasks) ``` -------------------------------- ### Run tests with coverage Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Execute tests and check code coverage for new code. Aim for over 80% coverage. ```bash pytest tests/ -v --cov=trendspyg ``` -------------------------------- ### Clear RSS Cache Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Use this function to remove all cached RSS data. No setup is required beyond importing the function. ```python from trendspyg import clear_rss_cache clear_rss_cache() # Clear all cached data ``` -------------------------------- ### Use Async for Batch Country Data Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Shows how to use asynchronous batch processing for downloading trend data from multiple countries, significantly reducing execution time compared to sequential requests. ```python # Sequential: ~5 seconds for 10 countries # Parallel: ~0.5 seconds for 10 countries results = await download_google_trends_rss_batch_async(countries) ``` -------------------------------- ### Push changes and create Pull Request Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Push your feature branch to origin and prepare to create a pull request. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Get RSS Cache Statistics Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Retrieve statistics about the current RSS cache, such as hit rate and size. This is useful for monitoring cache performance. ```python from trendspyg import get_rss_cache_stats stats = get_rss_cache_stats() print(f"Cache hit rate: {stats['hit_rate']}") ``` -------------------------------- ### Show trendspyg CLI help Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Display the help message for the trendspyg CLI to understand available commands and options. ```bash trendspyg --help ``` -------------------------------- ### Corrected API Documentation Values Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Correction of advertised sort values in API documentation. The actual values for sorting trends are 'volume' and 'recency', not 'traffic' or 'started'. ```markdown the advertised `sort` values (`traffic`/`started`) do not exist — the real values are `volume`/`recency` ``` -------------------------------- ### Import Standard TrendspyG Classes Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Import the core classes for working with standard trend data, news articles, and images. ```python from trendspyg import Trend, NewsArticle, TrendImage, TrendEnvelope from trendspyg import InterestPoint, RelatedQuery, RegionInterest, ExploreEnvelope ``` -------------------------------- ### Download Google Trends CSV Export Source: https://github.com/flack0x/trendspyg/blob/main/README.md Exports a comprehensive list of Google Trends data, with filtering options. This method requires Chrome to be installed and takes longer to execute. ```python from trendspyg import download_google_trends_csv # Get 480+ trends with filtering (requires Chrome) df = download_google_trends_csv( geo='US', hours=168, # Past 7 days category='sports', output_format='dataframe' ) ``` -------------------------------- ### Clone the repository Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Clone the trendspyg repository and navigate into the project directory. ```bash git clone https://github.com/flack0x/trendspyg.git cd trendspyg ``` -------------------------------- ### List available options Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Lists available countries, states, categories, or time periods supported by Trendspyg. Specify the type of list required using the `--type` option. ```bash # List all countries trendspyg list --type countries ``` ```bash # List US states trendspyg list --type states ``` ```bash # List categories trendspyg list --type categories ``` ```bash # List time periods trendspyg list --type hours ``` -------------------------------- ### Download Comprehensive Dataset Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Utilize the `csv` command to download a comprehensive dataset for a specified region and duration, outputting it as a pandas DataFrame. ```bash # Download comprehensive dataset trendspyg csv --geo US --hours 168 --output dataframe ``` -------------------------------- ### Download US trends via CSV Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Download comprehensive Google Trends data for the US using the CSV method. ```bash trendspyg csv --geo US ``` -------------------------------- ### download_google_trends_csv Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Downloads Google Trends data with extensive filtering options. Requires Chrome to be installed. The function can return data as a file path, pandas DataFrame, list of dictionaries, or a normalized envelope. ```APIDOC ## download_google_trends_csv ### Description Full-featured CSV download with filtering (requires Chrome). ### Method Python Function ### Parameters #### Function Parameters - **geo** (str) - Optional - Country or US state code. Defaults to 'US'. - **hours** (int) - Optional - Time period: 4, 24, 48, or 168 (7 days). Defaults to 24. - **category** (str) - Optional - Category filter (see Configuration). Defaults to 'all'. - **active_only** (bool) - Optional - Only show active/rising trends. Defaults to False. - **sort_by** (str) - Optional - Sort: 'relevance', 'title', 'volume', 'recency'. Defaults to 'relevance'. - **headless** (bool) - Optional - Run Chrome in headless mode. Defaults to True. - **download_dir** (str) - Optional - Download directory (default: ./downloads/). Defaults to None. - **output_format** (str) - Optional - Output: 'csv', 'json', 'parquet', 'dataframe', 'dict'. Defaults to 'csv'. - **normalize** (bool) - Optional - Return a unified `NormalizedEnvelope` (see [Normalized Output](#normalized-output)); `output_format` is ignored. Defaults to False. ### Returns - `str` - File path when `output_format` is 'csv', 'json', or 'parquet' - `pd.DataFrame` when `output_format='dataframe` - `List[Dict]` when `output_format='dict` - `Dict` (`NormalizedEnvelope`) when `normalize=True` ### Requires Chrome browser installed ### Example ```python from trendspyg import download_google_trends_csv # Basic usage csv_path = download_google_trends_csv(geo='US') # With filters df = download_google_trends_csv( geo='US-CA', hours=168, # 7 days category='sports', active_only=True, output_format='dataframe' ) ``` ``` -------------------------------- ### Real-time Trend Monitoring Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Use the `rss` command for a quick check of currently trending topics in a specific region without images or articles. ```bash # Quick check - what's trending now trendspyg rss --geo US --no-images --no-articles ``` -------------------------------- ### Use Caching for Trend Data Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Demonstrates how to leverage caching to speed up repeated calls for the same data. The first call performs a network request, while subsequent calls within the cache duration are instant. ```python # Results cached for 5 minutes by default trends = download_google_trends_rss(geo='US') # Network call trends = download_google_trends_rss(geo='US') # Instant (cached) ``` -------------------------------- ### Normalized Google Trends Output Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Demonstrates downloading Google Trends data with normalization enabled, providing a unified, agent-friendly schema. ```python from trendspyg import download_google_trends_rss env = download_google_trends_rss(geo='US', normalize=True) ``` -------------------------------- ### Basic Google Trends RSS Download Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Demonstrates the basic usage of downloading Google Trends RSS data for a specified region. ```python from trendspyg import download_google_trends_rss trends = download_google_trends_rss(geo='US') ``` -------------------------------- ### Run project tests Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Execute all project tests using pytest. ```bash pytest tests/ -v ``` -------------------------------- ### Pytest test structure for functionality and error handling Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Demonstrates how to structure tests using pytest, including testing basic functionality and error conditions with expected exceptions. ```python class TestFeature: """Test feature functionality""" def test_basic_functionality(self): """Test basic feature usage""" result = my_function() assert result is not None def test_error_handling(self): """Test error conditions""" with pytest.raises(InvalidParameterError): my_function(invalid_param) ``` -------------------------------- ### Update Security Documentation Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Refreshed security documentation including supported versions, updated dependency checking instructions, and honest statements about RSS XML trust. ```markdown pip-audit ``` -------------------------------- ### Create a new feature branch Source: https://github.com/flack0x/trendspyg/blob/main/CONTRIBUTING.md Use this command to create a new branch for your feature development. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Analyze keyword interest over time Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Analyze a keyword's interest over time, related queries, and regional interest using Google's Explore page. This command drives a real browser and is sensitive to rate limits. Options include specifying the keyword, geographic region, timeframe, category, and output format. The `--full` flag outputs the complete envelope, and `--quiet` suppresses banners for pipe-safe output. ```bash # Interest over time as JSON trendspyg explore --keyword bitcoin ``` ```bash # Past 5 years, as CSV trendspyg explore -k "taylor swift" --timeframe "today 5-y" --output csv ``` ```bash # Full envelope (interest + related + regions), pipe-clean for jq trendspyg explore -k bitcoin --full --quiet | jq '.related_queries.rising[0]' ``` -------------------------------- ### Asynchronous Google Trends RSS Download Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Shows how to download Google Trends RSS data asynchronously for parallel fetching. ```python from trendspyg import download_google_trends_rss_async trends = await download_google_trends_rss_async(geo='US') ``` -------------------------------- ### Batch Google Trends RSS Download with Progress Bar Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Illustrates downloading Google Trends RSS data in batches for multiple countries, including a progress bar. ```python from trendspyg import download_google_trends_rss_batch results = download_google_trends_rss_batch(['US', 'GB', 'CA']) ``` -------------------------------- ### Fetch Many Regions in Parallel (Async) Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Asynchronously fetch trends for multiple regions concurrently. Specify `max_concurrent` to control the number of simultaneous requests. Use `normalize=True` for a unified envelope. ```python import asyncio from trendspyg import download_google_trends_rss_batch_async results = asyncio.run( download_google_trends_rss_batch_async( ["US", "GB", "DE", "JP"], max_concurrent=5, normalize=True ) ) # results: dict[str, NormalizedEnvelope] (geo -> envelope) # drop normalize=True to get dict[str, list[Trend]] instead ``` -------------------------------- ### Download Google Trends RSS Batch Async Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md The fastest method for fetching multiple countries' trends asynchronously. It supports limiting the number of concurrent requests to prevent rate limiting issues. ```python async def download_google_trends_rss_batch_async( geos: List[str], include_images: bool = True, include_articles: bool = True, max_articles_per_trend: int = 5, show_progress: bool = True, max_concurrent: int = 10, normalize: bool = False ) -> Dict[str, Union[List[Dict], Dict]] ``` ```python import asyncio from trendspyg import download_google_trends_rss_batch_async async def main(): results = await download_google_trends_rss_batch_async( ['US', 'GB', 'CA', 'AU', 'DE', 'FR', 'JP'], max_concurrent=5 # Limit to avoid rate limits ) return results all_trends = asyncio.run(main()) ``` -------------------------------- ### download_google_trends_explore Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Fetches the complete Google Trends Explore data for a keyword in a single browser load, including interest over time, related queries, and interest by region. This function also drives a real Chrome browser and may incur delays. ```APIDOC ## download_google_trends_explore ### Description The full Explore picture for a keyword in a single browser load. ### Method Signature ```python download_google_trends_explore( keyword: str, geo: str = 'US', timeframe: str = 'today 12-m', category: int = 0, headless: bool = True, include_related: bool = True, include_geo: bool = True, ) -> Dict[str, Any] # ExploreEnvelope ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `keyword` | `str` | *(required)* | Search term to analyze. | | `geo` | `str` | `'US'` | Country/region code. | | `timeframe` | `str` | `'today 12-m'` | Date range. | | `category` | `int` | `0` | Google Trends category id. | | `headless` | `bool` | `True` | Run Chrome headless. | | `include_related` | `bool` | `True` | Whether to include related queries. | | `include_geo` | `bool` | `True` | Whether to include interest by region. | ### Returns An `ExploreEnvelope` dictionary: ```json { "schema_version": "1.0", "source": "explore", "keyword": "bitcoin", "geo": "US", "timeframe": "today 12-m", "fetched_at": "2026-06-06T...+00:00", "count": 53, # number of interest_over_time points "interest_over_time": [ {"date", "value", "is_partial"}, ... ], "related_queries": { "top": [ {"query", "value", "formatted_value", "link"}, ... ], "rising": [ {"query", "value", "formatted_value", "link"}, ... ], # formatted_value e.g. "+3,650%", "Breakout" }, "interest_by_region": [ {"geo_code", "geo_name", "value"}, ... ], # sorted strongest first } ``` `related_queries` / `interest_by_region` are empty lists when not requested (`include_related=False` / `include_geo=False`) or when Google did not return them — the `interest_over_time` series is the guaranteed payload. The envelope is JSON-safe throughout, so no `normalize` pass is needed. ### Request Example ```python from trendspyg import download_google_trends_explore env = download_google_trends_explore("taylor swift", geo="US") for q in env["related_queries"]["rising"][:5]: print(q["query"], q["formatted_value"]) ``` ``` -------------------------------- ### CLI: Watch Google Trends for Changes Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md The CLI equivalent of `watch_google_trends_rss` streams one NDJSON change per line, useful for monitoring trends continuously. ```bash trendspyg watch ``` -------------------------------- ### Download Google Trends RSS Async Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Use this asynchronous function for parallel fetching of Google Trends data, offering significant speed improvements for batch operations. It requires an `aiohttp.ClientSession` for connection pooling when making multiple requests. ```python async def download_google_trends_rss_async( geo: str = 'US', output_format: Literal['dict', 'dataframe', 'json', 'csv'] = 'dict', include_images: bool = True, include_articles: bool = True, max_articles_per_trend: int = 5, session: Optional[aiohttp.ClientSession] = None, cache: bool = True, normalize: bool = False ) -> Union[List[Dict], str, pd.DataFrame, Dict] ``` ```python import asyncio from trendspyg import download_google_trends_rss_async # Single country async def main(): trends = await download_google_trends_rss_async(geo='US') print(f"Got {len(trends)} trends") asyncio.run(main()) # Multiple countries in parallel async def fetch_all(): countries = ['US', 'GB', 'CA', 'AU'] tasks = [download_google_trends_rss_async(geo=c) for c in countries] results = await asyncio.gather(*tasks) return dict(zip(countries, results)) all_trends = asyncio.run(fetch_all()) ``` -------------------------------- ### Export Schema Version Constants Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Exported schema version constants for detecting shape drift in agent integrations. Includes versions for general monitoring, explore, and RSS feeds. ```python SCHEMA_VERSION ``` ```python EXPLORE_SCHEMA_VERSION ``` ```python MONITOR_SCHEMA_VERSION ``` -------------------------------- ### Configuring Concurrent Calls and Delays Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md When batching a large number of regions (50+), configure `max_concurrent` to limit simultaneous calls and optionally set a `delay` between calls to respect rate limits. ```python import trendspyg trendspyg.get_historical_data( regions=["US", "GB", "DE", ...], # 50+ regions max_concurrent=5, # Limit to 5 concurrent calls delay=0.5 # Optional: 0.5 second delay between calls ) ``` -------------------------------- ### Trendspyg CLI: List Countries Source: https://github.com/flack0x/trendspyg/blob/main/README.md Command-line interface command to list available countries for Trendspyg operations. ```bash trendspyg list --type countries ``` -------------------------------- ### Compare Trend Snapshots Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Provides functions to compare trend data and filter changes. `diff_trends` performs a pure comparison, `filter_changes` applies specific criteria, and `post_webhook` sends changes to a specified URL. ```python diff_trends(old, new) -> list[TrendChange] # pure, no network filter_changes(changes, *, min_volume=None, events=None, keywords=None) -> list[TrendChange] post_webhook(url, change, timeout=10.0) -> bool # 2xx -> True; never raises ``` -------------------------------- ### download_google_trends_rss_async Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Asynchronously downloads Google Trends data with an option for normalized JSON output. When normalize=True, the output conforms to the NormalizedEnvelope schema. ```APIDOC ## download_google_trends_rss_async ### Description Asynchronously downloads Google Trends data. Setting `normalize=True` returns a `NormalizedEnvelope` JSON object. ### Method Python async function call ### Parameters #### Path Parameters None #### Query Parameters - **geo** (str) - Required - The geographic region for the trends (e.g., 'US'). - **normalize** (bool) - Optional - If True, returns data in `NormalizedEnvelope` format. Defaults to False. ### Request Example ```python import asyncio from trendspyg import download_google_trends_rss_async async def main(): env = await download_google_trends_rss_async(geo='US', normalize=True) asyncio.run(main()) ``` ### Response #### Success Response - **NormalizedEnvelope** (dict) - A JSON-native schema identical across data paths when `normalize=True`. #### Response Example (NormalizedEnvelope) ```json { "schema_version": "1.0", "source": "rss", "geo": "US", "fetched_at": "2026-05-22T01:00:00+00:00", "count": 10, "trends": [ ... ] } ``` ### NormalizedTrend Structure | Field | Type | Description | |-------|------|-------------| | `keyword` | `str` | Search term, verbatim from the source | | `rank` | `int` | 1-based position in source ordering | | `volume_text` | `str` | Raw human-readable volume, e.g. `'5M+'` | | `volume_min` | `int` | Parsed lower bound of `volume_text` | | `started_at` | `str | None` | ISO 8601 start time | | `ended_at` | `str | None` | ISO 8601 end time (`None` if still active) | | `is_active` | `bool` | `True` when `ended_at` is `None` | | `related_queries` | `list[str]` | Related searches (CSV path); `[]` for RSS | | `news` | `list` | News articles (RSS path); `[]` for CSV | | `image` | `obj | None` | Trend image | | `explore_url` | `str` | Google Trends Explore URL | ``` -------------------------------- ### Configure Browser for Trend Scraping Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Configuration settings for browser-based scraping to avoid detection. This includes disabling automation flags and setting the UI language. ```python disable AutomationControlled / useAutomationExtension ``` ```python &hl=en-US ``` -------------------------------- ### Download Google Trends Interest Over Time Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Fetches the relative interest time series for a search term from Google Trends. Supports various output formats. ```python download_google_trends_interest_over_time(keyword, geo='US', timeframe='today 12-m', ...) ``` -------------------------------- ### Interest Over Time for a Keyword Source: https://github.com/flack0x/trendspyg/blob/main/examples/README.md Fetches the interest over time for a specific keyword in a given region and timeframe. Requires Chrome browser. ```python from trendspyg import download_google_trends_interest_over_time series = download_google_trends_interest_over_time('bitcoin', geo='US', timeframe='today 12-m') ``` -------------------------------- ### Handle Browser Errors in Explore Path Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Distinguishes between a throttle and a changed page in the Explore path. Raises a clear BrowserError for UI changes instead of a misleading RateLimitError. ```python BrowserError("the Explore UI may have changed") ``` -------------------------------- ### List Available Categories Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Displays the list of available categories for trend analysis. These include 'all', 'sports', 'entertainment', and more. ```python from trendspyg.config import CATEGORIES # Available categories: # 'all', 'sports', 'entertainment', 'business', 'politics', # 'technology', 'health', 'science', 'games', 'shopping', # 'food', 'travel', 'beauty', 'hobbies', 'climate', # 'jobs', 'law', 'pets', 'autos', 'other' ``` -------------------------------- ### Dependabot Configuration Source: https://github.com/flack0x/trendspyg/blob/main/CHANGELOG.md Configuration for Dependabot to automatically manage dependencies for pip and GitHub Actions. Includes merging initial batches of CI action bumps. ```yaml Dependabot (pip + GitHub Actions) ``` -------------------------------- ### Trendspyg CLI: Explore Data Source: https://github.com/flack0x/trendspyg/blob/main/README.md Command-line interface command to explore Google Trends data for a keyword, with an option to output as CSV. ```bash trendspyg explore --keyword bitcoin --output csv ``` -------------------------------- ### Download Google Trends Interest Over Time Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Fetches the relative interest time series for a single search term from Google Trends. Specify country, timeframe, category, and output format. Requires Chrome. ```python download_google_trends_interest_over_time( keyword: str, geo: str = 'US', timeframe: str = 'today 12-m', category: int = 0, headless: bool = True, output_format: str = 'dict', ) -> Union[List[Dict], str, pd.DataFrame] ``` ```python [ {"date": "2025-06-01T00:00:00+00:00", "value": 27, "is_partial": False}, ... {"date": "2026-05-31T00:00:00+00:00", "value": 35, "is_partial": True}, ] ``` ```python from trendspyg import download_google_trends_interest_over_time series = download_google_trends_interest_over_time("bitcoin", geo="US", timeframe="today 5-y") peak = max(series, key=lambda p: p["value"]) print(peak["date"], peak["value"]) ``` -------------------------------- ### Import Normalized TrendspyG Classes Source: https://github.com/flack0x/trendspyg/blob/main/AGENTS.md Import the classes specifically for handling normalized trend data, which ensures all fields are present and JSON-safe. ```python from trendspyg import NormalizedEnvelope, NormalizedTrend ``` -------------------------------- ### download_google_trends_rss_batch_async Source: https://github.com/flack0x/trendspyg/blob/main/docs/API.md Asynchronously downloads Google Trends RSS data for multiple locations in batches, offering the fastest option for multiple countries. ```APIDOC ## download_google_trends_rss_batch_async ### Description Async batch fetching - fastest option for multiple countries. ### Method Signature ```python async def download_google_trends_rss_batch_async( geos: List[str], include_images: bool = True, include_articles: bool = True, max_articles_per_trend: int = 5, show_progress: bool = True, max_concurrent: int = 10, normalize: bool = False ) -> Dict[str, Union[List[Dict], Dict]] ``` ### Parameters #### Path Parameters None #### Query Parameters - **geos** (List[str]) - Required - List of geo codes to fetch. - **include_images** (bool) - Optional - Whether to include images (default: True). - **include_articles** (bool) - Optional - Whether to include articles (default: True). - **max_articles_per_trend** (int) - Optional - Maximum number of articles per trend (default: 5). - **show_progress** (bool) - Optional - Show tqdm progress bar (default: True). - **max_concurrent** (int) - Optional - Maximum concurrent requests (default: 10). - **normalize** (bool) - Optional - If True, each geo maps to a `NormalizedEnvelope` instead of a trend list (default: False). #### Request Body None ### Returns `Dict[str, Union[List[Dict], Dict]]` - Dictionary mapping geo codes to trends (or geo to `NormalizedEnvelope` when `normalize=True`). ### Request Example ```python import asyncio from trendspyg import download_google_trends_rss_batch_async async def main(): results = await download_google_trends_rss_batch_async( ['US', 'GB', 'CA', 'AU', 'DE', 'FR', 'JP'], max_concurrent=5 # Limit to avoid rate limits ) return results all_trends = asyncio.run(main()) ``` ``` -------------------------------- ### Multiple Country Trend Data Source: https://github.com/flack0x/trendspyg/blob/main/CLI.md Collect trend data for multiple countries, outputting each as a JSON file for further processing. ```bash # US trends trendspyg csv --geo US --output json > us_trends.json ``` ```bash # UK trends trendspyg csv --geo GB --output json > gb_trends.json ``` ```bash # Japan trends trendspyg csv --geo JP --output json > jp_trends.json ```