### Example Router Function Setup Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/extension_types/provider.md This Python code demonstrates the necessary imports and setup for defining a router extension in OpenBB. It includes common models and classes required for command context, examples, query objects, and provider interfaces. ```python from openbb_core.app.model.command_context import CommandContext from openbb_core.app.model.example import APIEx, PythonEx from openbb_core.app.model.obbject import OBBject from openbb_core.app.provider_interface import ( ExtraParams, ProviderChoices, StandardParams, ) from openbb_core.app.query import Query from openbb_core.app.router import Router router = Router(prefix="", description="An Empty OpenBB Router Extension.") ``` -------------------------------- ### Uvicorn Server Output Example Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/data-integration.md Example output indicating that the Uvicorn server has started successfully and is running. ```bash $ uvicorn main:app --reload --host 0.0.0.0 --port 7779 INFO: Uvicorn running on http://0.0.0.0:7779 (Press CTRL+C to quit) INFO: Started reloader process [59166] using WatchFiles INFO: Started server process [59168] INFO: Waiting for application startup. INFO: Application startup complete. ``` -------------------------------- ### Execute Example Routine Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/cli/quickstart.md Run a predefined example routine using the `--example` flag with the `exe` command. This is useful for demonstrating or testing a sequence of operations. ```console /exe --example ``` -------------------------------- ### Install openbb-platform-api Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/quickstart/workspace.mdx Install the openbb-api package as a standalone executable for starting FastAPI applications. ```sh pip install openbb-platform-api ``` -------------------------------- ### Install All Toolkits and Data Providers Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/faqs/data_providers.mdx Install all toolkits and data providers with this command. ```bash pip install "openbb[all]" ``` -------------------------------- ### Install OpenBB Platform from Source Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/cli/installation.md Execute the development installation script to install the OpenBB Platform CLI from its source code. Ensure you are in the `~/OpenBB/openbb_platform` directory. ```bash python dev_install.py -e --cli ``` -------------------------------- ### Install openbb-charting Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/infrastructure/openbb-charting/index.md Install the core charting extension. ```bash pip install openbb-charting ``` -------------------------------- ### Install All Third-Party Providers Source: https://context7.com/openbb-finance/openbb-docs/llms.txt Install all available third-party data provider extensions at once using the `[all]` extra with pip. This command simplifies the installation of multiple providers. ```bash # Install all third-party providers at once pip install "openbb[all]" ``` -------------------------------- ### Install OpenBB Platform and Build Assets Source: https://context7.com/openbb-finance/openbb-docs/llms.txt Install the OpenBB platform via pip, build static assets for the Python interface, deploy using Docker, or install from source for development. ```bash pip install openbb openbb-build docker build -f build/docker/platformAPI.Dockerfile -t openbb-platform:latest . docker run -it --rm -p 6900:6900 -v ~/.openbb_platform:/root/.openbb_platform openbb-platform:latest git clone git@github.com:OpenBB-finance/OpenBB.git cd openbb_platform pip install poetry python dev_install.py -e ``` -------------------------------- ### Import Example Models Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/how-to/examples.mdx Import the necessary models for defining examples. ```python from openbb_core.app.model.example import APIEx, PythonEx ``` -------------------------------- ### Install Dependencies Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/data-integration.md Install the necessary Python libraries for creating the API server. ```bash pip install fastapi uvicorn ``` -------------------------------- ### Install openbb-core Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/openbb-core.mdx Install openbb-core as a standalone package from PyPI. ```sh pip install openbb-core ``` -------------------------------- ### Install the generated extension locally Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/extension_types/index.md After navigating into the generated project folder, install the extension in editable mode using `pip install -e .`. This allows for development and testing of the extension. ```bash pip install -e . ``` -------------------------------- ### Install OpenBB AI SDK Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/openbb-ai-sdk.md Install the openbb-ai package in your agent backend using pip. ```bash pip install openbb-ai ``` -------------------------------- ### Install All Toolkits and Data Providers from GitHub Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/faqs/data_providers.mdx Install all toolkits and data providers by cloning the GitHub repo, from the /openbb_platform/ folder. ```bash python dev_install.py -e ``` -------------------------------- ### Start All OpenBB Services in Snowflake Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/snowflake/index.md Manually start all OpenBB services using a Snowflake procedure. This is typically not needed as services start automatically on installation or upgrade. ```sql -- Start all services (usually not needed - automatic on install/upgrade) CALL .core.start_openbb_service(); ``` -------------------------------- ### Launch OpenBB API Backend Source: https://context7.com/openbb-finance/openbb-docs/llms.txt Command-line instructions for installing and launching the OpenBB API backend, including options for custom apps, host/port configuration, and editable widgets. ```bash # Install standalone pip install openbb-platform-api # Launch with all installed ODP extensions as widgets (default: http://127.0.0.1:6900) openbb-api # Launch a custom FastAPI app openbb-api --app ./some_file.py --host 0.0.0.0 --port 8005 --reload # Factory function openbb-api --app some_file.py:main --factory # Editable widgets.json (live-edit during runtime) openbb-api --editable --build # Exclude specific API paths from widget generation openbb-api --exclude '["/api/v1/*"]' ``` -------------------------------- ### Start MCP Server with Tool Discovery Disabled Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-mcp.mdx Starts the OpenBB MCP server with tool discovery disabled, which is useful for multi-client setups. ```bash openbb-mcp --no-tool-discovery ``` -------------------------------- ### Launching OpenBB API Backend Source: https://context7.com/openbb-finance/openbb-docs/llms.txt Instructions on how to install and launch the OpenBB API backend server, including options for custom configurations and app integration. ```APIDOC ## OpenBB API (`openbb-api`) — Workspace Backend Launcher **Convert any FastAPI app into an OpenBB Workspace backend with auto-generated widget definitions** ```bash # Install standalone pip install openbb-platform-api # Launch with all installed ODP extensions as widgets (default: http://127.0.0.1:6900) openbb-api # Launch a custom FastAPI app openbb-api --app ./some_file.py --host 0.0.0.0 --port 8005 --reload # Factory function openbb-api --app some_file.py:main --factory # Editable widgets.json (live-edit during runtime) openbb-api --editable --build # Exclude specific API paths from widget generation openbb-api --exclude '["/api/v1/*"]' ``` ``` -------------------------------- ### Define a GET Endpoint with FastAPI Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/extension_types/router.md Use the `_api_router.get` decorator to define a GET endpoint. This example shows how to create an endpoint that accepts a string parameter and returns a string. ```python from fastapi import APIRouter router = APIRouter() @router._api_router.get("/also_empty") async def also_empty(param: str) -> str: """Also Emmpty""" return "Hello world!" ``` -------------------------------- ### Basic GET Endpoint Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/extension_types/router.md This example shows a basic GET endpoint where all business logic is contained within the function itself. The endpoint's path is derived from the function name. ```APIDOC ## Basic GET Endpoint ### Description A standard router "get" command where business logic is self-contained. ### Method GET ### Endpoint The endpoint path is the name of the function. ### Parameters None explicitly defined as path or query parameters in this example. ### Request Body Not applicable for GET requests. ### Request Example ```python # Example usage within Python # Assuming 'obb' is an initialized OpenBB client # result = obb.empty_router.hello() ``` ### Response #### Success Response (200) - **OBBject[str]** - An OBBject containing a string result. #### Response Example ```json { "results": "Hello from the Empty Router extension!" } ``` ``` -------------------------------- ### Using the OBBject Extension Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/extension_types/obbject.md Demonstrates how to call the custom 'hello' method from the installed OBBject extension after retrieving an OBBject. ```console >>> from openbb import obb >>> output = obb.empty.hello() >>> output OBBject id: 068ee9a9-7853-7176-8000-567f982f83ad results: Hello from the Empty Router extension! provider: None warnings: None chart: None extra: {'metadata': {'arguments': {'provider_choices': {}, 'standard_params': {}, '... >>> output.empty.hello() Hello from the Empty OBBject extension! OBBject Results: Hello from the Empty Router extension! ``` -------------------------------- ### Start MCP Server Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/quickstart/mcp.mdx Start the MCP server using the command-line executable. This will launch the server on http://127.0.0.1:8001 using the streamable-http transport, making all GET endpoints available as MCP tools. ```sh openbb-mcp ``` -------------------------------- ### Advanced MCP Configuration Example Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-mcp.mdx This Python example demonstrates how to use `openapi_extra` to configure MCP settings for a FastAPI route. It explicitly exposes the route as a 'tool' for 'GET' requests only and excludes an internal parameter from the tool's interface. ```python @app.get( "/some/route", openapi_extra={ "mcp_config": { "expose": True, "mcp_type": "tool", "methods": ["GET"], "exclude_args": ["internal_param"], "prompts": [ # ... prompt definitions ... ] } }, ) def some_route(param1: str, internal_param: str = "default"): """An example route with advanced MCP configuration.""" return {"param1": param1} ``` -------------------------------- ### Table Widget from API Endpoint Source: https://github.com/openbb-finance/openbb-docs/blob/main/static/workspace/llms-full.txt Fetches and displays data from an external API. This example integrates with the DeFi Llama API to show chain TVL data. Ensure the 'requests' library is installed. ```python @register_widget({ "name": "Table Widget from API Endpoint", "description": "A table widget from an API endpoint", "type": "table", "endpoint": "table_widget_from_api_endpoint", "gridData": {"w": 12, "h": 4}, }) @app.get("/table_widget_from_api_endpoint") def table_widget_from_api_endpoint(): """Get current TVL of all chains using Defi LLama""" response = requests.get("https://api.llama.fi/v2/chains") if response.status_code == 200: return response.json() print(f"Request error {response.status_code}: {response.text}") raise HTTPException( status_code=response.status_code, detail=response.text ) ``` -------------------------------- ### Launch Any FastAPI App with OpenBB API Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/quickstart/workspace.mdx Launch the OpenBB API server with any FastAPI application. Ensure Python version is between 3.9 and 3.12 and the 'openbb-platform-api' package is installed. Only 'GET' methods are currently supported. ```sh openbb-api --app /Users/path/to/some/folder/some_file.py ``` -------------------------------- ### Example User Settings JSON Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/settings/user_settings/preferences.mdx This JSON structure shows an example of how user settings, including credentials, preferences, and command defaults, might be configured. ```json { "credentials": { "fmp_api_key": "REPLACE", "polygon_api_key": "REPLACE", }, "preferences": { "data_directory": "~/OpenBBUserData", "export_directory": "~/OpenBBUserData/exports", "metadata": true, "output_type": "OBBject" }, "defaults": { "commands": { "/equity/price/historical": { "provider": "fmp" }, "/equity/fundamental/balance": { "provider": [ "intrinio", "fmp", "polygon" ] }, } } } ``` -------------------------------- ### Define Inline Prompts for GDP Endpoint Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-mcp.mdx Add prompts to an endpoint's `openapi_extra` dictionary to guide LLM usage. This example defines prompts for GDP summary and comparison, including arguments and tags. ```python @app.get( "/economy/gdp", openapi_extra={ "mcp_config": { "prompts": [ { "name": "gdp_summary_prompt", "description": "Generate a brief summary of GDP for a country.", "content": "Provide a concise summary of the GDP for {country} over the last {years} years.", "arguments": [ { "name": "years", "type": "int", "default": 5, "description": "Number of years to summarize.", } ], "tags": ["economy", "gdp", "summary"], }, { "name": "gdp_comparison_prompt", "description": "Compare the GDP of two countries.", "content": "Compare the GDP growth of {country1} and {country2}.", "arguments": [ { "name": "country1", "type": "str", "description": "First country for comparison.", }, { "name": "country2", "type": "str", "description": "Second country for comparison.", }, ], "tags": ["economy", "gdp", "comparison"], }, ] } }, ) def get_gdp_data(country: str, period: Literal["annual", "quarterly"] = "annual"): """Get GDP data for a specific country.""" return {"country": country, "period": period} ``` -------------------------------- ### General Intake Form Submission and Retrieval Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-api.mdx This snippet demonstrates how to set up a POST endpoint for form submissions and a GET endpoint to retrieve submitted data. It includes the Pydantic models for request and response data, and the FastAPI application setup. ```APIDOC ## POST /general_intake_submit ### Description Submits general intake form data. Expects a JSON payload conforming to the `GeneralIntake` model and returns a boolean indicating success. ### Method POST ### Endpoint /general_intake_submit ### Parameters #### Request Body - **data** (GeneralIntake) - Required - The intake form data. ### Request Example ```json { "date_created": "2023-10-27", "first_name": "John", "last_name": "Doe", "email": "john.doe@example.com", "dob": "1990-01-01", "account_types": ["General Fund", "Private Equity"] } ``` ### Response #### Success Response (200) - **Success** (boolean) - True if the submission was successful. #### Response Example ```json true ``` ## GET /general_intake ### Description Retrieves a list of all submitted general intake forms. This endpoint is configured to work with a form widget. ### Method GET ### Endpoint /general_intake ### Parameters None ### Response #### Success Response (200) - **Submissions** (list[IntakeForm]) - A list of submitted intake forms. #### Response Example ```json [ { "contacted": false, "date_created": "2023-10-27", "first_name": "John", "last_name": "Doe", "email": "john.doe@example.com", "dob": "1990-01-01", "account_types": ["General Fund", "Private Equity"], "unique_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ] ``` ``` -------------------------------- ### Example Server Prompt Definition Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-mcp.mdx This JSON structure defines a server prompt named 'equity_analysis'. It includes a description, the content of the prompt with placeholders for arguments, a list of arguments with their types and descriptions, and associated tags. This prompt is designed to guide the LLM through a comprehensive equity analysis workflow. ```json [ { "name": "equity_analysis", "description": "Perform a comprehensive equity analysis using multiple data sources and metrics", "content": "Conduct a comprehensive analysis of {symbol} for {analysis_period}. Follow this workflow:\n1. First, get basic stock quote and recent price performance using equity_price_performance.\n2. Retrieve fundamental data including financial statements, ratios, and key metrics using [equity_fundamental_ratios, equity_fundamental_metrics, quity_fundamental_balance].\n3. Gather recent news and analyst estimates for the company using [news_company, equity_estiments_price_target].\n4. Compare valuation metrics with industry peers using equity_compare_peers.\n5. Summarize findings with investment recommendation.\n\nFocus areas: {focus_areas}\nRisk tolerance: {risk_tolerance}", "arguments": [ { "name": "symbol", "type": "str", "description": "Stock ticker symbol to analyze (e.g., AAPL, TSLA)" }, { "name": "analysis_period", "type": "str", "default": "last 12 months", "description": "Time period for the analysis" }, { "name": "focus_areas", "type": "str", "default": "growth, profitability, valuation", "description": "Specific areas to focus on in the analysis" }, { "name": "risk_tolerance", "type": "str", "default": "moderate", "description": "Risk tolerance level: conservative, moderate, or aggressive" } ], "tags": ["equity", "analysis", "comprehensive"] } ] ``` -------------------------------- ### Install and Launch MCP Server Source: https://context7.com/openbb-finance/openbb-docs/llms.txt Command-line instructions for installing and launching the MCP Server, with options for specifying tool categories, transport protocols, and network settings. ```bash # Install pip install openbb-mcp-server # Start with default settings (http://127.0.0.1:8001, streamable-http transport) openbb-mcp # Start with specific tool categories openbb-mcp --default-categories equity,news # Start with SSE transport (required for some clients) openbb-mcp --transport sse # Restrict allowed categories and set custom host/port openbb-mcp --allowed-categories equity,crypto,news --host 0.0.0.0 --port 8080 # Disable dynamic tool discovery (for multi-client/fixed-toolset deployments) openbb-mcp --no-tool-discovery ``` -------------------------------- ### Python FastAPI App with Form Widget Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/interface/openbb-api.mdx This snippet demonstrates a FastAPI application setup for a form widget. It includes Pydantic models for form input and submission records, a POST endpoint to handle form submissions, and a GET endpoint to retrieve all submitted forms. Ensure the `widget_config` in your `widgets.json` points to the correct `form_endpoint`. ```python import uuid from datetime import date as dateType from typing import Literal, Union from fastapi import FastAPI from pydantic import BaseModel, ConfigDict, Field app = FastAPI() AccountTypes = Literal["General Fund", "Separately Managed", "Private Equity", "Family Office"] class GeneralIntake(BaseModel): """Submit a form via POST request.""" model_config = ConfigDict( extra="ignore", model_title_generator=lambda model: "Submit Form" ) date_created: dateType = Field(alias="Created On", default_factory=dateType.today) first_name: str = Field(alias="First Name") last_name: str = Field(alias="Last Name") email: str = Field(alias="Contact Email") dob: dateType = Field( alias="Date Of Birth", ) account_types: Union[AccountTypes, list[AccountTypes]] = Field( alias="Type Of Account", json_schema_extra={ "x-widget_config": {"multiSelect": True}, }, ) class IntakeForm(BaseModel): """Submission Records.""" model_config = ConfigDict(extra="ignore") contacted: bool = Field( title="Contacted", default=False, ) date_created: dateType = Field( title="Created On", ) first_name: str = Field(title="First Name") last_name: str = Field(title="Last Name") email: str = Field(title="Contact Email") dob: dateType = Field( title="Date Of Birth", ) account_types: Union[AccountTypes, list[AccountTypes]] = Field( title="Account Interest", ) unique_id: uuid.UUID = Field( title="Unique ID", default_factory=uuid.uuid4, ) INTAKE_FORMS: list[IntakeForm] = [] @app.post("/general_intake_submit") async def general_intake_post(data: GeneralIntake) -> bool: global INTAKE_FORMS try: INTAKE_FORMS.append(IntakeForm(**data.model_dump())) return True except Exception as e: raise e from e @app.get( "/general_intake", openapi_extra= { "widget_config": { "form_endpoint": "/general_intake_submit", }, }, ) async def general_intake() -> list[IntakeForm]: return INTAKE_FORMS ``` -------------------------------- ### Start Local Development Server Source: https://github.com/openbb-finance/openbb-docs/blob/main/README.md Starts a local development server for live previewing changes. The server typically runs on http://localhost:3000. ```bash npm start ``` -------------------------------- ### Install openbb-technical Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/data-processing/technical.mdx Install the `openbb-technical` package using pip. This command installs the core package and its dependencies. ```console pip install openbb-technical ``` -------------------------------- ### Router Class Initialization Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/architecture_overview.mdx Shows how to initialize the `Router` class with a prefix and description, and how to include sub-routers. ```python from openbb_core.provider.app.router import Router ``` ```python some_router = Router(prefix="", description="Some description of this router.") some_router.include_router(some_sub_router) ``` -------------------------------- ### Install Poetry Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/cli/installation.md Install Poetry, a dependency management tool, which is required for installing the Open Data Platform from source. ```bash pip install poetry ``` -------------------------------- ### Install OpenBB Core without Dependencies Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/architecture_overview.mdx Install 'openbb' package with '--no-deps' flag if only 'openbb-core' is installed and you need to build assets. This ensures the build script is available without installing other components. ```sh pip install openbb --no-deps ``` -------------------------------- ### Define PythonEx Examples Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/how-to/examples.mdx Use PythonEx for more flexible Python code examples. Each example requires a description and a list of code lines. ```python @router.command( methods=["POST"], include_in_schema=False, examples=[ PythonEx( description="Perform Ordinary Least Squares (OLS) regression.", code=[ "stock_data = obb.equity.price.historical(symbol='TSLA', start_date='2023-01-01', provider='fmp').to_df()", 'obb.econometrics.ols_regression(data=stock_data, y_column="close", x_columns=["open", "high", "low"])', ], ) ], ) ``` -------------------------------- ### Run the Application Server Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/data-integration.md Start the backend server using uvicorn to make your custom integration accessible. Ensure the server is running on the specified host and port. ```bash uvicorn main:app --reload --host 0.0.0.0 --port 7779 ``` -------------------------------- ### Install openbb-econometrics Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/data-processing/econometrics.mdx Install the econometrics extension using pip. This command also installs necessary dependencies like arch, linearmodels, and statsmodels. ```console pip install openbb-econometrics ``` -------------------------------- ### OpenBB Routine Execution Help Source: https://github.com/openbb-finance/openbb-docs/blob/main/static/odp/cli/llms-full.txt Displays the help dialogue for the `exe` command, outlining its usage, arguments, and options for executing routine scripts. ```console /exe -h ``` ```console usage: exe [--file FILE [FILE ...]] [-i ROUTINE_ARGS] [-e] [--url URL] [-h] Execute automated routine script. For an example, please use `exe --example` and for documentation and to learn how create your own script type `about exe`. optional arguments: --file FILE [FILE ...], -f FILE [FILE ...] The path or .openbb file to run. (default: None) -i ROUTINE_ARGS, --input ROUTINE_ARGS Select multiple inputs to be replaced in the routine and separated by commas. E.g. GME,AMC,BTC-USD (default: None) -e, --example Run an example script to understand how routines can be used. (default: False) --url URL URL to run openbb script from. (default: None) -h, --help show this help message (default: False) For more information and examples, use 'about exe' to access the related guide. ``` -------------------------------- ### Basic OpenBB Routine Script Example Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/cli/routines/introduction-to-routines.md Illustrates a basic routine script with comments and commands for navigating menus, loading data, applying technical indicators, and performing fundamental analysis. ```openbb # Navigate into the price sub-menu of the equity module. equity/price # Load a company ticker, e.g. Apple historical --symbol AAPL --provider yfinance # Show a candle chart with a 20 day Moving Average /technical/ema --data OBB0 --length 20 # Switch over to the Fundamental Analysis menu /equity/fundamental # Show balance sheet balance --symbol aapl --provider yfinance # Show cash flow statement cash --symbol aapl --provider yfinance # Show income statement income --symbol aapl --provider yfinance # Return to home home ``` -------------------------------- ### Install openbb-quantitative Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/extensions/data-processing/quantitative.mdx Install the `openbb-quantitative` extension using pip. This command also installs necessary dependencies like pandas-ta-openbb, scipy, and statsmodels. ```console pip install openbb-quantitative ``` -------------------------------- ### Install Rust and Cargo on Linux Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/cli/installation.md Use this command to install Rust and Cargo, which are required for Linux installations. Ensure it's added to your PATH. ```bash curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Define APIEx Examples Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/odp/python/developer/how-to/examples.mdx Use APIEx to define structured, language-agnostic examples with parameters. Examples can include descriptions and various parameter combinations. ```python @router.command( model="WorldNews", examples=[ APIEx(parameters={}), APIEx(parameters={"limit": 100}), APIEx( description="Get news on the specified dates.", parameters={"start_date": "2024-02-01", "end_date": "2024-02-07"}, ), APIEx( description="Display the headlines of the news.", parameters={"display": "headline", "provider": "benzinga"}, ), APIEx( description="Get news by topics.", parameters={"topics": "finance", "provider": "benzinga"}, ), APIEx( description="Get news by source using 'tingo' as provider.", parameters={"provider": "tiingo", "source": "bloomberg"}, ), APIEx( description="Filter aticles by term using 'biztoc' as provider.", parameters={"provider": "biztoc", "term": "apple"}, ), ], ) ``` -------------------------------- ### Example Prompts in apps.json Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/json-specs/apps-json-reference.md This JSON snippet shows an example of how to define a list of suggested prompts for an agent within the apps.json configuration. ```json "prompts": [ "What is the latest CPI inflation momentum?", "Show me the year-over-year Core CPI.", "What was the last Non-Farm Payrolls (NFP) number?", "Plot the 2-year and 10-year Treasury yields.", "What is the current 30-year Treasury yield?" ] ``` -------------------------------- ### Complete Agent Example with Widget Data Flow Source: https://github.com/openbb-finance/openbb-docs/blob/main/content/workspace/developers/openbb-ai-sdk.md Implement a complete agent that handles fetching market data via widgets, processing the results, and streaming responses from an LLM. This example demonstrates the full data flow, including error handling and displaying results. ```python from openbb_ai import WidgetRequest, message_chunk, reasoning_step, cite, citations, table, get_widget_data from openbb_ai.models import QueryRequest, DataContent, ClientFunctionCallError import json async def query(request: QueryRequest): """Complete agent implementation with widget data flow.""" last_message = request.messages[-1] # Check for orchestration requests orchestration_requested = ( last_message.role == "ai" and last_message.agent_id == "openbb-copilot" ) # Phase 1: Fetch widget data if needed if ((last_message.role == "human" or orchestration_requested) and request.widgets and request.widgets.primary): widget_requests = [ WidgetRequest( widget=widget, input_arguments={ param.name: param.current_value for param in widget.params } ) for widget in request.widgets.primary ] yield reasoning_step( event_type="INFO", message="Fetching market data..." ).model_dump() yield get_widget_data(widget_requests).model_dump() return # Exit and wait for callback # Phase 2: Process widget data if hasattr(last_message, 'data'): yield reasoning_step( event_type="INFO", message="Analyzing data..." ).model_dump() # Process the data results = [] for item in last_message.data: if isinstance(item, ClientFunctionCallError): yield reasoning_step( event_type="ERROR", message=f"Failed: {item.content}" ).model_dump() continue if isinstance(item, DataContent): for data_item in item.items: data = json.loads(data_item.content) results.append(data) # Stream response from LLM yield message_chunk("Based on the market data analysis:\n").model_dump() # Continue with LLM streaming client = openai.AsyncOpenAI() async for event in await client.chat.completions.create( model="gpt-4o", messages=openai_messages, stream=True, ): if chunk := event.choices[0].delta.content: yield message_chunk(chunk).model_dump() # Show data table if results: yield table( data=results[:5], # Show top 5 name="Market Summary", description="Key metrics" ).model_dump() # Add citations citation_list = [ cite(widget=widget, input_arguments={ param.name: param.current_value for param in widget.params }) for widget in request.widgets.primary ] yield citations(citation_list).model_dump() yield reasoning_step( event_type="SUCCESS", message="Analysis complete" ).model_dump() # Phase 3: Handle regular chat without widgets else: yield message_chunk("Please add some widgets to analyze market data.").model_dump() ```