### Install langchain-community Source: https://docs.sectors.app/recipes/generative-ai-python/06-memory-ai Install the necessary package for SQL chat message history. Recommended to do this in a virtual environment. ```bash pip install langchain-community ``` -------------------------------- ### Get Format Instructions Source: https://docs.sectors.app/recipes/generative-ai-python/04-structured-output Retrieve the formatting instructions from the PydanticOutputParser, which can be used in prompts to guide LLM output. ```bash >>> parser.get_format_instructions() 'The output should be formatted as a JSON instance that conforms to the JSON schema below. As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}\nthe object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted. Here is the output schema:\n```\n{"description": "Information about a company\'s stock", "properties": {"symbol": {"description": "The stock symbol", "title": "Symbol", "type": "string"}, "name": {"description": "The name of the company for which the stock symbol represents", "title": "Name", "type": "string"}, "sector": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": null, "description": "The sector of the company", "title": "Sector"}, "industry": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": null, "description": "The industry of the company", "title": "Industry"}, "market_cap": {"anyOf": [{"type": "integer"}, {"type": "null"}], "default": null, "description": "The market capitalization of the company", "title": "Market Cap"}}, "required": ["symbol", "name"]}\n```' ``` -------------------------------- ### Install necessary Python packages Source: https://docs.sectors.app/recipes/generative-ai-python/02-tool-use Install the required libraries for making HTTP requests and using Langchain with Groq. ```bash pip install requests pip install langchain pip install langchain-groq ``` -------------------------------- ### Direct Fields Query Examples Source: https://docs.sectors.app/api-references/v2/singapore/screener/sgx-companies Examples demonstrating how to query direct fields using standard operators. ```APIDOC ## Direct Fields Query Examples ### Description Examples demonstrating how to query direct fields using standard operators. ### Method GET ### Endpoint /v2/singapore/screener ### Parameters #### Query Parameters - **where** (string) - Required - Filtering conditions for the screener. ### Request Example ```http GET /v2/singapore/screener?where=market_cap > 500000000000000 GET /v2/singapore/screener?where=company_name like '%energi%' GET /v2/singapore/screener?where=sector = 'Financials' and listing_date > '2005-01-01' ``` ### Response #### Success Response (200) Returns a list of companies matching the query criteria. #### Response Example (Response structure depends on the specific query and available data) ``` -------------------------------- ### Install Dependencies Source: https://docs.sectors.app/recipes/sectors-for-ai-agents/04-human-agent Installs the necessary Python libraries for making API requests and handling asynchronous operations. ```bash !pip install requests nest_asyncio -q ``` -------------------------------- ### Install Sectors Financial API Skill Source: https://docs.sectors.app/recipes/generative-ai-python/01-agent-skills-guide Use this command to install the Sectors Financial API skill from ClawHub. ```bash openclaw skills install sectors-api ``` -------------------------------- ### Install openai-agents Package Source: https://docs.sectors.app/recipes/generative-ai-python/03-multiagent-workflows Install the necessary package for building agent workflows. ```bash pip install openai-agents ``` -------------------------------- ### Example Log Format Source: https://docs.sectors.app/recipes/api-security/01-securing-api-usage This is an example of a structured log entry for API usage. Ensure sensitive information is not logged. ```text [2023-10-15 14:23:45] INFO: GET /api/v2/company/report/ - Status: 200 - User ID: 123xx45 ``` -------------------------------- ### Install LangGraph Source: https://docs.sectors.app/recipes/generative-ai-python/05-conversational Install the LangGraph library using pip. This is required for building more complex agentic systems. ```bash pip install langgraph ``` -------------------------------- ### Install Python Packages Source: https://docs.sectors.app/recipes/stock-investing-and-finance/02-benchmarking-idx-banking-stocks-sectors-api Installs the required Python packages for data analysis and visualization. Run this command in your environment before proceeding. ```bash !pip install requests pandas matplotlib numpy -q ``` -------------------------------- ### Install Skill via Natural Language Source: https://docs.sectors.app/recipes/generative-ai-python/01-agent-skills-guide Alternatively, instruct your OpenClaw agent to install the skill using natural language. ```text Install the sectors-api skill ``` -------------------------------- ### Install Required Python Libraries Source: https://docs.sectors.app/recipes/quick-start-in-python/01-list-all-subsectors Install the requests, pandas, and altair libraries using pip. These are necessary for making HTTP requests, data manipulation, and visualization respectively. ```python pip install requests pandas altair ``` -------------------------------- ### Install Required Python Libraries Source: https://docs.sectors.app/recipes/quick-start-in-python/00-your-first-request Install the 'requests', 'pandas', and 'altair' libraries using pip. These are necessary for making HTTP requests, data manipulation, and data visualization, respectively. ```bash pip install requests pip install pandas pip install altair ``` -------------------------------- ### Clone Sectors Agent Skills Repository Source: https://docs.sectors.app/recipes/generative-ai-python/01-agent-skills-guide Clone the repository to your local machine to get started with the Sectors agent skills. ```bash git clone https://github.com/supertypeai/sectors-agent-skills/ cd sectors-agent-skills ``` -------------------------------- ### Import and Initialize ChatGroq with Structured Output Source: https://docs.sectors.app/recipes/generative-ai-python/03-structured-output Imports necessary libraries, loads environment variables, defines a Pydantic model for stock information, and initializes `ChatGroq` with a specified model and API key, then configures it for structured output. ```python import os from dotenv import load_dotenv from typing import Optional from pydantic import BaseModel, Field from langchain_groq import ChatGroq load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") class Stock(BaseModel): """Information about a company's stock""" symbol: str = Field(description="The stock symbol") name: str = Field(description="The name of the company for which the stock symbol represents") sector: Optional[str] = Field(default=None, description="The sector of the company") industry: Optional[str] = Field(default=None, description="The industry of the company") market_cap: Optional[int] = Field(default=None, description="The market capitalization of the company") llm = ChatGroq( temperature=0, # model_name="llama3-groq-70b-8192-tool-use-preview", model_name="openai/gpt-oss-120b", groq_api_key=GROQ_API_KEY, ) structured_llm = llm.with_structured_output(Stock) print(type(structured_llm)) ``` -------------------------------- ### Set Request Timeout in Python Source: https://docs.sectors.app/recipes/api-security/01-securing-api-usage Configure a timeout for requests to prevent indefinite hanging. This example sets a 5-second timeout for a GET request. ```python try: response = requests.get(API_URL, headers=headers, timeout=5) # 5 seconds timeout response.raise_for_status() except requests.exceptions.Timeout: print("Request timed out. Try again later.") ``` -------------------------------- ### Get SGX Share Buybacks Source: https://docs.sectors.app/api-references/v2/singapore/transaction/share-buybacks Fetches SGX share buyback records. You can filter results by date range (start and end dates) and SGX symbol. ```APIDOC ## GET /v2/sgx/buybacks/ ### Description Returns SGX share buyback records. Each row includes the purchase date, buyback type, price range, total value, total shares purchased, treasury shares after purchase, and mandate details. SGX symbol: 3 characters (letters or digits). E.g. `D05`, `U11`, `Z74`. Date filters: both `start` and `end` are independent and optional — omit either side to leave that bound unconstrained. Future `end` dates return 400. ### Method GET ### Endpoint /v2/sgx/buybacks/ ### Parameters #### Query Parameters - **start** (string) - Optional - Start date for filtering buyback records (YYYY-MM-DD). - **end** (string) - Optional - End date for filtering buyback records (YYYY-MM-DD). - **symbol** (string) - Optional - SGX stock symbol (3 characters, e.g., D05). ``` -------------------------------- ### Create PromptTemplate with Format Instructions Source: https://docs.sectors.app/recipes/generative-ai-python/03-structured-output Construct a PromptTemplate that includes the format instructions from the parser, a query variable, and uses partial variables for the instructions. ```python from langchain_core.prompts import PromptTemplate prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()}, ) ``` -------------------------------- ### Get Stock Suspensions Source: https://docs.sectors.app/api-references/v2/indonesia/news/suspensions Fetches a paginated list of historical stock suspensions for IDX-listed companies. Supports filtering by symbol, start date, and end date. ```APIDOC ## GET /v2/suspensions/ ### Description Returns a paginated list of historical IDX-listed stock suspensions, including the date a stock was suspended, the official reason, and a link to the IDX PDF notice. Filter by `symbol` to look up a specific company's suspension history, or by `start` / `end` to scope to a date window. Date filters: both `start` and `end` are independent and optional — omit either side to leave that bound unconstrained. Future `end` dates return 400. ### Method GET ### Endpoint /v2/suspensions/ ### Parameters #### Query Parameters - **symbol** (string) - Optional - Filter by company symbol. - **start** (string) - Optional - Start date for the suspension date window (YYYY-MM-DD). - **end** (string) - Optional - End date for the suspension date window (YYYY-MM-DD). ### Response #### Success Response (200) - **data** (array) - List of suspension records. - **symbol** (string) - The stock symbol. - **suspension_date** (string) - The date the stock was suspended (YYYY-MM-DD). - **reason** (string) - The official reason for the suspension. - **notice_url** (string) - URL to the official IDX PDF notice. - **next_page_token** (string) - Token for paginating to the next page of results. ``` -------------------------------- ### Set up LLM and Prompt for Financial Advisor Source: https://docs.sectors.app/recipes/generative-ai-python/06-memory-ai Initializes the LLM and defines a chat prompt template for a financial advisor. Pay attention to the variable names used for history and the user's question. ```python import os from dotenv import load_dotenv from langchain_groq import ChatGroq from langchain_core.prompts import ChatPromptTemplate, from langchain_core.runnables import RunnableWithMessageHistory from langchain_core.chat_history import InMemoryChatMessageHistory load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") llm = ChatGroq(model="openai/gpt-oss-120b") prompt = ChatPromptTemplate.from_messages( [ ( "system", "You're a financial stock advisor with adept knowledge of the Indonesian stock exchange (IDX) and adept at analysing, summarizing, inferring trends from financial information", ), MessagesPlaceholder(variable_name="history"), ("human", "{question}"), ] ) chain = prompt | llm ``` -------------------------------- ### Accessing Annual Financial Data Source: https://docs.sectors.app/api-references/v2/indonesia/screener/companies Use bracket notation with the year to access annual financial data for companies. For example, to get the price-to-earnings ratio for 2024, use `pe[2024]`. ```text forecast_revenue_estimate[2025] ``` ```text pe[2024] ``` ```text pb[2024] ``` ```text ps[2024] ``` ```text pcf[2024] ``` ```text peg[2024] ``` ```text enterprise_to_ebitda[2024] ``` ```text enterprise_to_revenue[2024] ``` ```text pb_peer_avg[2024] ``` ```text pe_peer_avg[2024] ``` ```text ps_peer_avg[2024] ``` ```text debt_to_asset_ratio[2024] ``` ```text debt_to_equity_ratio[2024] ``` ```text cash_flow_to_debt_ratio[2024] ``` ```text interest_coverage_ratio[2024] ``` ```text current_ratio[2024] ``` ```text operating_cash_flow_margin[2024] ``` ```text fixed_asset_turnover[2024] ``` ```text total_asset_turnover[2024] ``` ```text roa[2024] ``` ```text roe[2024] ``` ```text net_profit_margin[2024] ``` ```text gross_profit_margin[2024] ``` ```text operating_profit_margin[2024] ``` ```text capital_adequacy_ratio[2024] ``` ```text casa_ratio[2024] ``` ```text leverage_ratio[2024] ``` ```text loan_to_deposit_ratio[2024] ``` ```text liquidity_coverage_ratio[2024] ``` ```text efficiency_ratio[2024] ``` ```text net_interest_margin[2024] ``` ```text cost_to_income_ratio[2024] ``` -------------------------------- ### Start Claude Code with Skill Source: https://docs.sectors.app/recipes/generative-ai-python/01-agent-skills-guide Launch Claude Code from the agent skills directory or explicitly reference the SKILL.md file. ```bash claude --skill ./SKILL.md ``` -------------------------------- ### Fetch Data from Sectors API Source: https://docs.sectors.app/recipes/build-python-app/sectorscan/01-sectorscan-part1 A reusable function to make GET requests to the Sectors Financial API. Ensure you have the 'requests' library installed. Replace 'Your API Key' with your actual API key. ```python import requests def fetch_data(url): api_key = "Your API Key" headers = { "Authorization": api_key } response = requests.get(url, headers = headers) if response.status_code == 200: return response.json() else: # Handle error raise Exception(f"API request failed with status code {response.status_code}") ``` -------------------------------- ### Get Quarterly Financials Source: https://docs.sectors.app/api-references/v2/indonesia/report/quarterly-financials Fetches quarterly financial data for a specified IDX symbol. The available fields may differ based on the company's sector. For example, financial-sector companies will have additional metrics. ```APIDOC ## GET /v2/indonesia/report/quarterly-financials ### Description Returns quarterly financial data for a given IDX symbol. Fields vary by sector — financial-sector companies (banks, insurance) have additional metrics like `net_interest_income`, `gross_loan`, `total_deposit`. ### Method GET ### Endpoint `/v2/indonesia/report/quarterly-financials` ### Parameters #### Query Parameters - **symbol** (string) - Required - The IDX symbol of the company (e.g., `BMRI`, `BBCA`, `TLKM`). Optionally followed by `.jk` (case-insensitive). - **report_date** (string) - Required - The specific report date for the quarterly financials. Use the [Quarterly Financial Dates](../helper-list/company-quarterly-dates) endpoint to get valid `report_date` values for a symbol. ### Response #### Success Response (200) - **symbol** (string) - The IDX symbol. - **report_date** (string) - The date of the financial report. - **sector_specific_metrics** (object) - Contains additional financial metrics relevant to the company's sector (e.g., `net_interest_income`, `gross_loan`, `total_deposit` for financial sector companies). - **general_metrics** (object) - Contains standard financial metrics applicable across sectors. ### Costs 1 API credit per quarter returned. ``` -------------------------------- ### Get SGX Filings Source: https://docs.sectors.app/api-references/v2/singapore/news/sgx-filings Retrieves a paginated list of SGX filings. You can filter the results by start and end dates, transaction type, and holder type. Pagination is supported using limit and offset parameters. ```APIDOC ## GET /v2/singapore/news/sgx-filings ### Description Retrieves a paginated list of SGX filings. You can filter the results by start and end dates, transaction type, and holder type. Pagination is supported using limit and offset parameters. ### Method GET ### Endpoint /v2/singapore/news/sgx-filings ### Parameters #### Query Parameters - **start** (string) - Optional - Start date in `YYYY-MM-DD` format. Filters on `timestamp`. - **end** (string) - Optional - End date in `YYYY-MM-DD` format. Future dates return 400. - **limit** (integer) - Optional - Number of results to return. Maximum: 30. Default: 20. - **offset** (integer) - Optional - Number of results to skip for pagination. Default: 0. - **transaction_type** (string) - Optional - Filter by transaction type (case-insensitive). Enum: award, buy, others, sell, transfer. - **holder_type** (string) - Optional - Filter by holder type (case-insensitive). Enum: insider, institution. ### Response #### Success Response (200) - **results** (array) - Array of SGX filing items. - **pagination** (object) - Pagination details for the results. #### Response Example { "results": [ { "symbol": "STI", "timestamp": "2023-10-27", "transaction_type": "buy", "holder_name": "DBS Bank Ltd", "holder_type": "institution", "holding_before": 1000000, "holding_after": 1100000, "amount_transaction": 100000, "transaction_value": 123456.78, "price_per_share": 1.2345678, "share_percentage_before": 0.1, "share_percentage_after": 0.11, "share_percentage_transaction": 0.01 } ], "pagination": { "total_count": 100, "showing": 20, "limit": 20, "offset": 0, "has_next": true } } #### Error Response (429) - **code** (integer) - Error code. - **message** (string) - Error message. #### Response Example { "code": 429, "message": "Rate limit exceeded. Consider upgrading." } ``` -------------------------------- ### Setup Retriever Utility Source: https://docs.sectors.app/recipes/generative-ai-python/05-conversational Sets up a utility function to retrieve data from an endpoint using an API key. Handles HTTP errors and returns JSON data. ```python import os import json import requests from dotenv import load_dotenv from typing import List load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") SECTORS_API_KEY = os.getenv("SECTORS_API_KEY") def retrieve_from_endpoint(url: str) -> dict: headers = {"Authorization": SECTORS_API_KEY} try: response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() except requests.exceptions.HTTPError as err: raise SystemExit(err) return json.dumps(data) ``` -------------------------------- ### Get Commodity Price Source: https://docs.sectors.app/api-references/v2/mining/commodities-trade/commodity-price Retrieves historical price data for a specified commodity. You can filter by start and end years. Requesting more than 3 years will result in a 400 error. This operation costs 1 API credit. ```APIDOC ## GET /mining/commodities/{commodity_name}/price ### Description Retrieves historical price data for a specified commodity. ### Method GET ### Endpoint /mining/commodities/{commodity_name}/price ### Parameters #### Path Parameters - **commodity_name** (string) - Required - The commodity name (e.g., `Gold`, `Coal`). Get valid names from the [List Commodities](../commodities-trade/commodities) endpoint. #### Query Parameters - **start_year** (integer) - Optional - Start year (e.g., `2022`). Defaults to current year − 2. - **end_year** (integer) - Optional - End year inclusive (e.g., `2024`). Defaults to current year. Maximum 3-year range from `start_year`. ### Response #### Success Response (200) - **name** (string) - Commodity name. - **date** (string) - Price date (monthly). - **price_usd_per_ton** (number) - Price in USD per metric ton. #### Response Example ```json [ { "name": "Gold", "date": "2024-01-01", "price_usd_per_ton": 63488000 }, { "name": "Gold", "date": "2024-02-01", "price_usd_per_ton": 66244000 } ] ``` #### Error Response (400) - **error** (string) - Invalid year parameters or date range exceeds 3 years. #### Error Response (404) - **error** (string) - Commodity not found or no data in specified range. #### Error Response (429) - **code** (integer) - 429 - **message** (string) - Rate limit exceeded. Consider upgrading. ``` -------------------------------- ### Initialize LLM and Agent Executor for Tool Use Source: https://docs.sectors.app/recipes/generative-ai-python/02-tool-use Sets up the ChatPromptTemplate, ChatGroq LLM, and AgentExecutor for handling tool-based queries. Note: The model 'llama3-groq-70b-8192-tool-use-preview' is deprecated and replaced with 'openai/gpt-oss-120b'. Ensure GROQ_API_KEY is set in your environment. ```python from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_groq import ChatGroq from langchain_classic.agents import create_tool_calling_agent, AgentExecutor prompt = ChatPromptTemplate.from_messages( [ ( "system", """Answer the following queries, being as factual and analytical as you can. If you need the start and end dates but they are not explicitly provided, infer from the query. Whenever you return a list of names, return also the corresponding values for each name. If the volume was about a single day, the start and end parameter should be the same.""" ), ("human", "{input}"), # msg containing previous agent tool invocations # and corresponding tool outputs MessagesPlaceholder("agent_scratchpad"), ] ) llm = ChatGroq( temperature=0, # model_name="llama3-groq-70b-8192-tool-use-preview", model_name="openai/gpt-oss-120b", groq_api_key=GROQ_API_KEY, ) # agent = create_tool_calling_agent(llm, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) ``` -------------------------------- ### Get SGX Share Buybacks Source: https://docs.sectors.app/api-references/v2/singapore/transaction/share-buybacks Fetches SGX share buyback records. You can filter by a date range using `start` and `end` query parameters. Both parameters are optional. Providing a future `end` date will result in an error. ```APIDOC ## GET /singapore/transaction/share-buybacks ### Description Returns SGX share buyback records. Each row includes the purchase date, buyback type, price range, total value, total shares purchased, treasury shares after purchase, and mandate details. ### Method GET ### Endpoint `/singapore/transaction/share-buybacks` ### Query Parameters - **start** (string) - Optional - The start date for filtering buyback records (YYYY-MM-DD). - **end** (string) - Optional - The end date for filtering buyback records (YYYY-MM-DD). ### Request Example ```json { "example": "/singapore/transaction/share-buybacks?start=2023-01-01&end=2023-12-31" } ``` ### Response #### Success Response (200) - **purchase_date** (string) - The date of the share purchase. - **buyback_type** (string) - The type of buyback. - **price_range** (string) - The price range of the shares bought back. - **total_value** (number) - The total value of the shares bought back. - **total_shares_purchased** (integer) - The total number of shares purchased. - **treasury_shares_after_purchase** (integer) - The number of treasury shares after the purchase. - **mandate_details** (string) - Details about the buyback mandate. #### Response Example ```json { "example": [ { "purchase_date": "2023-10-26", "buyback_type": "Market Purchase", "price_range": "3.10 - 3.12", "total_value": 15600.00, "total_shares_purchased": 5000, "treasury_shares_after_purchase": 100000, "mandate_details": "Mandate A" } ] } ``` ``` -------------------------------- ### Detailed Chat Prompt Template Source: https://docs.sectors.app/recipes/generative-ai-python/02-tool-use A Python example demonstrating a detailed ChatPromptTemplate for an LLM. It includes system instructions, human input, and a placeholder for agent scratchpad, with the current date dynamically inserted into the system prompt. ```python prompt = ChatPromptTemplate.from_messages( [ ( "system", "" Answer the following queries, being as factual and analytical as you can. If you need the start and end dates but they are not explicitly provided, infer from the query. Whenever you return a list of names, return also the corresponding values for each name. If the volume was about a single day, the start and end parameter should be the same. Note that the endpoint for performance since IPO has only one required parameter, which is the stock. Today's date is " + get_today_date(), ), ("human", "{input}"), # msg containing previous agent tool invocations and corresponding tool outputs MessagesPlaceholder("agent_scratchpad"), ] ) ``` -------------------------------- ### Get Top Companies by Transaction Volume Source: https://docs.sectors.app/recipes/generative-ai-python/02-tool-use This snippet shows an AI agent invoking a tool to retrieve the top companies by transaction volume within a specified date range. It requires start date, end date, and the number of top companies (top_n) as parameters. ```sh > Entering new AgentExecutor chain... Invoking: `get_top_companies_by_tx_volume` with `{'start_date': '2024-07-24', 'end_date': '2024-07-31', 'top_n': 3}` {"2024-07-24": [{"symbol": "GOTO.JK", "company_name": "PT GoTo Gojek Tokopedia Tbk", "volume": 2660984600, "price": 54}, {"symbol": "BSBK.JK", "company_name": "PT Wulandari Bangun Laksana Tbk", "volume": 1833364900, "price": 83}, {"symbol": "DOOH.JK", "company_name": "PT Era Media Sejahtera Tbk", "volume": 511754100, "price": 53}], "2024-07-25": [{"symbol": "BSBK.JK", "company_name": "PT Wulandari Bangun Laksana Tbk", "volume": 1513766400, "price": 76}, {"symbol": "GOTO.JK", "company_name": "PT GoTo Gojek Tokopedia Tbk", "volume": 911091700, "price": 54}, {"symbol": "BBKP.JK", "company_name": "PT Bank KB Bukopin Tbk", "volume": 432596400, "price": 56}], "2024-07-26": [{"symbol": "BSBK.JK", "company_name": "PT Wulandari Bangun Laksana Tbk", "volume": 2408506000, "price": 72}, {"symbol": "GOTO.JK", "company_name": "PT GoTo Gojek Tokopedia Tbk", "volume": 913457100, "price": 53}, {"symbol": "MSJA.JK", "company_name": "PT Multi Spunindo Jaya Tbk.", "volume": 450977300, "price": 342}], "2024-07-29": [{"symbol": "GOTO.JK", "company_name": "PT GoTo Gojek Tokopedia Tbk", "volume": 1621366300, "price": 54}, {"symbol": "ATLA.JK", "company_name": "PT Atlantis Subsea Indonesia Tbk", "volume": 1255103900, "price": 50}, {"symbol": "BSBK.JK", "company_name": "PT Wulandari Bangun Laksana Tbk", "volume": 754254000, "price": 69}], "2024-07-30": [{"symbol": "GOTO.JK", "company_name": "PT GoTo Gojek Tokopedia Tbk", "volume": 1236811400, "price": 55}, {"symbol": "BSBK.JK", "company_name": "PT Wulandari Bangun Laksana Tbk", "volume": 797879400, "price": 69}, {"symbol": "BIPI.JK", "company_name": "PT Astrindo Nusantara Infrastruktur Tbk.", "volume": 629061500, "price": 59}]} > Finished chain. Answer: The top 3 companies by transaction volume over the last 7 days are PT GoTo Gojek Tokopedia Tbk, PT Wulandari Bangun Laksana Tbk, and PT Era Media Sejahtera Tbk. ``` -------------------------------- ### Get Daily Stock Transaction Data Source: https://docs.sectors.app/recipes/generative-ai-python/02-tool-use This snippet shows an AI agent invoking a tool to retrieve daily stock transaction data for a specific stock symbol within a given date range. It requires the stock symbol, start date, and end date as arguments. ```sh > Entering new AgentExecutor chain... To determine if we are seeing an uptrend or downtrend in BBCA\'s closing prices between June 1st and June 30th, 2024, we need to analyze the closing prices over this period. First, let\'s get the daily transaction data for BBCA for the specified period: ```json { "name": "get_daily_tx", "arguments": { "stock": "BBCA", "start_date": "2024-06-01", "end_date": "2024-06-30" } } ``` > Finished chain. Answer: After analyzing the data, we can see that the closing prices have been increasing over the period, with the closing price on June 30th being higher than on June 1st. This indicates an uptrend in BBCA\'s closing prices during June 2024. The uptrend could be due to various factors such as positive news or events related to the company, an increase in investor confidence, or a general upward trend in the market. ``` -------------------------------- ### Successful Response Example (200 OK) Source: https://docs.sectors.app/api-references/news/news Example of a successful response returning a list of news articles. This includes article details like ID, creation date, title, body, source, and financial dimensions. ```json [ { "id": 5642, "created_at": "2025-06-28T04:21:45.467814Z", "title": "Bank Indonesia Records 43.77% Increase in Financial Surplus in 2024", "body": "Bank Indonesia reported a financial surplus of IDR 52.19 trillion in 2024, a 43.77% increase from IDR 36.3 trillion in 2023, driven by high revenue of IDR 228.66 trillion and expenses of IDR 161.3 trillion.", "source": "https://insight.kontan.co.id/news/surplus-bank-indonesia-naik-berkat-kebijakan-moneter", "timestamp": "2025-06-28T04:35:00Z", "sector": "financials", "sub_sector": [ "banks" ], "tags": [ "Bank Indonesia", "Financial Ratios", "Capital Allocation", "Profit", "Revenue", "Bullish" ], "tickers": [], "dimension": { "future": 0, "dividend": 0, "ownership": 0, "technical": 0, "valuation": 0, "financials": 2, "management": 0, "sustainability": 0 } }, { "id": 5646, "created_at": "2025-06-28T04:32:52.825906Z", "title": "Indonesian Banks Host Large Events to Attract New Customers and Boost Digital Transactions", "body": "Several national banks in Indonesia are hosting large events, such as concerts and marathons, to attract new customers and increase digital transactions. Bank Tabungan Negara (BTN) is expecting a 15-20% increase in transactions and digital service activations through its Jakarta International Marathon event.", "source": "https://insight.kontan.co.id/news/bank-menjaring-nasabah-lewat-event-lari-hingga-konser-musik", "timestamp": "2025-06-27T06:30:00Z", "sector": "financials", "sub_sector": [ "banks" ], "tags": [ "Bank Indonesia", "Digital Payments", "Financial Ratios", "Loan Growth", "Bullish" ], "tickers": [ "BTPN.JK" ], "dimension": { "future": 2, "dividend": 0, "ownership": 0, "technical": 0, "valuation": 0, "financials": 1, "management": 0, "sustainability": 0 } }, ... ] ``` -------------------------------- ### Get IDX Historical Market Cap Data Source: https://docs.sectors.app/api-references/transaction/idx-mc Fetches historical market cap data for the IDX within a specified date range (up to 90 days). Supports custom start and end dates, with default values provided if not specified. Note: This is a v1 endpoint and is discontinued. ```APIDOC ## GET /v1/idx/market-cap ### Description Retrieves historical market cap data for the IDX (Indonesia Stock Exchange) for a specified interval, with a maximum of 90 days of data. ### Method GET ### Endpoint /v1/idx/market-cap ### Parameters #### Header Parameters - **Authorization** (string) - Required - Authorization header that should be filled with your Sectors Financial API key. #### Query Parameters - **start** (string) - Optional - Start date for which the IDX historical market cap data is to be retrieved. Format: YYYY-MM-DD. Defaults to 30 days before the `end` date, or 30 days before today if `end` is not provided. Must be no earlier than 90 days before the `end` date. - **end** (string) - Optional - End date for which the IDX historical market cap data is to be retrieved. Format: YYYY-MM-DD. Defaults to today. Must be no later than 90 days after the `start` date. ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **payload** (IDXMarketCapData[]) - An array of IDX market cap data objects. - **date** (string) - The date of the total IDX market capitalization data. - **idx_total_market_cap** (integer) - The total IDX market capitalization on the given date in IDR. #### Response Example ```json [ { "date": "2024-01-02", "idx_total_market_cap": 11741696124656268 }, { "date": "2024-01-03", "idx_total_market_cap": 11682715125038308 } ] ``` #### Error Responses - **400 Bad Request** - `{"error": "Use a valid date format of YYYY-MM-DD."}` - `{"error": "Starting date must not be earlier than January 1, 2021."}` - `{"error": "Start date must not be later than end date."}` - `{"error": "Dates cannot be in the future. Today's date is 2025-04-28."}` - **429 Too Many Requests** - `{"code": 429, "message": "Rate limit exceeded. Consider upgrading."}` ``` -------------------------------- ### Get Daily Transaction Data Source: https://docs.sectors.app/api-references/transaction/daily-transaction Fetches daily transaction data for a specific stock ticker within a defined date range. The endpoint supports filtering by start and end dates, with a default range of 30 days if not specified. It's important to note that this v1 endpoint is discontinued and will return a 410 Gone status. ```APIDOC ## GET /v1/transaction/daily ### Description Retrieves daily transaction data for a given ticker within a specified date range (up to 90 days). ### Method GET ### Endpoint `/v1/transaction/daily` ### Parameters #### Header Parameters - **Authorization** (string) - Required - Authorization header that should be filled with your Sectors Financial API key. #### Path Parameters - **ticker** (string) - Required - Ticker of the company for which the daily transaction data is to be retrieved. Examples: `ASII`, `BBCA`, `BBRI`. Format: 4 letters, optionally followed by '.jk', case-insensitive. #### Query Parameters - **start** (string) - Optional - Start date for the data retrieval in `YYYY-MM-DD` format. Must be no earlier than 90 days before the `end` date. Defaults to 30 days before `end` date or 30 days before today if `end` is not provided. - **end** (string) - Optional - End date for the data retrieval in `YYYY-MM-DD` format. Must be no later than 90 days after the `start` date. Defaults to 30 days after `start` date or today if `start` is not provided. ### Response #### Success Response (200) - **payload** (DailyTransactionData[]) - An array of daily transaction data objects. - **DailyTransactionData.symbol** (string) - The ticker of the company. - **DailyTransactionData.date** (string) - The date of the transaction. - **DailyTransactionData.close** (integer) - The closing price of the given ticker in IDR. - **DailyTransactionData.volume** (integer) - The transaction volume of the given ticker. - **DailyTransactionData.market_cap** (integer) - The market capitalization of the given ticker in IDR. #### Error Response (400) - **error** (string) - Possible error messages include: "Given stock ticker does not exist in the requested date.", "Please provide a valid stock ticker.", "Invalid query parameters: .", "Use a valid date format of YYYY-MM-DD." #### Error Response (429) - **code** (integer) - 429 - **message** (string) - Rate limit exceeded. Consider upgrading. ### Response Example (200) ```json [ { "symbol": "GOTO.JK", "date": "2024-05-21", "close": 0, "volume": 0, "market_cap": 0 } ] ``` ### Response Example (400) ```json { "error": "Given stock ticker does not exist in the requested date." } ``` ### Response Example (429) ```json { "code": 429, "message": "Rate limit exceeded. Consider upgrading." } ``` ``` -------------------------------- ### Setting up LLMChain with ConversationBufferMemory Source: https://docs.sectors.app/recipes/generative-ai-python/06-memory-ai This snippet shows how to initialize an LLMChain with a ChatGroq model, a PromptTemplate, and ConversationBufferMemory to enable conversational context. ```python from langchain_classic.memory import ConversationBufferMemory from langchain_groq import ChatGroq from langchain_core.prompts.prompt import PromptTemplate from langchain_classic.chains import LLMChain load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") llm = ChatGroq(model="openai/gpt-oss-120b") template = """The following is a friendly conversation between a human and a helpful AI assistant. If the AI does not know the answer to a question, it truthfully says it does not know. Current conversation: {history} Human: {input} AI Assistant:""" prompt = PromptTemplate(input_variables=["history", "input"], template=template) conversation = LLMChain( llm=llm, prompt=prompt, verbose=True, memory=ConversationBufferMemory(memory_key="history") ) ``` -------------------------------- ### Handle Diverse Outputs: Stocks and Conversational Responses Source: https://docs.sectors.app/recipes/generative-ai-python/04-structured-output Demonstrates invoking the structured output chain with different types of prompts. The first example generates fictional stock data, while the second handles a simple conversational query, showcasing the flexibility of the `FinalResponse` schema. ```python create = "Create two fictional companies that contain the word 'Super' in their name and operating in the technology sector. Make up the other details about the companies." generated = runnable.invoke(create) print(generated.output) # Stocks(stocks=[Stock(symbol='SPR', name='SuperTech Innovations', sector='Technology', industry='Technology', market_cap=500000000), Stock(symbol='SUP', name='SuperNet Solutions', sector='Technology', industry='Technology', market_cap=750000000)]) question = "how are you this evening?" generic = runnable.invoke(question) print(generic.output) # response="I'm doing well, thank you for asking. How can I assist you further this evening?" ``` -------------------------------- ### Create Prompt and Chain Source: https://docs.sectors.app/recipes/generative-ai-python/04-structured-output Construct a prompt using PromptTemplate, incorporating the format instructions, and chain it with an LLM and the PydanticOutputParser for structured output generation. ```python prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()}, ) runnable = prompt | llm | parser ```