Stockdex

repository·main·Indexed 42 days ago

https://github.com/ahnazary/stockdex

A Python library for extracting financial data from sources including Yahoo Finance, Finviz, Digrin, Macrotrends, and JustETF. It converts financial metrics and historical data into pandas DataFrames and interactive Plotly figures, with built-in support for creating multi-plot Dash dashboards.

Tokens
14.4K
Snippets
92
Records
99
Agent score
53%

What's inside Stockdex

  1. Overview of Stockdex capabilities

    main

    Stockdex is a Python package designed to provide a simple interface for retrieving financial data. It returns data in two primary formats:

    1. pandas DataFrames: For data manipulation and analysis.
    2. Plotly figures: For interactive data visualization.

    Key features include:

    • Multi-source support: Access data from Yahoo Finance, Digrin, Finviz, Macrotrends, and JustETF (for EU ETFs).
    • Extensive historical data: Access long-term historical datasets via Digrin and Macrotrends.
    • Diverse data categories: Retrieve financial statements, earnings, dividends, stock splits, key executives, and major shareholders.
    • Visualization: Support for bar, line, and Sankey plots, with the ability to combine multiple plots into an interactive Dash application.
  2. Retrieve historical stock data via Digrin

    main

    Stockdex provides access to Digrin's data, which includes comprehensive historical stock data across various categories. This is an alternative to Yahoo Finance, which is typically limited to the last 5 years or 4 quarters of data.

    Important Considerations:

    • Data Cleaning: Some Digrin dataframes may require manual cleaning. The API payload can sometimes include hidden data like trailing spaces or characters. For example, the Date field in digrin_payout_ratio may contain trailing spaces that prevent direct conversion to pandas datetime objects.
    • DataFrame Size: While documentation examples show only the first 5 rows, the actual returned DataFrames may contain significantly more data.
  3. Identify and use Stockdex data sources

    main

    Stockdex allows you to extract financial data as pandas DataFrames from multiple providers. To identify which provider a specific function uses, look for the source prefix in the function name.

    Common prefixes include:

    • yahoo_api_<function_name>: Retrieves data from the Yahoo Finance API.
    • yahoo_web_<function_name>: Retrieves data via web scraping from Yahoo Finance.
    • finviz_<function_name>: Retrieves data from Finviz.
    • digrin_<function_name>: Retrieves data from Digrin.
    • macrotrends_<function_name>: Retrieves data from Macrotrends.
    • jsutetf_<function_name>: Retrieves data from Jsujetf.
  4. Build Dash dashboards with multiple plots

    main

    You can create a multi-plot dashboard using the dash library by combining stockdex plotting functions with stockdex.lib.plot_multiple_categories.

    Crucial Requirement: When calling any function with the plot_ prefix, you must set show_plot=False. This ensures the function returns a Plotly figure object instead of attempting to render the plot immediately in a separate browser tab. If you do not set this, your dashboard will not function correctly as the plots will be displayed in separate tabs instead of being passed to the dashboard builder.

    To build the dashboard:

    1. Initialize a Ticker object.
    2. Generate a list of Plotly figures by calling various plot_ methods on the ticker instance with show_plot=False.
    3. Pass the ticker symbol and the list of figures to plot_multiple_categories().

    The dashboard is served by default at http://127.0.0.1:8050/.

    from stockdex.ticker import Ticker
    from stockdex.lib import plot_multiple_categories
    
    ticker = Ticker(ticker="MSFT")
    
    # Generate figures with show_plot=False to return Plotly objects
    figures = [
        ticker.plot_digrin_shares_outstanding(show_plot=False),
        ticker.plot_digrin_price(show_plot=False),
        ticker.plot_digrin_dividend(show_plot=False),
        ticker.plot_digrin_assets_vs_liabilities(show_plot=False),
        ticker.plot_digrin_free_cash_flow(show_plot=False),
        ticker.plot_digrin_net_income(show_plot=False),
        ticker.plot_digrin_cash_and_debt(show_plot=False),
        ticker.plot_digrin_expenses(show_plot=False),
        ticker.plot_digrin_cost_of_revenue(show_plot=False),
    ]
    
    # Create the Dash app
    plot_multiple_categories(ticker=ticker.ticker, figures=figures)
  5. Plot extracted data using Plotly figures

    main

    Stockdex provides built-in plotting capabilities for various data sources. Each data source implements functions following the naming convention plot_<data_source>_<function_name>. These functions generate interactive Plotly figures.

    To control whether the plot is displayed immediately upon calling the function, use the show_plot parameter:

    • show_plot=True (default): Displays the plot immediately.
    • show_plot=False: Returns the Plotly figure object instead of displaying it, allowing you to manipulate the figure or embed it in other applications (like Dash) before showing it.
    # Example pattern (actual function names depend on the data source)
    # figure = extractor.plot_<data_source>_<function_name>(show_plot=False)
    # figure.show()
  6. Verify installation with a simple Ticker test

    main

    To verify that stockdex is installed correctly, you can instantiate a Ticker object and attempt to fetch data from the Yahoo Finance API (e.g., an income statement).

    from stockdex import Ticker
    
    ticker = Ticker(ticker="NVDA")
    result = ticker.yahoo_api_income_statement(frequency='quarterly')
  7. Plot a Sankey chart for a stock

    main

    You can visualize a company's cash flow using the plot_sankey_chart() method on a Ticker instance. This function generates a Sankey chart based on income statement data extracted from the Yahoo Finance API. The resulting chart allows you to hover over different segments to see the specific amount of cash in each category.

    To use it, instantiate a Ticker with the desired symbol and call the method.

    from stockdex import Ticker
    
    ticker = Ticker(ticker="AAPL")
    
    ticker.plot_sankey_chart()
  8. Retrieve revenue by regions via `finviz_revenue_by_regions()`

    main

    Use finviz_revenue_by_regions() to get a revenue breakdown by geographic regions over fiscal years.

    Returns a dictionary where:

    • Key: The region name (e.g., China, United States).
    • Value: A dictionary containing two lists: fiscal_year and value.
    from stockdex import Ticker 
    
    ticker = Ticker(ticker="AAPL")
    result = ticker.finviz_revenue_by_regions()
  9. Retrieve historical price data with `yahoo_api_price`

    main

    Use the yahoo_api_price method on a Ticker instance to extract historical price data from the Yahoo Finance API. The method returns a pandas DataFrame containing columns such as timestamp, volume, close, open, high, low, currency, timezone, exchangeTimezoneName, exchangeName, and instrumentType.

    Parameters

    • range: The time period for historical data.
      • Options: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max.
    • dataGranularity: The frequency of the data points.
      • Options: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo.
    from stockdex import Ticker 
    
    ticker = Ticker(ticker="AMZN")
    result = ticker.yahoo_api_price(range='1y', dataGranularity='1d')