### AWS API Gateway and WAF Setup Example Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/api-security/01-securing-api-usage.mdx Basic commands to create an AWS API Gateway REST API and a Web Application Firewall (WAF) for enhanced security. These are foundational steps for securing API traffic. ```bash # Example: Using AWS API Gateway with WAF aws apigateway create-rest-api --name "SectorsFinancialAPI" aws wafv2 create-web-acl --name "SectorsFinancialWAF" --scope REGIONAL ``` -------------------------------- ### Install Dependencies Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/02-tool-use.mdx Install necessary Python libraries for making HTTP requests and using Langchain. ```bash pip install requests pip install langchain pip install langchain-groq ``` -------------------------------- ### Install LangGraph Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/05-conversational.mdx Install the LangGraph library to build more complex agentic systems. ```bash pip install langgraph ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/supertypeai/sectors_api_docs/blob/main/README.md Use this command to install the Mintlify CLI globally. This tool is required for previewing documentation changes locally. ```bash npm i -g mintlify ``` -------------------------------- ### Install langchain-community Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Install the necessary package for SQLChatMessageHistory. It is recommended to do this in a virtual environment. ```bash pip install langchain-community ``` -------------------------------- ### Install openai-agents Package Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/03-multiagent-workflows.mdx Install the necessary package for this recipe. Ensure you have Python and pip installed. ```bash pip install openai-agents ``` -------------------------------- ### Install Required Libraries Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/quick-start-in-python/01-list-all-subsectors.mdx 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 pandas altair ``` -------------------------------- ### Start Claude Code with Skill Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx Start Claude Code from the skill's directory or explicitly reference the SKILL.md file. Alternatively, load the skill within Claude Code using a command. ```bash claude --skill ./SKILL.md ``` ```bash /claude read ./SKILL.md ``` -------------------------------- ### Clone Sectors Agent Skills Repository Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx Clone the repository to your local machine to get started with the agent skills. ```bash git clone https://github.com/supertypeai/sectors-agent-skills/ cd sectors-agent-skills ``` -------------------------------- ### Get Format Instructions Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/04-structured-output.mdx Call `get_format_instructions()` on the parser to obtain a string that describes the expected JSON schema and formatting rules. This string can be included in prompts to guide the LLM. ```bash >>> parser.get_format_instructions() 'The output should be formatted as a JSON instance that conforms to the JSON schema below.\n\nAs 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.\n\nHere 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 Required Libraries Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/quick-start-in-python/00-your-first-request.mdx Install the necessary Python libraries for making HTTP requests, data manipulation, and visualization. These libraries are essential for interacting with the API and processing the data. ```bash pip install requests pip install pandas pip install altair ``` -------------------------------- ### Run Mintlify Development Server Source: https://github.com/supertypeai/sectors_api_docs/blob/main/README.md Execute this command from the root of your documentation project (where mint.json is located) to start the local development server. ```bash mintlify dev ``` -------------------------------- ### Setup and API Key Loading Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/workshop_03.ipynb Loads environment variables for API keys. Ensure GROQ_API_KEY and SECTORS_API_KEY are set in your .env file. ```python import os import json import requests from dotenv import load_dotenv from typing import List from IPython.display import Image, display from langchain_core.prompts import ChatPromptTemplate from langchain_groq import ChatGroq from langchain_core.tools import tool from langgraph.prebuilt import create_react_agent from langchain_core.messages import HumanMessage load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") SECTORS_API_KEY = os.getenv("SECTORS_API_KEY") # SECTORS_API_KEY = "caa1a3b0c03c98047c2d9f790047058c8a9dd0d944df103ffc540ce11d1b41df" ``` -------------------------------- ### Install Sectors API Skill for OpenClaw Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx Use this command to install the Sectors Financial API skill from ClawHub. Alternatively, you can instruct your OpenClaw agent to install it. ```bash openclaw skills install sectors-api ``` -------------------------------- ### Install Streamlit Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/build-python-app/sectorscan/01-sectorscan-part1.mdx Install Streamlit version 1.35.0. This command also installs necessary dependencies like pandas, requests, and altair. ```bash pip install streamlit==1.35.0 ``` -------------------------------- ### Install R Packages Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/animated-plots-in-r/01-top-stock-volume-animation-plot.mdx Installs the tidyverse and gganimate packages for data manipulation and creating animated plots in R. ```r install.packages(c("tidyverse","gganimate")) ``` -------------------------------- ### Streaming Response Example Output Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/05-conversational.mdx This is an example of the output received when streaming responses from the agent. It shows chunks of data including tool calls and the final agent message, separated by '# ----'. ```python { 'agent': {'messages': [ AIMessage(content='', ..., tool_calls=[{'name': 'get_top_companies_ranked', 'args': {'dimension': 'market_cap'} ... }], ) ] } # ---- {'tools': {'messages': [ ToolMessage(content='[{"symbol": "BBCA.JK", "company_name": "PT Bank Central Asia Tbk."}, {"symbol": "BREN.JK", "company_name": "PT Barito Renewables Energy Tbk."}, {"symbol": "TPIA.JK", "company_name": "PT Chandra Asri Pacific Tbk"}, {"symbol": "BBRI.JK", "company_name": "PT Bank Rakyat Indonesia (Persero) Tbk"}, {"symbol": "BMRI.JK", "company_name": "PT Bank Mandiri (Persero) Tbk"}]', name='get_top_companies_ranked', ... )] } # ---- {'agent': {'messages': [ AIMessage(content='Here are the top 5 companies ranked by market cap:\n1. **PT Bank Central Asia Tbk.** (BBCA.JK)\n2. **PT Barito Renewables Energy Tbk.** (BREN.JK)\n3. **PT Chandra Asri Pacific Tbk** (TPIA.JK)\n4. **PT Bank Rakyat Indonesia (Persero) Tbk** (BBRI.JK)\n5. **PT Bank Mandiri (Persero) Tbk** (BMRI.JK)', ... )] } ``` -------------------------------- ### Load API Keys from .env File Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/02-tool-use.mdx Install the python-dotenv library and create a .env file to securely load API keys into your environment variables. ```bash pip install python-dotenv ``` -------------------------------- ### Bash: Install Visualization Dependencies Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/03-multiagent-workflows.mdx Installs necessary Python libraries for data visualization, including pandas, matplotlib, and seaborn. Run this command before using visualization functions. ```bash pip install pandas matplotlib seaborn ``` -------------------------------- ### Configure OpenCode with API Key Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx Set the SECTORS_API_KEY for OpenCode by editing the config.json file or by exporting it as an environment variable before starting OpenCode. ```json { "env": { "SECTORS_API_KEY": "your-api-key-here" } } ``` ```bash export SECTORS_API_KEY="your-api-key-here" opencode ``` -------------------------------- ### Setting up LLM and Agent for Tool Use Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/02-tool-use.mdx Configure a ChatPromptTemplate, initialize a Groq LLM, and create an AgentExecutor for handling tool-based queries. Ensure GROQ_API_KEY is set. ```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) ``` -------------------------------- ### Financial Agent Response: Stock Trend Analysis Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/02-tool-use.mdx This example demonstrates how a financial agent analyzes stock price trends. It shows the tool invocation to get daily transaction data and the subsequent explanation of the trend. ```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. ``` -------------------------------- ### Prompt Template and LLM Configuration Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/workshop_03.ipynb Sets up a system prompt for the agent and initializes the ChatGroq language model with specific parameters. The prompt guides the agent on how to answer queries, infer dates, and format output. ```python prompt = ChatPromptTemplate.from_messages( [ ( "system", f"""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. Always answer in markdown table if you can. """, ), ("human", "{text}"), ] ) llm = ChatGroq( temperature=0, model_name="llama3-groq-70b-8192-tool-use-preview", groq_api_key=GROQ_API_KEY, ) ``` -------------------------------- ### Run the Python Sample Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/quick-start-in-python/00-your-first-request.mdx Execute the Python script from your working directory to send the request to the Sectors Financial API and view the results. This command initiates the script that was previously configured. ```bash python first_request.py ``` -------------------------------- ### Setup Retriever Utility Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/05-conversational.mdx Set up a utility function to retrieve data from an API endpoint using requests. Ensure your API keys are loaded from environment variables. ```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) ``` ```dotenv GROQ_API_KEY="..." SECTORS_API_KEY="..." ``` -------------------------------- ### Set up LLM and Prompt Template Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Initializes the LLM and defines a chat prompt template including a system message, a placeholder for history, and a human input variable. Ensure your environment variables are set up for API keys. ```python import os from dotenv import load_dotenv from langchain_groq import ChatGroq from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder load_dotenv() GROQ_API_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 ``` -------------------------------- ### Install Missing Python Module Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx If you encounter an 'ImportError: No module named 'requests'', install the 'requests' library using pip. ```bash pip install requests ``` -------------------------------- ### Initiate Chat and Print Output Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Initiates a chat with a specific user and input, then prints the content of the response. This example demonstrates a successful interaction using the configured chat function. ```python out = chat( user_id="001", input="hi, my name is Sam. What stocks do i own? I can't remember", ) print(out.content) # Hi Sam! Tidak apa-apa, kita bisa cek bersama! Kamu memiliki saham dari beberapa perusahaan, yaitu BBCA, ADRO, BBRI, dan GOTO. ``` -------------------------------- ### JSON Structure Example: Peers Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/non-programmatical-tools/01-excel/01-excel.mdx This is an example of a nested JSON structure for 'peers' data, illustrating the hierarchy that needs to be navigated in Power Query. ```json "peers": [ { "peers_info": { "companies": [ { "group": [ "sub_sector", "sector", "industry", "sub_industry" ], "pb_mrq": 0.874056870326003, "pe_ttm": 6.80030672274856, "symbol": "BNGA.JK", "dar_mrq": 0.0265205201419848, "der_mrq": 0.171900552646426, "roa_ttm": 0.019768254215725055, "roe_ttm": 0.12813375478101982, "market_cap": 44764426665984, "company_name": "PT Bank CIMB Niaga Tbk", "total_assets": 332993846000000, "total_equity": 51373715000000, "total_revenue": 19029474000000, "profit_and_loss": 6582707000000, "yearly_mcap_chg": 0.0646029933881279, "total_liabilities": 281620131000000, "financials_latest_date": "2024-03-31" }, ], "group_name": { "sector": "Financials", "industry": "Banks", "sub_sector": "Banks", "sub_industry": "Banks" } } } ] ``` -------------------------------- ### Agent Creation with Tools Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/workshop_03.ipynb Initializes a ReAct agent using LangGraph, providing the language model, defined tools, and a system message that instructs the agent on its role and behavior. ```python tools = [ get_company_overview, get_top_companies_ranked, ] system_message = "You are an expert tool calling agent meant for financial data retriever and summarization. Use tools to get the information you need. If you do not know the answer to a question, say so. Whenever possible, answer with markdown-formatted code." app = create_react_agent(llm, tools, state_modifier=system_message) ``` -------------------------------- ### Initialize LLMChain with Memory Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Sets up an `LLMChain` with a specific LLM, prompt template, and `ConversationBufferMemory`. This is an alternative to `ConversationChain` for simpler conversational flows. ```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 import os from dotenv import load_dotenv 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") ) ``` -------------------------------- ### Calculate Start Date for Data Retrieval Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/stock-investing-and-finance/01 - Portfolio-Optimization.mdx This Python function calculates the date 90 days prior to the current date, which can be used as a start date for fetching historical stock data. It utilizes the datetime and timedelta objects for date manipulation. ```python # Retrieve date and price from "Daily Transaction Data" API from datetime import datetime, timedelta # Function to calculate the date 90 days ago from today def calculate_start_date(days_ago=90): return (datetime.now() - timedelta(days=days_ago)).strftime('%Y-%m-%d') # Calculate the start date 90 days ago start_date = calculate_start_date() # Looping API info history_sminfra18 = [] ``` -------------------------------- ### Make Your First API Request Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/quick-start-in-python/00-your-first-request.mdx This Python script demonstrates how to make a GET request to the Sectors Financial API to retrieve a list of subsectors. Ensure you replace 'Your API KEY' with your actual API key. ```python import requests API_KEYS = "Your API KEY" url = "https://api.sectors.app/v2/subsectors/" headers = { "Authorization": API_KEYS } response = requests.get(url, headers = headers) if response.status_code == 200: data = response.json() print(data) else: # Handle error print(response.status_code) ``` -------------------------------- ### Get SGX Companies by Sector Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Returns SGX-listed companies, optionally filtered by sector. ```APIDOC ## GET /v2/sgx/companies/ ### Description Returns SGX-listed companies, optionally filtered by sector. ### Method GET ### Endpoint /v2/sgx/companies/ ### Parameters #### Query Parameters - **sector** (string) - Optional - Filter by sector name. ### Request Example ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/sgx/companies/", headers=headers, params={"sector": "Financials"} ) print(resp.json()) ``` ### Response #### Success Response (200) - **symbol** (string) - The company ticker symbol. - **company_name** (string) - The name of the company. - **sector** (string) - The sector the company belongs to. ``` -------------------------------- ### Initialize ConversationChain with Memory Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Sets up a `ConversationChain` with `ConversationBufferMemory` and a `ChatGroq` model. Requires GROQ API key and environment variables to be set. ```python from langchain_classic.memory import ConversationBufferMemory from langchain_groq import ChatGroq from langchain_core.prompts.prompt import PromptTemplate from langchain_classic.chains import ConversationChain load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") ``` -------------------------------- ### Get Mining License Auction Detail Source: https://github.com/supertypeai/sectors_api_docs/blob/main/api-references/v2/mining/licenses-auctions/mining-license-auctions-detail.mdx Fetches the details of a specific mining license auction. ```APIDOC ## GET /v2/mining/license-auctions/{wiup_code}/ ### Description Retrieves detailed information about a specific mining license auction identified by its WIUP code. ### Method GET ### Endpoint /v2/mining/license-auctions/{wiup_code}/ ### Parameters #### Path Parameters - **wiup_code** (string) - Required - The unique identifier for the mining license auction (WIUP code). ``` -------------------------------- ### Create a Basic ReAct Agent Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/05-conversational.mdx Import and create a ReAct agent using `create_react_agent`. This agent can be invoked with a dictionary containing a 'messages' key. Ensure you have the necessary tools and LLM model defined. ```python from langgraph.prebuilt import create_react_agent tools = [ get_company_overview, get_top_companies_ranked, ] app = create_react_agent(llm, tools) app.invoke({"messages": "..."}) ``` -------------------------------- ### Get SGX Company Report Source: https://github.com/supertypeai/sectors_api_docs/blob/main/api-references/v2/singapore/sgx-report.mdx Fetches a full company report for a specified SGX-listed ticker. ```APIDOC ## GET /v2/sgx/company/report/{ticker}/ ### Description Retrieves a full company report for an SGX-listed ticker. ### Method GET ### Endpoint /v2/sgx/company/report/{ticker}/ ### Parameters #### Path Parameters - **ticker** (string) - Required - The ticker symbol of the SGX-listed company. ``` -------------------------------- ### Get Company News Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Retrieves news articles for IDX-listed companies. You can filter by ticker and/or tag. ```APIDOC ## GET /v2/news/ ### Description Returns news articles for IDX-listed companies. Supports filtering by ticker and/or tag. ### Method GET ### Endpoint /v2/news/ ### Parameters #### Query Parameters - **ticker** (string) - Optional - Filter by company ticker. - **tag** (string) - Optional - Filter by news tag (e.g., "dividends"). ### Request Example ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/news/", headers=headers, params={"ticker": "BBCA", "tag": "dividends"} ) articles = resp.json() for article in articles[:2]: print(article["title"], "-", article["date"]) ``` ### Response #### Success Response (200) - **title** (string) - The title of the news article. - **date** (string) - The publication date of the article. - **url** (string) - The URL to the full article. ``` -------------------------------- ### Python: Sort Companies by Growth or Use Natural Language Query Source: https://github.com/supertypeai/sectors_api_docs/blob/main/get-started/v2/migration-guide.mdx Demonstrates how to fetch top growing companies using direct sorting by revenue growth or by using a natural language query in Python. Requires an API key for authorization. ```python import requests url = "https://api.sectors.app/v2/companies/" headers = {"Authorization": "YOUR_API_KEY"} # Method 1: Direct sorting by growth params = {"order_by": "-yoy_quarter_revenue_growth"} response = requests.get(url, headers=headers, params=params) # Method 2: Natural Language Query params = {"q": "give me the top growing banking companies by revenue in 2024"} response = requests.get(url, headers=headers, params=params) ``` -------------------------------- ### Configure .env File for API Keys Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/02-tool-use.mdx Store your Groq and Sectors API keys in a .env file for easy and secure access. ```dotenv GROQ_API_KEY=your_groq_api_key SECTORS_API_KEY=your_sectors_api_key ``` -------------------------------- ### Get List of All Sectors Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/build-python-app/sectorscan/01-sectorscan-part1.mdx Fetches a list of all available subsectors from the Sectors Financial API and stores them in a list. ```python url = "https://api.sectors.app/v2/subsectors/" data = fetch_data(url) ``` ```python sectors = [item['subsector'] for item in data] ``` -------------------------------- ### Querying Conversation History from SQLite Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Example SQL query to retrieve all stored conversation messages from the 'message_store' table. ```sql SELECT * FROM message_store ``` -------------------------------- ### Rank Companies by Metric (Python) Source: https://github.com/supertypeai/sectors_api_docs/blob/main/get-started/v2/migration-guide.mdx Demonstrates how to rank companies by revenue for a specific year and apply sector filtering using Python. Requires an API key for authorization. ```python import requests url = "https://api.sectors.app/v2/companies/" headers = {"Authorization": "YOUR_API_KEY"} # Basic ranking by revenue for 2023 params = {"order_by": "-revenue[2023]"} response = requests.get(url, headers=headers, params=params) # Ranking with sector filter params = { "order_by": "-revenue[2023]", "where": "sub_sector='banks'" } response = requests.get(url, headers=headers, params=params) ``` -------------------------------- ### List All Tracked Commodities Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Get a list of all commodity types tracked by the mining extension. Requires an API key. ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get("https://api.sectors.app/v2/mining/commodities/", headers=headers) print(resp.json()) # ["coal", "nickel", "gold", "tin", "copper", "bauxite", ...] ``` -------------------------------- ### Create Price/Book Ratio Visualization Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/build-python-app/sectorscan/01-sectorscan-part1.mdx Generates a line chart comparing the Price/Book Ratio across different sectors over the years using Altair. Includes data points and tooltips for interactivity. ```python valuation_chart = alt.Chart(df_valuation).mark_line( point=True # add individual data points to the line chart ).encode( x=alt.X("Year:N", axis=alt.Axis(labelAngle=0)), # 0 degree of x-axis label angle y=alt.Y("Price/Book Ratio:Q"), color=alt.Color( "Sector:N", scale=alt.Scale(scheme="lightgreyred"), sort=alt.SortField(field="Sector", order="ascending") # sort color based on the sector's name ), tooltip=[ alt.Tooltip("Sector:N"), alt.Tooltip("Year:N"), alt.Tooltip("Price/Book Ratio:Q", format=".2f") ] ).properties( title="Price/Book Ratio Across Sectors", width=900 ) ``` -------------------------------- ### Initialize ConversationChain with Memory Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/06-memory-ai.mdx Sets up a `ConversationChain` with a specific LLM, prompt template, and `ConversationBufferMemory`. The `memory_key` in the memory must match a variable in the `PromptTemplate`. ```python from langchain_groq import ChatGroq from langchain_core.prompts.prompt import PromptTemplate from langchain_classic.chains import ConversationChain from langchain_classic.memory import ConversationBufferMemory import os from dotenv import load_dotenv 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 financial stock advisor AI with specific knowledge of the Indonesian stock market (IDX). The AI is talkative and provides lots of specific details from its context. 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 = ConversationChain( llm=llm, prompt=prompt, verbose=True, memory=ConversationBufferMemory(memory_key="history") ) ``` -------------------------------- ### Get Daily Index Transaction Data Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Retrieves daily index-level transaction data for a named IDX index. ```APIDOC ## GET /v2/index-daily/{index_code}/ ### Description Returns daily index-level transaction data for a named IDX index (e.g., `lq45`, `idxbumn20`, `composite`). ### Method GET ### Endpoint /v2/index-daily/{index_code}/ ### Parameters #### Path Parameters - **index_code** (string) - Required - The code of the index (e.g., 'lq45', 'idxbumn20', 'composite'). #### Query Parameters - **start** (string) - Required - The start date for the period (YYYY-MM-DD). - **end** (string) - Required - The end date for the period (YYYY-MM-DD). ### Request Example ```python import requests headers = {"Authorization": "YOUR_API_KEY"} index_code = "lq45" resp = requests.get( f"https://api.sectors.app/v2/index-daily/{index_code}/", headers=headers, params={"start": "2024-01-01", "end": "2024-06-30"} ) print(resp.json()) ``` ### Response #### Success Response (200) - **date** (string) - The date of the index data. - **open** (float) - The opening index value. - **high** (float) - The highest index value. - **low** (float) - The lowest index value. - **close** (float) - The closing index value. - **volume** (integer) - The index trading volume. ``` -------------------------------- ### Portfolio Optimization using SLSQP Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/stock-investing-and-finance/01 - Portfolio-Optimization.mdx This code snippet sets up and performs portfolio optimization using Scipy's minimize function with the SLSQP method. It requires initial guesses for weights, bounds, and constraints. The objective is to minimize the negative Sharpe ratio to maximize the actual Sharpe ratio. ```python init_guess = [0.25, 0.25, 0.25, 0.25] # SLSQP stands for Sequential Least Squares Quadratic Programming, which is an algorithm that can handle both equality and inequality constraints, making it well-suited for portfolio optimization problems. # We are minimize the negative sharp ratio - maximize sharp ratio opt_results = minimize(sharp_neg, init_guess, method = 'SLSQP', bounds = bounds, constraints = cons) opt_results ``` -------------------------------- ### Get SGX Companies by Sector Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Fetch SGX-listed companies, with an option to filter by sector. Requires an API key. ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/sgx/companies/", headers=headers, params={"sector": "Financials"} ) print(resp.json()) ``` -------------------------------- ### Tool Use with ChatGroq LLM Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/05-conversational.mdx This snippet shows how to bind tools to a ChatGroq LLM for conversational agents. It sets up a prompt, initializes the LLM with a specific model and API key, defines available tools, and creates a runnable that invokes the LLM with tool-calling capabilities. Useful for identifying and preparing to call external tools based on user queries. ```python from langchain_core.prompts import ChatPromptTemplate from langchain_groq import ChatGroq prompt = ChatPromptTemplate.from_messages( [ ( "system", f"""Answer the following queries factually. Whenever you return a list of names, return also the corresponding values for each name. Always answer in markdown table if you can. """, ), ("human", "{text}"), ] ) 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, ) tools = [ get_company_overview, get_top_companies_ranked, ] llm_with_tools = llm.bind_tools(tools) runnable = prompt | llm_with_tools out_with_runnable = runnable.invoke("overview of BBRI") print(out_with_runnable.tool_calls) # output: # [{'name': 'get_company_overview', 'args': {'stock': 'BBRI'}, 'id': 'call_9dp1', 'type': 'tool_call'}] ``` -------------------------------- ### Get Listing Performance Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Retrieve listing performance data for a given ticker. Requires an API key for authorization. ```bash curl -H "Authorization: YOUR_API_KEY" \ "https://api.sectors.app/v2/listing-performance/GOTO/" # {"symbol": "GOTO.JK", "chg_7d": -0.0104712, "chg_30d": -0.418848, # "chg_90d": -0.115183, "chg_365d": -0.740838} ``` -------------------------------- ### Company IPO and listing performance Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Get a company's price performance since its IPO listing date. ```APIDOC ## GET /v2/listing-performance/{ticker}/ ### Description Returns a company's price performance since its IPO listing date, with change percentages at 7-day, 30-day, 90-day, and 365-day horizons. ### Method GET ### Endpoint /v2/listing-performance/{ticker}/ ### Parameters #### Path Parameters - **ticker** (string) - Required - The stock ticker symbol of the company. ### Request Example ```python import requests headers = {"Authorization": "YOUR_API_KEY"} for ticker in ["GOTO", "BREN"]: resp = requests.get( f"https://api.sectors.app/v2/listing-performance/{ticker}/", headers=headers ) data = resp.json() print(f"{ticker}: 90d={data['chg_90d']:.2%}, 365d={data.get('chg_365d', 'N/A')}") # GOTO: 90d=-11.52%, 365d=-74.08% ``` ``` -------------------------------- ### Perform Portfolio Optimization using Scipy Minimize Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/stock-investing-and-finance/Stock_Portfolio_Optimization_with_Python.ipynb Uses Scipy's minimize function with the SLSQP method to find the optimal portfolio weights that maximize the Sharpe ratio, subject to the defined bounds and constraints. ```python # SLSQP stands for Sequential Least Squares Quadratic Programming, which is an algorithm that can handle both equality and inequality constraints, making it well-suited for portfolio optimization problems. # We are minimize the negative sharp ratio - maximize sharp ratio opt_results = minimize(sharp_neg, init_guess, method = 'SLSQP', bounds = bounds, constraints = cons) ``` -------------------------------- ### Load Skill in OpenCode Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/sectors-for-ai-agents/01-agent-skills-guide.mdx Manually load the SKILL.md file in OpenCode using the '/load-skill' command. ```bash /load-skill ./SKILL.md ``` -------------------------------- ### Get Province Resources & Reserves Detail Source: https://github.com/supertypeai/sectors_api_docs/blob/main/api-references/v2/mining/sites-production/commodity-resources-reserves-detail.mdx Fetches detailed commodity resources and reserves data for a given province. ```APIDOC ## GET /v2/mining/resources-reserves/{province}/ ### Description Retrieves detailed commodity resources and reserves information for a specified province. ### Method GET ### Endpoint /v2/mining/resources-reserves/{province}/ ### Parameters #### Path Parameters - **province** (string) - Required - The name of the province to query. ### Response #### Success Response (200) - **data** (object) - Contains the resources and reserves details. - **commodity** (string) - The type of commodity. - **resource_category** (string) - The category of the resource (e.g., Measured, Indicated, Inferred). - **reserve_category** (string) - The category of the reserve (e.g., Proved, Probable). - **quantity** (number) - The amount of the resource or reserve. - **unit** (string) - The unit of measurement for the quantity. - **grade** (number) - The grade of the resource or reserve. - **grade_unit** (string) - The unit of measurement for the grade. - **year** (integer) - The year the data pertains to. #### Response Example ```json { "data": [ { "commodity": "Gold", "resource_category": "Measured", "reserve_category": "Proved", "quantity": 1500000, "unit": "tonnes", "grade": 2.5, "grade_unit": "g/t", "year": 2023 }, { "commodity": "Gold", "resource_category": "Indicated", "reserve_category": "Probable", "quantity": 2000000, "unit": "tonnes", "grade": 2.1, "grade_unit": "g/t", "year": 2023 } ] } ``` ``` -------------------------------- ### Get KLSE Company Report Source: https://github.com/supertypeai/sectors_api_docs/blob/main/api-references/v2/malaysia/klse-report.mdx Fetches a detailed report for a specific KLSE-listed company using its ticker symbol. ```APIDOC ## GET /v2/klse/company/report/{ticker}/ ### Description Retrieves a full company report for a KLSE-listed ticker. ### Method GET ### Endpoint /v2/klse/company/report/{ticker}/ ### Parameters #### Path Parameters - **ticker** (string) - Required - The ticker symbol of the KLSE-listed company. ``` -------------------------------- ### Query Companies by Multiple Indices (Python) Source: https://github.com/supertypeai/sectors_api_docs/blob/main/get-started/v2/migration-guide.mdx Demonstrates how to query companies by multiple indices using both SQL-style and natural language filtering in Python. Requires an API key for authorization. ```python import requests url = "https://api.sectors.app/v2/companies/" headers = {"Authorization": "YOUR_API_KEY"} # Method 1: SQL-style filtering params = {"where": "indices in ['idxbumn20', 'lq45']"} response = requests.get(url, headers=headers, params=params) # Method 2: Natural Language Query params = {"q": "find me all companies in lq45 and/or idxbumn20"} response = requests.get(url, headers=headers, params=params) ``` -------------------------------- ### Get Company Quarterly Financial Dates Source: https://github.com/supertypeai/sectors_api_docs/blob/main/api-references/v2/indonesia/helper-list/company-quarterly-dates.mdx Fetches the quarterly financial dates for a company using its ticker symbol. ```APIDOC ## GET /v2/company/get_quarterly_financial_dates/{ticker}/ ### Description Retrieves the quarterly financial dates for a specific company. ### Method GET ### Endpoint /v2/company/get_quarterly_financial_dates/{ticker}/ ### Parameters #### Path Parameters - **ticker** (string) - Required - The ticker symbol of the company. ``` -------------------------------- ### Prepare Revenue Growth Data for Visualization Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/build-python-app/sectorscan/01-sectorscan-part1.mdx Converts the 'Revenue Growth' from a decimal format to a percentage by multiplying by 100. This enhances readability for the visualization. ```python df_top_growth["Revenue Growth (%)"] = df_top_growth["Revenue Growth"] * 100 ``` -------------------------------- ### Python App Requirements Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/build-python-app/sectorscan/02-sectorscan-part2.mdx Specify the Streamlit version required for the application. This file is used by Streamlit to install necessary dependencies. ```txt streamlit==1.35.0 ``` -------------------------------- ### Initialize Monte Carlo Simulation Variables Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/stock-investing-and-finance/01 - Portfolio-Optimization.mdx Sets up the necessary arrays to store weights, returns, volatilities, and Sharpe ratios for multiple Monte Carlo simulation runs. 'num_ports' should be set to the desired number of simulations. ```python # Specify the number of simulated portfolios to generate (in our case, 5000) num_ports = 5000 # A 2D array to store the randomly generated weights for each asset in each portfolio. all_weights = np.zeros((num_ports, len(selected_stocks))) # Create arrays to store portfolio returns, volatilities, and Sharpe ratios for each simulated portfolio. ret_arr = np.zeros(num_ports) vol_arr = np.zeros(num_ports) sharp_arr = np.zeros(num_ports) ``` -------------------------------- ### Get Mining License Auctions Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Retrieve data on government auctions of mining concession licenses. Requires an API key. ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/mining/license-auctions/", headers=headers ) print(resp.json()) ``` -------------------------------- ### Handle Different Output Types with the Same Runnable Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/04-structured-output.mdx Demonstrates invoking the same structured output runnable with different types of prompts. The LLM dynamically chooses the appropriate output schema (Stocks or ConversationalResponse) based on the input query. ```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?" ``` -------------------------------- ### Get Mining Licenses Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Fetch the index of mining licenses (IUP). Supports filtering by commodity. Requires an API key. ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/mining/licenses/", headers=headers, params={"commodity": "nickel"} ) print(resp.json()) ``` -------------------------------- ### Create and Invoke a Chained Runnable with Structured Output Source: https://github.com/supertypeai/sectors_api_docs/blob/main/recipes/generative-ai-python/04-structured-output.mdx Construct a LangChain RunnableSequence by chaining a prompt with an LLM configured to output structured data according to a defined Pydantic schema. Invoke the runnable with input text to generate structured output. ```python from langchain_core.prompts import ChatPromptTemplate from langchain_community.llms import OpenAI # Assuming OpenAI is used llm = OpenAI(temperature=0) # Example LLM initialization prompt = ChatPromptTemplate.from_messages( [ ( "system", "You are an expert extraction algorithm, " "Extract relevant information from the text. " "If you do not know the value of an attribute asked to extract, " "return null for the attribute's value.", ), ("human", "{text}"), ] ) runnable = prompt | llm.with_structured_output(schema=FinalResponse) text = """ Bank Central Asia (BCA) is a bank in Indonesia and is part of the finance sector. It is in the banking industry and has a market capitalization of $85 billion. It trades under the symbol BBCA on the Indonesia Stock Exchange. Bank Rakyat Indonesia (BRI) is the oldest bank in Indonesia, tracing back since 1895. It has a market capital of $52 billion and is an important player in the country's finance sector. It trades as BBRI on the Indonesia Stock Exchange. """ out = runnable.invoke({"text": text}) # in FinalResponse schema, the return value is stored in an attribute called `output` out_list = list(out.output.stocks) print(out_list[0]) # Stock(symbol='BBCA', name='Bank Central Asia', sector='finance', industry='banking', market_cap=85000000000) print(out_list[1]) # Stock(symbol='BBRI', name='Bank Rakyat Indonesia', sector='finance', industry='banking', market_cap=52000000000) ``` -------------------------------- ### Get Mining Contracts Source: https://context7.com/supertypeai/sectors_api_docs/llms.txt Retrieve data on mining work contracts (PKP2B) and concession agreements. Requires an API key. ```python import requests headers = {"Authorization": "YOUR_API_KEY"} resp = requests.get( "https://api.sectors.app/v2/mining/contracts/", headers=headers ) print(resp.json()) ```