Logo
AXION

C SDK

Axion C SDK

The Axion C SDK provides a lightweight, high-performance C library for interacting with the Axion Financial API. This SDK offers direct access to financial data including ESG scores, stock prices, cryptocurrency data, economic indicators, and more. Designed for embedded systems, high-frequency applications, and integration with C/C++ projects.

GitHub: https://github.com/axionquant/c-sdk

Installation & Dependencies

The SDK requires libcurl for HTTP requests andcJSON for JSON parsing. Both can be installed via system package managers or included as submodules.

System Dependencies

Ubuntu/Debian

sudo apt-get install libcurl4-openssl-dev libcjson-dev

macOS (Homebrew)

brew install curl cjson

Building from Source

Clone and compile

git clone https://github.com/axionquant/c-sdk.git
cd c-sdk && mkdir build && cd build
cmake .. && make
sudo make install # optional

|

Compiler Flags

Linker flags

# Static linking
-laxion -lcurl -lcjson

# Or pkg-config (if installed)
pkg-config --cflags --libs axion

Quick Start

A minimal example that initializes the client, fetches stock data and ESG scores for Apple, and cleans up. Always check for errors and free responses.

Steps

  1. Include the main header
  2. Initialize client with your API key
  3. Make API calls
  4. Process JSON responses using cJSON
  5. Free responses and client
|

Quick Start (C)

#include "axion.h"
#include <stdio.h>

int main() {
    AxionClient* client = axion_init("your_api_key_here");
    if (!client) return 1;

    // Get stock quote for Apple
    AxionResponse* quote = axion_stocks_ticker(client, "AAPL");
    if (quote && quote->json && !quote->error) {
        cJSON* price = cJSON_GetObjectItem(quote->json, "price");
        if (cJSON_IsNumber(price))
            printf("AAPL Price: %.2f\n", price->valuedouble);
    }
    axion_response(quote);

    // Get ESG data
    AxionResponse* esg = axion_esg_data(client, "AAPL");
    if (esg && esg->json && !esg->error) {
        cJSON* score = cJSON_GetObjectItem(esg->json, "score");
        if (cJSON_IsNumber(score))
            printf("ESG Score: %.2f\n", score->valuedouble);
    }
    axion_response(esg);

    axion_client(client);
    return 0;
}

Client Initialization

The SDK follows a traditional C pattern: explicit initialization, manual cleanup, and response structures that must be freed. All API calls return an AxionResponse*.

Core Functions

FunctionDescriptionReturns
axion_init(api_key)Create client, init curlAxionClient*
axion_client(client)Cleanup client, global curlvoid
axion_response(resp)Free response + JSONvoid

Response Structure

AxionResponse

int http_status; - HTTP status code
char *data; - raw JSON string
cJSON *json; - parsed JSON (NULL if invalid)
char *error; - error message (NULL if none)

|

Error-aware response handling

AxionResponse* resp = axion_esg_data(client, "AAPL");
if (!resp) {
    // fatal allocation error
    return;
}

if (resp->error) {
    fprintf(stderr, "API error: %s\n", resp->error);
} else if (resp->http_status >= 400) {
    fprintf(stderr, "HTTP %d error\n", resp->http_status);
} else if (!resp->json) {
    fprintf(stderr, "JSON parse failed\n");
} else {
    // success, use resp->json
    cJSON* score = cJSON_GetObjectItem(resp->json, "score");
    // process...
}

axion_response(resp);

API Categories

The SDK provides comprehensive coverage of financial data through categorized API functions. Each category follows consistent naming patterns for easy discovery.

Stocks

Tickers, quotes, prices, gainers/losers, listings

axion_stocks_tickers()axion_stocks_ticker()axion_stocks_prices()axion_stocks_gainers()axion_stocks_losers()axion_stocks_quote()axion_stocks_list_*()

Crypto

Cryptocurrency data

axion_crypto_tickers()axion_crypto_ticker()axion_crypto_prices()axion_crypto_gainers()axion_crypto_losers()axion_crypto_quote()axion_crypto_list_*()

Forex

Currency pairs

axion_forex_tickers()axion_forex_ticker()axion_forex_prices()axion_forex_gainers()axion_forex_losers()axion_forex_quote()axion_forex_list_*()

Futures

Futures contracts

axion_futures_tickers()axion_futures_ticker()axion_futures_prices()axion_futures_gainers()axion_futures_losers()axion_futures_quote()axion_futures_list_*()

Indices

Market indices

axion_indices_tickers()axion_indices_ticker()axion_indices_prices()axion_indices_gainers()axion_indices_losers()axion_indices_quote()axion_indices_components()axion_indices_exposure()axion_indices_list_*()

Profiles

Company information

axion_profiles_profile()axion_profiles_info()axion_profiles_summary()axion_profiles_statistics()axion_profiles_recommendation()axion_profiles_calendar()

Financials

Income, balance sheet, cash flow, metrics

axion_financials_revenue()axion_financials_net_income()axion_financials_metrics()axion_financials_snapshot()axion_financials_eps()axion_financials_pe()axion_financials_market_cap()axion_financials_roe()axion_financials_enterprise_value()axion_financials_ebitda()axion_financials_debt_to_equity()axion_financials_balance_sheet()axion_financials_income_statement()axion_financials_cash_flow_statement()

Earnings

Earnings history, trends, reports, transcripts

axion_earnings_history()axion_earnings_trend()axion_earnings_index()axion_earnings_report()axion_earnings_transcript()axion_earnings_transcript_sentiment()

Filings

SEC filings, forms, search, documents

axion_filings_recent()axion_filings_history()axion_filings_list_forms()axion_filings_search()axion_filings_document_text()axion_filings_document_sentiment()

Insiders

Insider trading, ownership, funds

axion_insiders_funds()axion_insiders_individuals()axion_insiders_institutions()axion_insiders_ownership()axion_insiders_activity()axion_insiders_transactions()

Sentiment

Social, news, analyst sentiment

axion_sentiment_all()axion_sentiment_social()axion_sentiment_news()axion_sentiment_analyst()

Economic

Indicators, calendar, datasets, search

axion_econ_search()axion_econ_find()axion_econ_dataset()axion_econ_calendar()

ETF

ETF data, holdings, exposure, weights

axion_etfs_tickers()axion_etfs_ticker()axion_etfs_prices()axion_etfs_fund()axion_etfs_holdings()axion_etfs_holdings_all()axion_etfs_exposure()axion_etfs_weights()axion_etfs_quote()

ETF API

Comprehensive ETF data including fund information, holdings, exposure, weights, gainers, and losers.

Available Functions

FunctionDescriptionParameters
axion_etfs_tickers()Filtered ETF listcountry, exchange
axion_etfs_ticker()Current ETF quoteticker
axion_etfs_prices()Historical pricesticker, from, to, frame
axion_etfs_fund()Fund overview and detailsticker
axion_etfs_holdings()Top holdingsticker
axion_etfs_holdings_all()All holdingsticker
axion_etfs_exposure()Sector and asset exposureticker
axion_etfs_weights()Weight allocationsticker
axion_etfs_quote()Real-time ETF quoteticker
axion_etfs_gainers()Top gaining ETFsdays, limit
axion_etfs_losers()Top losing ETFsdays, limit
axion_etfs_list_market()Available marketsNone
axion_etfs_list_country()Available countriesNone
axion_etfs_list_currency()Available currenciesNone
axion_etfs_list_sector()Available sectorsNone
axion_etfs_list_industry()Available industriesNone
axion_etfs_list_type()Available typesNone
|

ETF Examples

// Get SPY ETF holdings
AxionResponse* holdings = axion_etfs_holdings(client, "SPY");
if (holdings && holdings->json) {
    printf("SPY holdings retrieved\n");
}
axion_response(holdings);

// Get all SPY ETF holdings
AxionResponse* allHoldings = axion_etfs_holdings_all(client, "SPY");
if (allHoldings && allHoldings->json) {
    printf("SPY all holdings retrieved\n");
}
axion_response(allHoldings);

// Get top gaining ETFs
AxionResponse* gainers = axion_etfs_gainers(client, 7, 10);
if (gainers && gainers->json) {
    printf("Top ETF gainers retrieved\n");
}
axion_response(gainers);

// Get ETF exposure
AxionResponse* exposure = axion_etfs_exposure(client, "QQQ");
if (exposure && exposure->json) {
    printf("QQQ exposure data retrieved\n");
}
axion_response(exposure);

Market Data APIs

All market data endpoints follow consistent patterns: tickers lists, individual ticker quotes, historical prices, gainers/losers, and metadata listings.

Stocks API

FunctionDescriptionParameters
axion_stocks_tickers()Filtered ticker listcountry, exchange
axion_stocks_ticker()Current quote for a tickerticker
axion_stocks_prices()Historical pricesticker, from, to, frame
axion_stocks_gainers()Top gainersdays, limit, market
axion_stocks_losers()Top losersdays, limit, market
axion_stocks_quote()Real-time stock quoteticker
axion_stocks_list_market()Available marketsNone
axion_stocks_list_country()Available countriesNone
axion_stocks_list_currency()Available currenciesNone
axion_stocks_list_sector()Available sectorsNone
axion_stocks_list_industry()Available industriesNone
axion_stocks_list_type()Available typesNone

Cryptocurrency API

FunctionDescriptionParameters
axion_crypto_tickers()List of crypto tickerstype (optional)
axion_crypto_ticker()Current quote (e.g., "BTC-USD")ticker
axion_crypto_prices()Historical pricesticker, from, to, frame
axion_crypto_gainers()Top gaining cryptocurrenciesdays, limit
axion_crypto_losers()Top losing cryptocurrenciesdays, limit
axion_crypto_quote()Real-time crypto quoteticker
axion_crypto_list_category()Available categoriesNone
axion_crypto_list_rating()Available ratingsNone
axion_crypto_list_type()Available typesNone

Forex API

FunctionDescriptionParameters
axion_forex_tickers()Filtered forex tickerscountry, exchange
axion_forex_ticker()Current forex quoteticker
axion_forex_prices()Historical forex pricesticker, from, to, frame
axion_forex_gainers()Top gaining currenciesdays, limit
axion_forex_losers()Top losing currenciesdays, limit
axion_forex_quote()Real-time forex quoteticker
axion_forex_list_exchange()Available exchangesNone
axion_forex_list_rating()Available ratingsNone
axion_forex_list_country()Available countriesNone

Futures API

FunctionDescriptionParameters
axion_indices_tickers()Filtered index listexchange
axion_indices_ticker()Current index valueticker
axion_indices_prices()Historical index dataticker, from, to, frame
axion_indices_gainers()Top gaining indicesdays, limit
axion_indices_losers()Top losing indicesdays, limit
axion_indices_quote()Real-time index quoteticker
axion_indices_list_exchange()Available exchangesNone
axion_indices_list_type()Available typesNone

Indices API

FunctionParametersDescription
axion_indices_tickers()exchangeFiltered indices list
axion_indices_ticker()tickerCurrent index quote
axion_indices_prices()ticker, from, to, frameHistorical index prices
axion_indices_gainers()days, limitTop gaining indices
axion_indices_losers()days, limitTop losing indices
axion_indices_quote()tickerReal-time index quote
axion_indices_components()tickerIndex constituent list
axion_indices_exposure()tickerIndex sector exposure
axion_indices_list_exchange()NoneAvailable exchanges
axion_indices_list_timezone()NoneAvailable timezones
axion_indices_list_country()NoneAvailable countries
|

Market Data Examples

// Get NASDAQ stocks
AxionResponse* tickers = axion_stocks_tickers(client, "US", "NASDAQ");

// Get Bitcoin quote
AxionResponse* btc = axion_crypto_ticker(client, "BTC-USD");

// Get historical prices for EUR/USD
AxionResponse* eur = axion_forex_prices(client, "EUR-USD",
    "2024-01-01", "2024-03-31", "daily");

// Get S&P 500 futures
AxionResponse* sp = axion_futures_ticker(client, "ES");

// Get top stock gainers
AxionResponse* gainers = axion_stocks_gainers(client, 7, 10, "US");

// Get S&P 500 components
AxionResponse* sp500 = axion_indices_components(client, "SPX");

Profiles API

Comprehensive company data and metadata.

FunctionParametersDescription
axion_profiles_profile()tickerBasic company profile
axion_profiles_info()tickerDetailed company information
axion_profiles_summary()tickerFinancial summary
axion_profiles_statistics()tickerKey statistics and ratios
axion_profiles_recommendation()tickerAnalyst recommendations
axion_profiles_calendar()tickerUpcoming events calendar
|

Profiles Example

AxionResponse* info = axion_profiles_info(client, "AAPL");
if (info && info->json) {
    cJSON* name = cJSON_GetObjectItem(info->json, "name");
    cJSON* sector = cJSON_GetObjectItem(info->json, "sector");
    printf("Company: %s\nSector: %s\n", 
           name->valuestring, sector->valuestring);
}
axion_response(info);

AxionResponse* recs = axion_profiles_recommendation(client, "AAPL");
// Process recommendations...
axion_response(recs);

Financials API

Detailed financial statements and metrics. Most functions accept an optional periods parameter to specify number of historical periods. Statement functions accept year and quarter parameters.

Available Functions

FunctionDescriptionParameters
axion_financials_revenue(ticker, periods)Revenue dataticker, periods
axion_financials_net_income(ticker, periods)Net incometicker, periods
axion_financials_total_assets(ticker, periods)Total assetsticker, periods
axion_financials_total_liabilities(ticker, periods)Total liabilitiesticker, periods
axion_financials_stockholders_equity(ticker, periods)Stockholders equityticker, periods
axion_financials_current_assets(ticker, periods)Current assetsticker, periods
axion_financials_current_liabilities(ticker, periods)Current liabilitiesticker, periods
axion_financials_operating_cash_flow(ticker, periods)Operating cash flowticker, periods
axion_financials_capital_expenditures(ticker, periods)CapExticker, periods
axion_financials_free_cash_flow(ticker, periods)Free cash flowticker, periods
axion_financials_shares_outstanding_basic(ticker, periods)Basic shares outstandingticker, periods
axion_financials_shares_outstanding_diluted(ticker, periods)Diluted shares outstandingticker, periods
axion_financials_metrics(ticker)Calculated financial metricsticker
axion_financials_snapshot(ticker)Financial snapshot overviewticker
axion_financials_eps(ticker, from, to)Earnings per shareticker, from, to
axion_financials_pe(ticker, from, to, frame)P/E ratioticker, from, to, frame
axion_financials_market_cap(ticker, from, to, frame)Market capitalizationticker, from, to, frame
axion_financials_roe(ticker, from, to)Return on equityticker, from, to
axion_financials_enterprise_value(ticker, from, to, frame)Enterprise valueticker, from, to, frame
axion_financials_ebitda(ticker, from, to)EBITDAticker, from, to
axion_financials_debt_to_equity(ticker, from, to)Debt-to-equity ratioticker, from, to
axion_financials_balance_sheet(client, ticker, year, quarter)Complete balance sheet statementclient, ticker, year, quarter
axion_financials_income_statement(client, ticker, year, quarter)Complete income statementclient, ticker, year, quarter
axion_financials_cash_flow_statement(client, ticker, year, quarter)Complete cash flow statementclient, ticker, year, quarter
|

Financials Example

// Get last 4 quarters of revenue
AxionResponse* revenue = axion_financials_revenue(client, "AAPL", 4);

// Get current metrics
AxionResponse* metrics = axion_financials_metrics(client, "AAPL");

if (metrics && metrics->json) {
    cJSON* pe = cJSON_GetObjectItem(metrics->json, "pe_ratio");
    cJSON* pb = cJSON_GetObjectItem(metrics->json, "pb_ratio");
    printf("P/E: %.2f, P/B: %.2f\n", 
           pe->valuedouble, pb->valuedouble);
}

// Get balance sheet for Q1 2024
AxionResponse* bs = axion_financials_balance_sheet(client, "AAPL", "2024", "Q1");
if (bs && bs->json) {
    printf("Balance sheet retrieved\n");
}
axion_response(bs);

axion_response(revenue);
axion_response(metrics);

Earnings API

Comprehensive earnings data including history, trends, detailed reports, and call transcripts.

FunctionDescriptionParameters
axion_futures_tickers()Filtered futures listtype, exchange
axion_futures_ticker()Current futures quoteticker
axion_futures_prices()Historical futures pricesticker, from, to, frame
axion_futures_quote()Real-time futures quoteticker
axion_futures_list_exchange()Available exchangesNone
axion_futures_list_type()Available typesNone
|

Earnings Example

// Get earnings history
AxionResponse* history = axion_earnings_history(client, "AAPL");

// Get Q1 2024 earnings report
AxionResponse* report = axion_earnings_report(client, "AAPL", "2024", "Q1");

if (report && report->json) {
    cJSON* eps = cJSON_GetObjectItem(report->json, "eps_actual");
    cJSON* revenue = cJSON_GetObjectItem(report->json, "revenue_actual");
    printf("EPS: %.2f, Revenue: %.2f\n", 
           eps->valuedouble, revenue->valuedouble);
}

// Get earnings call transcript
AxionResponse* transcript = axion_earnings_transcript(client, "AAPL", "2024", "Q1");
if (transcript && transcript->json) {
    printf("Transcript retrieved\n");
}
axion_response(transcript);

axion_response(history);
axion_response(report);

Filings API

SEC filings data with powerful search capabilities and document access.

FunctionParametersDescription
axion_filings_recent()ticker, form, limitList of filings for a ticker
axion_filings_history()ticker, form_type, start_date, end_dateFiltered forms for a ticker by date range
axion_filings_list_forms()NoneDescription of all form types
axion_filings_search()ticker, form, year, quarterSearch across all filings
axion_filings_document_text()document_idFull document text content
axion_filings_document_sentiment()document_idDocument sentiment analysis
|

Filings Example

// Get latest 10-K filings for Apple
AxionResponse* filings = axion_filings_recent(client, "AAPL", "10-K", 5);

// Search for all 10-Q filings in Q1 2024
AxionResponse* search = axion_filings_search(client, NULL, "10-Q", "2024", "Q1");

if (search && search->json) {
    cJSON* filings_array = search->json;
    int count = cJSON_GetArraySize(filings_array);
    printf("Found %d filings\n", count);
}

// Get document text
AxionResponse* doc = axion_filings_document_text(client, "doc_12345");
if (doc && doc->json) {
    printf("Document text retrieved\n");
}
axion_response(doc);

axion_response(filings);
axion_response(search);

Insiders API

Insider trading data including transactions, ownership, funds, and activity.

Available Functions

FunctionDescriptionParameters
axion_insiders_funds()Fund ownership dataticker
axion_insiders_individuals()Insider holders (individuals)ticker
axion_insiders_institutions()Institutional ownershipticker
axion_insiders_ownership()Major holders breakdownticker
axion_insiders_activity()Net share purchase activityticker
axion_insiders_transactions()Insider transactionsticker
|

Insiders Example

// Get recent insider transactions
AxionResponse* transactions = axion_insiders_transactions(client, "AAPL");

if (transactions && transactions->json) {
    cJSON* first = cJSON_GetArrayItem(transactions->json, 0);
    if (first) {
        cJSON* name = cJSON_GetObjectItem(first, "insider_name");
        cJSON* shares = cJSON_GetObjectItem(first, "shares");
        printf("%s traded %d shares\n", 
               name->valuestring, shares->valueint);
    }
}
axion_response(transactions);

Sentiment API

Multi-source sentiment analysis for stocks.

Available Functions

FunctionDescriptionParameters
axion_sentiment_all()Combined sentiment analysisticker
axion_sentiment_social()Social media sentimentticker
axion_sentiment_news()News-based sentimentticker
axion_sentiment_analyst()Analyst sentimentticker
|

Sentiment Example

AxionResponse* sentiment = axion_sentiment_all(client, "TSLA");
if (sentiment && sentiment->json) {
    cJSON* overall = cJSON_GetObjectItem(sentiment->json, "overall_score");
    cJSON* social = cJSON_GetObjectItem(sentiment->json, "social_score");
    cJSON* news = cJSON_GetObjectItem(sentiment->json, "news_score");
    
    printf("Overall: %.2f, Social: %.2f, News: %.2f\n",
           overall->valuedouble, social->valuedouble, news->valuedouble);
}
axion_response(sentiment);

News API

Financial news from multiple sources.

Available Functions

FunctionDescriptionParameters
axion_news_general()General market news feedNone
axion_news_company()News for a specific companyticker
axion_news_country()News by countrycountry
axion_news_category()News by categorycategory
|

News Example

// Get latest news for Apple
AxionResponse* news = axion_news_company(client, "AAPL");
if (news && news->json) {
    cJSON* first = cJSON_GetArrayItem(news->json, 0);
    if (first) {
        cJSON* title = cJSON_GetObjectItem(first, "title");
        cJSON* source = cJSON_GetObjectItem(first, "source");
        printf("%s - %s\n", source->valuestring, title->valuestring);
    }
}
axion_response(news);

Economic API

Macroeconomic indicators, datasets, AI-powered search, and economic calendar.

Available Functions

FunctionDescriptionParameters
axion_econ_search()Search for economic seriesquery
axion_econ_find()AI-powered FRED series searchquery
axion_econ_dataset()Get series observationsseries_id
axion_econ_calendar()Economic calendar with filtersfrom, to, country, min_importance, currency, category
|

Economic Example

// Get economic calendar for US with min importance 3
AxionResponse* calendar = axion_econ_calendar(client, 
    "2024-03-01", "2024-03-31", "US", 3, NULL, NULL);

// Get GDP data
AxionResponse* gdp = axion_econ_dataset(client, "GDP");

// AI-powered economic search
AxionResponse* found = axion_econ_find(client, "US GDP growth rate 2024");
if (found && found->json) {
    printf("Economic data found\n");
}
axion_response(found);

axion_response(calendar);
axion_response(gdp);

ESG API

Environmental, Social, Governance data

axion_esg_data(client, ticker)

Returns ESG scores and metrics for a company

Credit API

Credit ratings and entity search

axion_credit_search(client, query)axion_credit_ratings(client, entity_id)

Supply Chain API

Customers, peers, suppliers

axion_supply_chain_customers(client, ticker)axion_supply_chain_peers(client, ticker)axion_supply_chain_suppliers(client, ticker)

Web Traffic API

Website traffic metrics

axion_webtraffic_traffic(client, ticker)

Error Handling

Every API call returns an AxionResponse* that must be checked for errors.

CheckDescription
!responseFatal error (allocation failure)
response->errorAPI error message
response->http_status >= 400HTTP error
!response->jsonJSON parse failure
|

Robust error handling

AxionResponse* resp = axion_esg_data(client, "INVALID");
if (!resp) {
    fprintf(stderr, "Fatal: allocation failed\n");
    return;
}

if (resp->error) {
    fprintf(stderr, "API error: %s\n", resp->error);
} else if (resp->http_status >= 400) {
    fprintf(stderr, "HTTP %d error\n", resp->http_status);
} else if (!resp->json) {
    fprintf(stderr, "Invalid JSON response\n");
} else {
    // Success - process resp->json
    cJSON* score = cJSON_GetObjectItem(resp->json, "score");
    // ...
}

axion_response(resp);

Memory Management

The SDK uses manual memory management. Every AxionResponse* must be freed withaxion_response(). The client must be freed last.

Always free responses

Use axion_response() for every response.

Free client last

All responses freed before axion_client().

NULL safe

Free functions accept NULL.

Thread safety

One client per thread, or use mutex.

|

Cleanup with goto pattern

AxionClient* client = NULL;
AxionResponse* r1 = NULL;
AxionResponse* r2 = NULL;

client = axion_init("your-api-key");
if (!client) goto cleanup;

r1 = axion_stocks_ticker(client, "AAPL");
if (!r1 || r1->error) goto cleanup;

r2 = axion_esg_data(client, "AAPL");
if (!r2 || r2->error) goto cleanup;

// Process responses...

cleanup:
    axion_response(r1);
    axion_response(r2);
    axion_client(client);

Performance Tips

Optimize for high-frequency or embedded environments.

Reuse client

One client instance per thread reduces curl init overhead.

Batch calls

Group API calls to reuse connections.

Free early

Free responses immediately after processing.

Date formats

Always use YYYY-MM-DD format for dates.

|

Batch processing pattern

// Fire all requests first
const char* tickers[] = {"AAPL", "MSFT", "GOOGL"};
AxionResponse* resps[3];

for (int i = 0; i < 3; i++) {
    resps[i] = axion_stocks_ticker(client, tickers[i]);
}

// Then process and free
for (int i = 0; i < 3; i++) {
    if (resps[i] && resps[i]->json && !resps[i]->error) {
        cJSON* price = cJSON_GetObjectItem(resps[i]->json, "price");
        printf("%s: %.2f\n", tickers[i], price->valuedouble);
    }
    axion_response(resps[i]);
}

Complete Example

A comprehensive program that fetches stock data, ESG scores, and financial metrics for multiple companies.

#include "axion.h"
#include <stdio.h>
#include <string.h>

typedef struct {
    char ticker[16];
    double price;
    double esg_score;
    double pe_ratio;
    double market_cap;
} CompanyAnalysis;

int main() {
    AxionClient* client = axion_init("your-api-key-here");
    if (!client) {
        fprintf(stderr, "Failed to initialize client\n");
        return 1;
    }

    const char* tickers[] = {"AAPL", "MSFT", "GOOGL", "TSLA", "AMZN"};
    CompanyAnalysis results[5] = {0};
    
    for (int i = 0; i < 5; i++) {
        strcpy(results[i].ticker, tickers[i]);
        
        // Get stock quote
        AxionResponse* quote = axion_stocks_ticker(client, tickers[i]);
        if (quote && quote->json && !quote->error) {
            cJSON* price = cJSON_GetObjectItem(quote->json, "price");
            if (cJSON_IsNumber(price)) {
                results[i].price = price->valuedouble;
            }
        }
        axion_response(quote);
        
        // Get ESG data
        AxionResponse* esg = axion_esg_data(client, tickers[i]);
        if (esg && esg->json && !esg->error) {
            cJSON* score = cJSON_GetObjectItem(esg->json, "score");
            if (cJSON_IsNumber(score)) {
                results[i].esg_score = score->valuedouble;
            }
        }
        axion_response(esg);
        
        // Get financial metrics
        AxionResponse* metrics = axion_financials_metrics(client, tickers[i]);
        if (metrics && metrics->json && !metrics->error) {
            cJSON* pe = cJSON_GetObjectItem(metrics->json, "pe_ratio");
            cJSON* mcap = cJSON_GetObjectItem(metrics->json, "market_cap");
            if (cJSON_IsNumber(pe)) results[i].pe_ratio = pe->valuedouble;
            if (cJSON_IsNumber(mcap)) results[i].market_cap = mcap->valuedouble;
        }
        axion_response(metrics);
    }
    
    // Print results
    printf("\n=== Company Analysis ===\n\n");
    for (int i = 0; i < 5; i++) {
        printf("%s:\n", results[i].ticker);
        printf("  Price: $%.2f\n", results[i].price);
        printf("  ESG Score: %.1f\n", results[i].esg_score);
        printf("  P/E Ratio: %.2f\n", results[i].pe_ratio);
        printf("  Market Cap: $%.2fB\n\n", results[i].market_cap / 1e9);
    }
    
    axion_client(client);
    return 0;
}

Axion JavaScript/TypeScript SDK

The Axion JavaScript SDK provides a comprehensive TypeScript-first wrapper for interacting with the Axion Financial API. This SDK offers full type safety, async/await support, and automatic error handling for financial data including ESG scores, stock prices, cryptocurrency data, forex, futures, indices, ETFs, economic indicators, company financials, insider transactions, SEC filings, earnings transcripts, news, sentiment analysis, supply chain, web traffic, and credit ratings.

Installation

Install the SDK via npm, yarn, or pnpm. The package includes both CommonJS and ES module builds, with full TypeScript definitions.

|

npm / yarn / pnpm

# npm
npm install @axionquant/sdk

# yarn
yarn add @axionquant/sdk

# pnpm
pnpm add @axionquant/sdk

Quick Start

Initialize the client and start fetching data. All methods return Promises and are fully typed.

Steps

  1. Import the Axion class
  2. Create a client with your API key
  3. Call methods on category properties (e.g., client.esg.data())
  4. Use async/await to handle responses
|

Quick Start (TypeScript)

import { Axion } from '@axionquant/sdk';

const client = new Axion('your_api_key_here');

// Get ESG data for Apple
const esgData = await client.esg.data('AAPL');
console.log(esgData);

// Get stock prices for Microsoft
const prices = await client.stocks.prices('MSFT', {
  from: '2024-01-01',
  to: '2024-03-01'
});
console.log(prices);

// Get economic indicators
const gdp = await client.econ.dataset('GDP_USA');

// Get company news
const news = await client.news.company('AAPL');

// Get ETF holdings
const holdings = await client.etfs.holdings('SPY');

Client Initialization

The Axion client can be initialized with or without an API key. When no key is provided at construction, it must be included in the Authorization header of each request.

Constructor Parameters

ParameterTypeRequiredDescription
apiKeystringOptionalYour Axion API key. If omitted, you must provide it per request.
|

TypeScript Example

import { Axion } from '@axionquant/sdk';
import type { ApiResponse } from '@axionquant/sdk';

const client = new Axion('your_api_key_here');

async function fetchFinancialData() {
  try {
    const esgData: ApiResponse = await client.esg.data('AAPL');
    const stockPrices: ApiResponse = await client.stocks.prices('MSFT');
    return { esgData, stockPrices };
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

API Categories

The SDK is organized into 18 specialized API classes, each accessible as a property of the main client. All methods are promise-based and fully typed.

client.credit

Credit ratings & entity search

credit.search(query)credit.ratings(entityId)

client.esg

Environmental, Social, Governance

esg.data(ticker)

client.etfs

ETF fund data, holdings, exposure

etfs.tickers(params?)etfs.ticker(ticker)etfs.prices(ticker, params?)etfs.quote(ticker)etfs.fund(ticker)etfs.holdings(ticker)etfs.holdingsAll(ticker)etfs.weights(ticker)etfs.exposure(ticker)etfs.gainers(params?)etfs.losers(params?)etfs.list(column)

client.supplyChain

Customers, peers, suppliers

supplyChain.customers(ticker)supplyChain.peers(ticker)supplyChain.suppliers(ticker)

client.stocks

Stock quotes, prices, tickers

stocks.tickers(params?)stocks.ticker(ticker)stocks.prices(ticker, params?)stocks.quote(ticker)stocks.gainers(params?)stocks.losers(params?)stocks.list(column)

client.crypto

Cryptocurrency data

crypto.tickers(params?)crypto.ticker(ticker)crypto.prices(ticker, params?)crypto.quote(ticker)crypto.gainers(params?)crypto.losers(params?)crypto.list(column)

client.profiles

Company profiles, info, statistics

profiles.profile(ticker)profiles.info(ticker)profiles.summary(ticker)profiles.statistics(ticker)profiles.recommendation(ticker)profiles.calendar(ticker)

client.sentiment

News & social sentiment

sentiment.all(ticker)sentiment.social(ticker)sentiment.news(ticker)sentiment.analyst(ticker)

client.financials

Comprehensive financial metrics

financials.revenue(ticker, params?)financials.balanceSheet(ticker, params?)financials.incomeStatement(ticker, params?)financials.cashFlowStatement(ticker, params?)financials.metrics(ticker)financials.snapshot(ticker)financials.dcfValue(ticker)financials.dcfRate(ticker)financials.eps(ticker, params?)financials.pe(ticker, params?)financials.marketCap(ticker, params?)financials.roe(ticker, params?)financials.enterpriseValue(ticker, params?)financials.ebitda(ticker, params?)financials.debtToEquity(ticker, params?)

client.earnings

Earnings history, trends, reports

earnings.history(ticker)earnings.trend(ticker)earnings.index(ticker)earnings.report(ticker, params)earnings.transcript(ticker, params)earnings.transcriptSentiment(id)

client.filings

SEC filings and forms

filings.recent(ticker, params?)filings.history(ticker, formType, params?)filings.listForms()filings.search(params)filings.documentText(documentId)filings.documentSentiment(documentId)

client.insiders

Insider transactions & ownership

insiders.funds(ticker)insiders.individuals(ticker)insiders.institutions(ticker)insiders.ownership(ticker)insiders.activity(ticker)insiders.transactions(ticker)

client.forex

Foreign exchange currency data

forex.tickers(params?)forex.ticker(ticker)forex.prices(ticker, params?)forex.quote(ticker)forex.gainers(params?)forex.losers(params?)forex.list(column)

client.futures

Commodity & financial futures

futures.tickers(params?)futures.ticker(ticker)futures.prices(ticker, params?)futures.quote(ticker)futures.gainers(params?)futures.losers(params?)futures.list(column)

client.indices

Stock market indices

indices.tickers(params?)indices.ticker(ticker)indices.prices(ticker, params?)indices.quote(ticker)indices.components(ticker)indices.exposure(ticker)indices.gainers(params?)indices.losers(params?)indices.list(column)

client.econ

Economic indicators & calendar

econ.find(query)econ.search(query)econ.dataset(seriesId)econ.calendar(params?)

client.news

Financial news by company/country

news.general()news.company(ticker)news.country(country)news.category(category)

client.webTraffic

Website traffic analytics

webTraffic.traffic(ticker)

Profiles API

client.profiles

Comprehensive company profiles, statistics, recommendations, and calendar events.

Available Methods

MethodDescriptionParameters
profile(ticker)Get asset profileticker: string
recommendation(ticker)Get recommendation trendsticker: string
statistics(ticker)Get key statisticsticker: string
summary(ticker)Get summary detailsticker: string
calendar(ticker)Get earnings & dividend calendarticker: string
info(ticker)Get company info (summary profile)ticker: string
|

Profiles API - Example

// Company profile
const profile = await client.profiles.profile('AAPL');
console.log(`Company: ${profile.name}`);

// Recommendation trends
const recommendations = await client.profiles.recommendation('AAPL');
console.log(`Strong Buy: ${recommendations.strongBuy}`);

// Key statistics
const stats = await client.profiles.statistics('AAPL');
console.log(`Market Cap: ${stats.marketCap}`);

// Calendar events
const calendar = await client.profiles.calendar('AAPL');
console.log(`Next Earnings: ${calendar.earnings[0].date}`);

Financials API

client.financials

Detailed financial metrics, statements, and calculated ratios.

Available Methods

MethodDescriptionParameters
balanceSheet(ticker, params?)Balance sheet statementticker: string, params?: { year?: string, quarter?: string }
incomeStatement(ticker, params?)Income statementticker: string, params?: { year?: string, quarter?: string }
cashFlowStatement(ticker, params?)Cash flow statementticker: string, params?: { year?: string, quarter?: string }
revenue(ticker, params?)Revenue dataticker: string, params?: { periods?: number }
netIncome(ticker, params?)Net incometicker: string, params?: { periods?: number }
totalAssets(ticker, params?)Total assetsticker: string, params?: { periods?: number }
totalLiabilities(ticker, params?)Total liabilitiesticker: string, params?: { periods?: number }
stockholdersEquity(ticker, params?)Stockholders equityticker: string, params?: { periods?: number }
currentAssets(ticker, params?)Current assetsticker: string, params?: { periods?: number }
currentLiabilities(ticker, params?)Current liabilitiesticker: string, params?: { periods?: number }
operatingCashFlow(ticker, params?)Operating cash flowticker: string, params?: { periods?: number }
capitalExpenditures(ticker, params?)CapExticker: string, params?: { periods?: number }
freeCashFlow(ticker, params?)Free cash flowticker: string, params?: { periods?: number }
sharesOutstandingBasic(ticker, params?)Basic sharesticker: string, params?: { periods?: number }
sharesOutstandingDiluted(ticker, params?)Diluted sharesticker: string, params?: { periods?: number }
metrics(ticker)Calculated metricsticker: string
snapshot(ticker)Financial snapshotticker: string
dcfValue(ticker)DCF valuationticker: string
dcfRate(ticker)Discount rate / WACCticker: string
|

Financials API - Example

// Revenue data for last 4 quarters
const revenue = await client.financials.revenue('AAPL', { periods: 4 });
console.log('Quarterly Revenue:', revenue);

// Key financial metrics
const metrics = await client.financials.metrics('AAPL');
console.log(`P/E Ratio: ${metrics.pe_ratio}`);
console.log(`ROE: ${metrics.return_on_equity}`);

// Complete financial snapshot
const snapshot = await client.financials.snapshot('AAPL');
console.log(snapshot);

// DCF analysis
const dcfValue = await client.financials.dcfValue('AAPL');
console.log(`Fair Price: ${dcfValue.fairPrice}, Recommendation: ${dcfValue.recommendation}`);

const dcfRate = await client.financials.dcfRate('AAPL');
console.log(`WACC: ${(dcfRate.wacc * 100).toFixed(2)}%`);

// Financial statements
const balanceSheet = await client.financials.balanceSheet('AAPL');
const income = await client.financials.incomeStatement('AAPL');
const cashflow = await client.financials.cashFlowStatement('AAPL');

Earnings API

client.earnings

Historical earnings data, trends, and detailed reports.

Available Methods

MethodDescriptionParameters
history(ticker)Earnings historyticker: string
trend(ticker)Earnings trendticker: string
index(ticker)Index trendticker: string
report(ticker, params)Detailed earnings reportticker: string, params: { year: string, quarter: string }
transcript(ticker, params)Earnings call transcriptticker: string, params: { year: string, quarter: string }
transcriptSentiment(id)Earnings transcript sentimentid: string
|

Earnings API - Example

// Earnings history
const history = await client.earnings.history('MSFT');
console.log(`EPS Q1: ${history[0].eps}`);

// Specific quarter report
const report = await client.earnings.report('MSFT', {
  year: '2024',
  quarter: 'Q1'
});
console.log(`Revenue: ${report.revenue}`);
console.log(`EPS: ${report.eps}`);

// Earnings call transcript
const transcript = await client.earnings.transcript('MSFT', {
  year: '2024',
  quarter: 'Q1'
});
console.log(`Transcript: ${transcript.text.substring(0, 200)}...`);

// Transcript sentiment
const sentiment = await client.earnings.transcriptSentiment('transcript_id');
console.log(`Sentiment: ${sentiment.score}`);

Filings API

client.filings

SEC filings search and retrieval.

Available Methods

MethodDescriptionParameters
recent(ticker, params?)Get recent filingsticker: string, params?: { limit?: number, form?: string }
history(ticker, formType, params?)Get specific form type by date rangeticker: string, formType: string, params?: { startDate?: string, endDate?: string }
listForms()List available form typesnone
search(params)Search filings by year/quarterparams: { ticker?: string, form?: string, year: string, quarter: string }
documentText(documentId)Get raw text of a filing documentdocumentId: string
documentSentiment(documentId)Get sentiment analysis of a filingdocumentId: string
|

Filings API - Example

// Get recent 10-K filings
const filings = await client.filings.recent('AAPL', { 
  form: '10-K', 
  limit: 3 
});

// Search for Q1 2024 filings
const searchResults = await client.filings.search({
  ticker: 'AAPL',
  year: '2024',
  quarter: 'Q1'
});

// Get all 10-Q filings for Q1 2024
const forms = await client.filings.history('AAPL', '10-Q', {
  startDate: '2024-01-01',
  endDate: '2024-03-31'
});

// Get raw document text and sentiment
const text = await client.filings.documentText('document_id_here');
const sentiment = await client.filings.documentSentiment('document_id_here');
console.log(`Sentiment: ${sentiment.score}`);

Insiders API

client.insiders

Insider ownership, transactions, and institutional holdings.

Available Methods

MethodDescriptionParameters
funds(ticker)Fund ownership dataticker: string
individuals(ticker)Insider holders (individuals)ticker: string
institutions(ticker)Institutional ownershipticker: string
ownership(ticker)Major holders breakdownticker: string
activity(ticker)Net share purchase activityticker: string
transactions(ticker)Insider transactionsticker: string
|

Insiders API - Example

// Institutional ownership
const institutions = await client.insiders.institutions('AAPL');
console.log(`Top Holder: ${institutions[0].name} (${institutions[0].shares} shares)`);

// Recent insider transactions
const transactions = await client.insiders.transactions('AAPL');
transactions.slice(0,5).forEach(t => {
  console.log(`${t.insider}: ${t.shares} shares ${t.type}`);
});

// Ownership breakdown
const ownership = await client.insiders.ownership('AAPL');
console.log(`Insider Ownership: ${ownership.insider_percent}%`);

Web Traffic API

client.webTraffic

Website traffic data and analytics for companies.

Available Methods

MethodDescriptionParameters
traffic(ticker)Get web traffic dataticker: string
|

WebTraffic API - Example

// Get web traffic for Amazon
const traffic = await client.webTraffic.traffic('AMZN');
console.log(`Monthly Visits: ${traffic.monthly_visits}`);
console.log(`YoY Growth: ${traffic.yoy_growth}%`);

ETF API

client.etfs

ETF tickers, quotes, prices, fund details, holdings, weights, exposure, gainers/losers, and metadata listings.

Available Methods

MethodDescriptionParameters
tickers(params?)Filtered list of ETF tickersparams?: { country?: string, exchange?: string }
ticker(ticker)Current quote for a single ETFticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
fund(ticker)Fund overview and detailsticker: string
holdings(ticker)Top holdings breakdownticker: string
holdingsAll(ticker)All holdings with weightsticker: string
weights(ticker)Fund allocation weightsticker: string
exposure(ticker)Exposure analysisticker: string
gainers(params?)Top gaining ETFsparams?: { days?: number, limit?: number }
losers(params?)Top losing ETFsparams?: { days?: number, limit?: number }
list(column)List metadata by columncolumn: string
|

ETF API - Example

// All US ETFs
const usEtfs = await client.etfs.tickers({ country: 'US' });

// SPY quote
const spyQuote = await client.etfs.ticker('SPY');
console.log(`SPY: $${spyQuote.price}`);

// Fund details and holdings
const spyFund = await client.etfs.fund('SPY');
const spyHoldings = await client.etfs.holdings('SPY');
const spyAllHoldings = await client.etfs.holdingsAll('SPY');

// Historical prices
const spyPrices = await client.etfs.prices('SPY', {
  from: '2024-01-01',
  to: '2024-03-31'
});

Stocks API

client.stocks

Access stock tickers, real-time quotes, historical price data, gainers/losers, and market metadata.

Available Methods

MethodDescriptionParameters
tickers(params?)Filtered list of stock tickersparams?: { country?: string, exchange?: string }
ticker(ticker)Current quote for a single symbolticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
gainers(params?)Top gaining stocksparams?: { days?: number, limit?: number, market?: string }
losers(params?)Top losing stocksparams?: { days?: number, limit?: number, market?: string }
list(column)List metadata by columncolumn: string
|

Stocks API - Example

// All US tickers
const usStocks = await client.stocks.tickers({ country: 'US' });

// Apple quote
const appleQuote = await client.stocks.ticker('AAPL');
console.log(`Price: ${appleQuote.price}`);

// Historical weekly prices for Microsoft
const msftPrices = await client.stocks.prices('MSFT', {
  from: '2024-01-01',
  to: '2024-03-31',
  frame: 'weekly'
});

// Top gainers this week
const gainers = await client.stocks.gainers({ days: 7, limit: 10 });

// List available sectors
const sectors = await client.stocks.list('sector');

Cryptocurrency API

client.crypto

Cryptocurrency tickers, real-time quotes, historical price data, gainers/losers, and metadata listings.

Available Methods

MethodDescriptionParameters
tickers(params?)Get all crypto tickersparams?: { type?: string }
ticker(ticker)Get quote by symbolticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
gainers(params?)Top gaining cryptocurrenciesparams?: { days?: number, limit?: number }
losers(params?)Top losing cryptocurrenciesparams?: { days?: number, limit?: number }
list(column)List metadata by columncolumn: string
|

Crypto API - Example

// All cryptocurrencies
const allCrypto = await client.crypto.tickers();

// Bitcoin quote
const btc = await client.crypto.ticker('BTC-USD');
console.log(`Bitcoin: $${btc.price}`);

// Ethereum historical daily prices
const ethPrices = await client.crypto.prices('ETH-USD', {
  from: '2024-01-01',
  to: '2024-03-31',
  frame: 'daily'
});

// Top crypto gainers
const topGainers = await client.crypto.gainers({ days: 1, limit: 5 });

Economic API

client.econ

Economic indicators, AI-powered FRED search, datasets, and calendar events.

Available Methods

MethodDescriptionParameters
find(query)AI-powered FRED series searchquery: string
search(query)Search for economic seriesquery: string
dataset(seriesId)Get series observationsseriesId: string
calendar(params?)Economic calendar with filtersparams?: { from?: string, to?: string, country?: string, minImportance?: number, currency?: string, category?: string, limit?: number }
|

Economic API - Example

// AI-powered FRED series search
const series = await client.econ.find('US GDP quarterly');

// Search for inflation series
const inflationSeries = await client.econ.search('inflation');

// Get GDP dataset
const gdpData = await client.econ.dataset('GDP_USA');

// Important US economic events this month
const calendar = await client.econ.calendar({
  from: '2024-04-01',
  to: '2024-04-30',
  country: 'US',
  minImportance: 3
});

Forex API

client.forex

Foreign exchange currency tickers, quotes, historical prices, gainers/losers, and metadata listings.

Available Methods

MethodDescriptionParameters
tickers(params?)Filtered list of forex pairsparams?: { country?: string, exchange?: string }
ticker(ticker)Current quote for a currency pairticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
gainers(params?)Top gaining currency pairsparams?: { days?: number, limit?: number }
losers(params?)Top losing currency pairsparams?: { days?: number, limit?: number }
list(column)List metadata by columncolumn: string
|

Forex API - Example

// All EUR forex pairs
const eurPairs = await client.forex.tickers({ country: 'EUR' });

// EUR/USD quote
const eurusd = await client.forex.ticker('EUR-USD');
console.log(`EUR/USD: ${eurusd.price}`);

// Historical prices
const eurGbpPrices = await client.forex.prices('EUR-GBP', {
  from: '2024-01-01',
  to: '2024-03-31',
  frame: 'daily'
});

Futures API

client.futures

Commodity and financial futures tickers, quotes, historical prices, gainers/losers, and metadata listings.

Available Methods

MethodDescriptionParameters
tickers(params?)Filtered list of futures tickersparams?: { exchange?: string }
ticker(ticker)Current quote for a futures contractticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
gainers(params?)Top gaining futures contractsparams?: { days?: number, limit?: number }
losers(params?)Top losing futures contractsparams?: { days?: number, limit?: number }
list(column)List metadata by columncolumn: string
|

Futures API - Example

// Crude oil futures quote
const crudeOil = await client.futures.ticker('CL');
console.log(`Crude Oil: $${crudeOil.price}`);

// Historical gold futures prices
const goldPrices = await client.futures.prices('GC', {
  from: '2024-01-01',
  to: '2024-03-31',
  frame: 'daily'
});

Indices API

client.indices

Stock market indices tickers, quotes, historical prices, components, exposure analysis, gainers/losers, and metadata listings.

Available Methods

MethodDescriptionParameters
tickers(params?)Filtered list of indicesparams?: { exchange?: string }
ticker(ticker)Current quote for an indexticker: string
prices(ticker, params?)Historical pricesticker: string, params?: { from?: string, to?: string, frame?: string }
quote(ticker)Real-time quote dataticker: string
components(ticker)Get index constituent holdingsticker: string
exposure(ticker)Which indices hold a given tickerticker: string
gainers(params?)Top gaining indicesparams?: { days?: number, limit?: number }
losers(params?)Top losing indicesparams?: { days?: number, limit?: number }
list(column)List metadata by columncolumn: string
|

Indices API - Example

// S&P 500 quote
const spx = await client.indices.ticker('SPX');
console.log(`S&P 500: ${spx.price}`);

// Dow Jones components
const dowComponents = await client.indices.components('DJI');
console.log(`Components: ${dowComponents.length}`);

// Which indices hold AAPL
const aaplExposure = await client.indices.exposure('AAPL');
console.log(`Found in ${aaplExposure.indices.length} indices`);

News API

client.news

Financial news retrieval by company, country, and category, plus general market news.

Available Methods

MethodDescriptionParameters
general()General market news feednone
company(ticker)News for a specific companyticker: string
country(country)News by countrycountry: string
category(category)News by categorycategory: string
|

News API - Example

// General market news
const marketNews = await client.news.general();
console.log(`Latest: ${marketNews.articles[0].headline}`);

// News for Apple
const aaplNews = await client.news.company('AAPL');

// News by country
const ukNews = await client.news.country('GB');

Complete Example

A comprehensive TypeScript application demonstrating multiple API calls, error handling, and portfolio monitoring.

import { Axion } from '@axionquant/sdk';

class FinancialAnalyst {
  private client: Axion;

  constructor(apiKey: string) {
    this.client = new Axion(apiKey);
  }

  async analyzeCompany(ticker: string) {
    try {
      const [profile, esg, quote, sentiment, financials] = await Promise.all([
        this.client.profiles.profile(ticker),
        this.client.esg.data(ticker),
        this.client.stocks.ticker(ticker),
        this.client.sentiment.all(ticker),
        this.client.financials.snapshot(ticker)
      ]);

      console.log(`${profile.name}: $${quote.price} | ESG: ${esg.score} | Sentiment: ${sentiment.overall_score}`);
      console.log(`P/E: ${financials.pe_ratio} | Revenue: ${financials.revenue}`);
      
      return { profile, esg, quote, sentiment, financials };
    } catch (error) {
      console.error(`Failed to analyze ${ticker}:`, error);
      return null;
    }
  }

  async monitorPortfolio(tickers: string[]) {
    setInterval(async () => {
      const updates = await Promise.all(
        tickers.map(t => this.client.stocks.quote(t))
      );
      console.log(new Date().toLocaleTimeString());
      updates.forEach(u => 
        console.log(`${u.symbol}: $${u.price} (${u.change_percent}%)`)
      );
    }, 60000); // every minute
  }

  async getEconomicInsights() {
    const gdp = await this.client.econ.dataset('GDP_USA');
    const calendar = await this.client.econ.calendar({
      country: 'US',
      minImportance: 3
    });
    return { gdp, calendar };
  }

  async getETFData(ticker: string) {
    const [fund, holdings, weights] = await Promise.all([
      this.client.etfs.fund(ticker),
      this.client.etfs.holdings(ticker),
      this.client.etfs.weights(ticker)
    ]);
    return { fund, holdings, weights };
  }
}

// Usage
const analyst = new FinancialAnalyst(process.env.AXION_API_KEY!);
analyst.analyzeCompany('AAPL');
analyst.monitorPortfolio(['AAPL', 'MSFT', 'GOOGL']);
analyst.getEconomicInsights();
analyst.getETFData('SPY');

Error Handling

The SDK throws descriptive errors that can be caught and handled gracefully.

Error Types

Error PatternDescription
HTTP Error {status}: {message}Client or server error with status code
Connection ErrorNetwork failure reaching the API
Authentication requiredNo API key provided to client
Request ErrorInvalid parameters or request setup
|

Error handling with retry

try {
  const data = await client.esg.data('INVALID');
} catch (error) {
  if (error.message.includes('404')) {
    console.log('Ticker not found');
  } else if (error.message.includes('429')) {
    // Rate limit - exponential backoff
    await delay(1000);
    return fetchWithRetry();
  } else if (error.message.includes('Authentication')) {
    console.error('API key missing - provide one to the client');
  } else if (error.message.includes('Connection')) {
    console.error('Network error - check your connection');
  }
  throw error;
}

TypeScript Support

The SDK is written in TypeScript and provides complete type definitions.

Complete Type Safety

All methods have full parameter and return types.

Auto-completion

IDE support for all methods and parameters.

Custom Type Extensions

Easily extend or override types for your domain.

|

TypeScript example

import { Axion } from '@axionquant/sdk';
import type { ApiResponse } from '@axionquant/sdk';
import SEOMetadata from '@/components/SEOMetadata';

interface CustomESG {
  score: number;
  grade: string;
  environmental: number;
}

class Analyst {
  client = new Axion(process.env.API_KEY!);

  async getESG(ticker: string): Promise<CustomESG> {
    const data = await this.client.esg.data(ticker);
    return {
      score: data.score,
      grade: data.grade,
      environmental: data.environmental_score
    };
  }
}

Axion Python SDK

The Axion Python SDK provides a comprehensive wrapper for interacting with the Axion Financial API. This SDK simplifies access to financial data including ESG scores, stock prices, cryptocurrency data, economic indicators, company financials, insider trading, SEC filings, and more. All methods return normalized Python data structures with proper type coercion.

Installation

Install the SDK via pip, or clone the repository for development.

|

pip / GitHub

# Install via pip
pip install axionquant-sdk

# Or clone from GitHub
git clone https://github.com/axionquant/python-sdk.git
cd python-sdk
pip install -e .

Quick Start

Initialize the client and start fetching data. All methods return normalized Python objects.

Steps

  1. Import the Axion class from axion
  2. Create a client with your API key
  3. Call methods on category attributes (e.g., client.stocks.quote("AAPL"))
  4. Use the returned dict/list directly (numbers, booleans are already converted)
|

Quick Start (Python)

from axion import Axion

# Initialize client
client = Axion(api_key="your_api_key_here")

# Get stock data
quote = client.stocks.quote("AAPL")
print(f"Apple price: {quote['price']}")

# Get ESG data
esg = client.esg.data("AAPL")
print(f"ESG Score: {esg['score']}")

# Get company profile
profile = client.profiles.info("AAPL")
print(f"Company: {profile['name']}")

Client Initialization

The Axion client requires an API key for authentication. The SDK is organized into 18 specialized API classes, accessible as attributes of the main client.

Constructor Parameters

ParameterTypeRequiredDescription
api_keystrOptional*Your Axion API key. If omitted, it must be provided in the Authorization header per request, but most endpoints require authentication.
|

Initialization example

from axion import Axion

# Recommended: set API key once
client = Axion(api_key="your_api_key_here")

# All API categories are now available
credit = client.credit.search("Apple")
esg = client.esg.data("AAPL")
stocks = client.stocks.quote("AAPL")
crypto = client.crypto.quote("BTC-USD")

API Categories

The SDK is organized into 18 specialized API classes, each handling a specific data domain. All API classes are accessible as attributes of the main client.

client.credit

Credit ratings & entity search

credit.search()credit.ratings()

client.esg

Environmental, Social, Governance

esg.data()

client.etfs

ETF fund data, holdings, exposure

etfs.tickers()etfs.ticker()etfs.prices()etfs.fund()etfs.holdings()etfs.holdings_all()etfs.exposure()etfs.weights()etfs.gainers()etfs.losers()etfs.quote()

client.supply_chain

Customers, peers, suppliers

supply_chain.customers()supply_chain.peers()supply_chain.suppliers()

client.stocks

Stock quotes, prices, tickers

stocks.tickers()stocks.ticker()stocks.quote()stocks.prices()stocks.gainers()stocks.losers()

client.crypto

Cryptocurrency data

crypto.tickers()crypto.ticker()crypto.quote()crypto.prices()crypto.gainers()crypto.losers()

client.forex

Foreign exchange currency data

forex.tickers()forex.ticker()forex.quote()forex.prices()forex.gainers()forex.losers()

client.futures

Commodity & financial futures

futures.tickers()futures.ticker()futures.quote()futures.prices()futures.gainers()futures.losers()

client.indices

Stock market indices

indices.tickers()indices.ticker()indices.quote()indices.prices()indices.gainers()indices.losers()indices.components()indices.exposure()

client.econ

Economic indicators & calendar

econ.find()econ.search()econ.dataset()econ.calendar()

client.news

Financial news articles

news.general()news.company()news.country()news.category()

client.sentiment

News & social sentiment

sentiment.all()sentiment.social()sentiment.news()sentiment.analyst()

client.profiles

Company profiles & summaries

profiles.profile()profiles.info()profiles.statistics()profiles.summary()profiles.calendar()profiles.recommendation()

client.earnings

Earnings data & estimates

earnings.history()earnings.trend()earnings.index()earnings.report()earnings.transcript()earnings.transcript_sentiment()

client.filings

SEC filings data

filings.recent()filings.history()filings.list_forms()filings.search()filings.document_sentiment()filings.document_text()

client.financials

Financial statements & metrics

financials.revenue()financials.metrics()financials.snapshot()financials.balance_sheet()financials.income_statement()financials.cash_flow_statement()financials.dcf_value()financials.dcf_rate()financials.eps()financials.pe()financials.market_cap()financials.roe()financials.enterprise_value()financials.ebitda()financials.debt_to_equity()+24 more financial metrics

client.insiders

Insider trading data

insiders.funds()insiders.individuals()insiders.institutions()insiders.ownership()insiders.activity()insiders.transactions()

client.web_traffic

Website traffic analytics

web_traffic.traffic()

Stocks API

client.stocks

Methods for accessing stock market data including tickers, quotes, and historical prices.

Available Methods

MethodDescriptionParameters
tickers(country, exchange)Get all stock tickers with optional filteringcountry: str = None, exchange: str = None
ticker(ticker)Get a single stock ticker by its symbolticker: str
quote(ticker)Get current quote for a stockticker: str
prices(ticker, from_date, to_date, frame)Get historical stock pricesticker: str, from_date: str = None, to_date: str = None, frame: str = 'daily'
gainers(days, limit, market)Get top stock gainersdays: int = None, limit: int = None, market: str = None
losers(days, limit, market)Get top stock losersdays: int = None, limit: int = None, market: str = None
|

Stocks API - Example

# Get all US stock tickers
us_stocks = client.stocks.tickers(country="US")

# Get quote for a single stock
aapl = client.stocks.quote("AAPL")
print(f"Apple: {aapl['price']} ({aapl['change']}%)")

# Get historical prices with date range
prices = client.stocks.prices(
    "MSFT",
    from_date="2024-01-01",
    to_date="2024-03-31",
    frame="weekly"
)

# Convert to pandas DataFrame
import pandas as pd
df = pd.DataFrame(prices)
df['date'] = pd.to_datetime(df['date'])
print(df.head())

Cryptocurrency API

client.crypto

Methods for accessing cryptocurrency data including tickers, quotes, and historical prices.

Available Methods

MethodDescriptionParameters
tickers(type)Get all cryptocurrency tickers with optional filtering by typetype: str = None
ticker(ticker)Get a single cryptocurrency ticker by its symbolticker: str
quote(ticker)Get current quote for a cryptocurrencyticker: str
prices(ticker, from_date, to_date, frame)Get historical prices for a cryptocurrencyticker: str, from_date: str = None, to_date: str = None, frame: str = 'daily'
gainers(days, limit)Get top crypto gainersdays: int = None, limit: int = None
losers(days, limit)Get top crypto losersdays: int = None, limit: int = None
|

Crypto API - Example

# Get all crypto tickers
all_crypto = client.crypto.tickers()

# Filter by type (e.g., "coin", "token")
stablecoins = client.crypto.tickers(type="stablecoin")

# Get Bitcoin quote
btc = client.crypto.quote("BTC-USD")
print(f"Bitcoin: {btc['price']:,.2f}")

# Get Ethereum historical prices
eth_prices = client.crypto.prices(
    "ETH-USD",
    from_date="2024-01-01",
    to_date="2024-03-31",
    frame="daily"
)

Profiles API

client.profiles

Comprehensive company profiles, business summaries, and market data.

Available Methods

MethodDescription
profile(ticker)Get asset profile and business summary
info(ticker)Get company profile information
statistics(ticker)Get key statistics and financial ratios
summary(ticker)Get summary detail including prices and volumes
calendar(ticker)Get calendar events including earnings and dividends
recommendation(ticker)Get analyst recommendation trends
|

Profiles API - Example

# Get company profile
profile = client.profiles.profile("AAPL")
print(f"Company: {profile['name']}")
print(f"Industry: {profile['industry']}")
print(f"Sector: {profile['sector']}")

# Get key statistics
stats = client.profiles.statistics("AAPL")
print(f"Market Cap: {stats['market_cap']:,.0f}")
print(f"P/E Ratio: {stats['pe_ratio']}")

# Get upcoming events
calendar = client.profiles.calendar("AAPL")
for event in calendar:
    print(f"{event['date']}: {event['event_type']}")

Financials API

client.financials

Comprehensive financial statement data and calculated metrics.

Key Methods

financials.revenue(ticker, periods)
financials.net_income(ticker, periods)
financials.total_assets(ticker, periods)
financials.total_liabilities(ticker, periods)
financials.stockholders_equity(ticker, periods)
financials.current_assets(ticker, periods)
financials.current_liabilities(ticker, periods)
financials.operating_cash_flow(ticker, periods)
financials.capital_expenditures(ticker, periods)
financials.free_cash_flow(ticker, periods)
financials.shares_outstanding_basic(ticker, periods)
financials.shares_outstanding_diluted(ticker, periods)
financials.balance_sheet(ticker, year, quarter)
financials.income_statement(ticker, year, quarter)
financials.cash_flow_statement(ticker, year, quarter)
financials.metrics(ticker)
financials.snapshot(ticker)
financials.dcf_value(ticker)
financials.dcf_rate(ticker)
financials.eps(ticker, from, to)
financials.pe(ticker, from, to, frame)
financials.market_cap(ticker, from, to, frame)
financials.roe(ticker, from, to)
financials.enterprise_value(ticker, from, to, frame)
financials.ebitda(ticker, from, to)
financials.debt_to_equity(ticker, from, to)

Metric methods accept optional periods parameter. Statement methods accept optional year and quarter. Historical valuation methods accept optional from, to, and frame parameters.

|

Financials API - Example

# Get revenue history (last 4 quarters)
revenue = client.financials.revenue("AAPL", periods=4)
for period in revenue:
    print(f"{period['date']}: {period['value']:,.0f}")

# Get comprehensive financial snapshot
snapshot = client.financials.snapshot("AAPL")
print(f"Revenue (TTM): {snapshot['revenue_ttm']:,.0f}")
print(f"Gross Margin: {snapshot['gross_margin']}%")
print(f"Operating Margin: {snapshot['operating_margin']}%")
print(f"Debt/Equity: {snapshot['debt_to_equity']}")

# Calculate free cash flow trend
fcf = client.financials.free_cash_flow("AAPL", periods=5)
fcf_values = [period['value'] for period in fcf]
print(f"FCF Trend: {fcf_values}")

# DCF valuation
dcf = client.financials.dcf_value("AAPL")
print(f"Fair Price: {dcf['fair_price']:.2f}, Recommendation: {dcf['recommendation']}")

# Discount rate / WACC
rate = client.financials.dcf_rate("AAPL")
print(f"WACC: {rate['wacc'] * 100:.2f}%")

Filings API (SEC)

client.filings

Access SEC filings data for public companies.

Available Methods

MethodDescription
recent(ticker, limit, form)Get recent SEC filings for a company
history(ticker, form_type, start_date, end_date)Get specific form type filings by date range
list_forms()List available SEC form types and descriptions
search(ticker, form, year, quarter)Search filings by year/quarter and optional filters
document_sentiment(document_id)Get sentiment analysis of an SEC filing document by its base64 document ID
document_text(document_id)Get raw text content of an SEC filing document by its base64 document ID
|

Filings API - Example

# List all available form types
form_types = client.filings.list_forms()
print(form_types[:5])

# Get recent 10-K filings for Apple
filings = client.filings.recent("AAPL", form="10-K", limit=5)
for filing in filings:
    print(f"{filing['filed_date']}: {filing['form']}")

# Search for Q1 2024 filings
q1_filings = client.filings.search(
    form="10-Q",
    year="2024",
    quarter="Q1"
)

# Get specific 10-Q filing in Q1 2024
ten_q = client.filings.history(
    "AAPL",
    form_type="10-Q",
    start_date="2024-01-01",
    end_date="2024-03-31"
)

Insiders API

client.insiders

Access insider trading data, institutional ownership, and fund holdings.

Available Methods

MethodDescription
funds(ticker)Get fund ownership data
individuals(ticker)Get insider holders (individuals)
institutions(ticker)Get institutional ownership data
ownership(ticker)Get major holders breakdown
activity(ticker)Get net share purchase activity
transactions(ticker)Get insider transactions
|

Insiders API - Example

# Get institutional ownership
institutions = client.insiders.institutions("AAPL")
print("Top Institutional Holders:")
for holder in institutions[:5]:
    print(f"{holder['name']}: {holder['shares']:,} shares")

# Get insider transactions
transactions = client.insiders.transactions("AAPL")
print("
Recent Insider Transactions:")
for tx in transactions[:5]:
    print(f"{tx['date']}: {tx['insider']} - {tx['transaction_type']}: {tx['shares']:,} shares")

# Get ownership breakdown
ownership = client.insiders.ownership("AAPL")
print(f"
Insiders: {ownership['insider_percent']}%")
print(f"Institutions: {ownership['institution_percent']}%")
print(f"Retail: {ownership['retail_percent']}%")

Earnings API

client.earnings

Historical earnings data, trends, and estimates.

Available Methods

MethodDescription
history(ticker)Get historical earnings data
trend(ticker)Get earnings trend and estimates
index(ticker)Get index trend estimates
report(ticker, year, quarter)Get detailed earnings report for a specific period
transcript(ticker, year, quarter)Get earnings call transcript for a ticker, year, and quarter
transcript_sentiment(id)Get sentiment analysis of an earnings call transcript by its base64 ID
|

Earnings API - Example

# Get earnings history
history = client.earnings.history("AAPL")
print("Earnings History:")
for period in history:
    print(f"{period['date']}: EPS {period['eps']} vs {period['estimate']} est")

# Get earnings trend
trend = client.earnings.trend("AAPL")
print(f"
Current Quarter Estimate: {trend['current_quarter_estimate']}")
print(f"Next Quarter Estimate: {trend['next_quarter_estimate']}")
print(f"Current Year Estimate: {trend['current_year_estimate']}")

# Get specific quarterly report
q1_2024 = client.earnings.report("AAPL", year="2024", quarter="Q1")
print(f"
Q1 2024 Revenue: {q1_2024['revenue']:,.0f}")
print(f"Q1 2024 EPS: {q1_2024['eps']}")

Economic API

client.econ

Economic indicators, datasets, and calendar events.

Available Methods

MethodDescription
find(query)Find economic series using natural language description
search(query)Search for economic series
dataset(series_id)Get series observations
calendar(from_date, to_date, country, min_importance, currency, category)Get economic calendar with filters
|

Economic API - Example

# Search for inflation series
inflation_series = client.econ.search("inflation")
for series in inflation_series:
    print(f"{series['id']}: {series['name']}")

# Get GDP data
gdp = client.econ.dataset("GDP_USA")
print("
GDP History:")
for observation in gdp['observations'][-5:]:
    print(f"{observation['date']}: {observation['value']}")

# Get important economic events
calendar = client.econ.calendar(
    from_date="2024-04-01",
    to_date="2024-04-30",
    country="US",
    min_importance=3
)
for event in calendar:
    print(f"{event['date']}: {event['event']} - {event['importance']}/3")

Sentiment API

client.sentiment

Social media sentiment, news sentiment, and analyst sentiment data.

Available Methods

MethodDescription
all(ticker)Get combined sentiment (social + news + analyst)
social(ticker)Get social media sentiment
news(ticker)Get news sentiment
analyst(ticker)Get analyst sentiment
|

Sentiment API - Example

# Get overall sentiment
sentiment = client.sentiment.all("TSLA")
print(f"Overall Score: {sentiment['overall_score']}")
print(f"Sentiment: {sentiment['sentiment']}")

# Get social media sentiment
social = client.sentiment.social("TSLA")
print(f"
Social Media:")
print(f"Mentions: {social['mentions']}")
print(f"Positive: {social['positive_percent']}%")
print(f"Negative: {social['negative_percent']}%")

# Get analyst sentiment
analyst = client.sentiment.analyst("TSLA")
print(f"
Analyst Sentiment:")
print(f"Buy: {analyst['buy_count']}")
print(f"Hold: {analyst['hold_count']}")
print(f"Sell: {analyst['sell_count']}")

News API

client.news

Financial news articles by company, country, or category.

Available Methods

MethodDescription
general()Get general financial news
company(ticker)Get news for a specific company
country(country)Get news for a specific country
category(category)Get news by category
|

News API - Example

# Get top general headlines
headlines = client.news.general()
print("Top Financial News:")
for article in headlines[:5]:
    print(f"- {article['title']} ({article['source']})")

# Get company-specific news
aapl_news = client.news.company("AAPL")
print("
Apple News:")
for article in aapl_news[:3]:
    print(f"{article['published_at']}: {article['title']}")

# Get news by category
earnings_news = client.news.category("earnings")
mergers_news = client.news.category("mergers")

Supply Chain API

client.supply_chain

Company relationships including customers, suppliers, and industry peers.

Available Methods

MethodDescription
customers(ticker)Get major customers
suppliers(ticker)Get key suppliers
peers(ticker)Get industry peers
|

Supply Chain API - Example

# Get Apple's suppliers
suppliers = client.supply_chain.suppliers("AAPL")
print("Apple Suppliers:")
for supplier in suppliers[:5]:
    print(f"- {supplier['name']} ({supplier['ticker']})")

# Get industry peers
peers = client.supply_chain.peers("AAPL")
print("
Industry Peers:")
for peer in peers:
    print(f"- {peer['name']} ({peer['ticker']})")

# Get major customers
customers = client.supply_chain.customers("TSLA")
print("
Tesla Customers:")
for customer in customers:
    print(f"- {customer['name']}")

ETFs API

client.etfs

Comprehensive ETF data including fund information, holdings, and exposure analysis.

Available Methods

MethodDescription
tickers(country, exchange)Get all ETF tickers with optional filtering
ticker(ticker)Get a single ETF ticker by its symbol
quote(ticker)Get a quote for an ETF by its symbol
prices(ticker, from_date, to_date, frame)Get historical prices for an ETF
fund(ticker)Get detailed fund data for an ETF
holdings(ticker)Get holdings data for an ETF
exposure(ticker)Get exposure data for an ETF holding
weights(ticker)Get weights data for an ETF's components
gainers(days, limit)Get top ETF gainers
losers(days, limit)Get top ETF losers
|

ETFs API - Example

# Get SPY fund information
spy = client.etfs.fund("SPY")
print(f"SPY - {spy['name']}")
print(f"AUM: {spy['aum']:,.0f}")
print(f"Expense Ratio: {spy['expense_ratio']}%")
print(f"Inception Date: {spy['inception_date']}")

# Get top holdings
holdings = client.etfs.holdings("SPY")
print("
Top Holdings:")
for holding in holdings[:5]:
    print(f"{holding['name']}: {holding['weight']}%")

# Get sector exposure
exposure = client.etfs.exposure("SPY")
print("
Sector Exposure:")
for sector, weight in exposure['sectors'].items():
    print(f"{sector}: {weight}%")

Forex API

client.forex

Foreign exchange currency data including tickers, quotes, and historical prices.

Available Methods

MethodDescription
tickers(country, exchange)Get all forex tickers with optional filtering
ticker(ticker)Get a single forex ticker by its symbol
quote(ticker)Get current quote for a forex pair
prices(ticker, from_date, to_date, frame)Get historical prices for a forex pair
gainers(days, limit)Get top forex gainers
losers(days, limit)Get top forex losers
|

Forex API - Example

# Get all major forex pairs
pairs = client.forex.tickers()
print("Major Forex Pairs:")
for pair in pairs[:5]:
    print(f"- {pair['symbol']}: {pair['name']}")

# Get EUR/USD quote
eur_usd = client.forex.quote("EUR-USD")
print(f"
EUR/USD: {eur_usd['price']}")
print(f"Change: {eur_usd['change']}%")
print(f"Day Range: {eur_usd['day_low']} - {eur_usd['day_high']}")

# Get historical USD/JPY prices
usd_jpy = client.forex.prices(
    "USD-JPY",
    from_date="2024-01-01",
    to_date="2024-03-31",
    frame="daily"
)

Futures API

client.futures

Commodity and financial futures data including tickers, quotes, and historical prices.

Available Methods

MethodDescription
tickers(exchange)Get all futures tickers with optional filtering
ticker(ticker)Get a single futures ticker by its symbol
quote(ticker)Get current quote for a futures contract
prices(ticker, from_date, to_date, frame)Get historical prices for a futures contract
gainers(days, limit)Get top futures gainers
losers(days, limit)Get top futures losers
|

Futures API - Example

# Get all futures tickers
futures = client.futures.tickers()
print("Available Futures:")
for future in futures[:5]:
    print(f"- {future['symbol']}: {future['name']}")

# Get gold futures quote
gold = client.futures.quote("GC=F")
print(f"
Gold Futures: {gold['price']}")
print(f"Settlement: {gold['settlement']}")
print(f"Open Interest: {gold['open_interest']}")

# Get crude oil futures prices
oil_prices = client.futures.prices(
    "CL=F",
    from_date="2024-01-01",
    to_date="2024-03-31",
    frame="daily"
)

Indices API

client.indices

Stock market indices data including tickers, quotes, and historical prices.

Available Methods

MethodDescription
tickers(exchange)Get all index tickers with optional filtering
ticker(ticker)Get a single index ticker by its symbol
quote(ticker)Get current quote for an index
prices(ticker, from_date, to_date, frame)Get historical prices for an index
gainers(days, limit)Get top index gainers
losers(days, limit)Get top index losers
components(ticker)Get index components for a given index
exposure(ticker)Get index exposure for a given index
|

Indices API - Example

# Get all indices
indices = client.indices.tickers()
print("Major Indices:")
for index in indices[:5]:
    print(f"- {index['symbol']}: {index['name']}")

# Get S&P 500 quote
spx = client.indices.quote("^GSPC")
print(f"
S&P 500: {spx['price']:,.2f}")
print(f"Change: {spx['change']}%")
print(f"YTD Change: {spx['ytd_change']}%")

# Get NASDAQ historical prices
nasdaq = client.indices.prices(
    "^IXIC",
    from_date="2024-01-01",
    to_date="2024-03-31",
    frame="daily"
)

Credit API

client.credit

Credit ratings and entity search for companies and financial instruments.

Available Methods

MethodDescription
search(query)Search for credit entities
ratings(entity_id)Get ratings for a specific credit entity
|

Credit API - Example

# Search for credit entities
results = client.credit.search("Apple")
for entity in results:
    print(f"{entity['name']} - {entity['entity_type']}")

# Get credit ratings for Apple
ratings = client.credit.ratings("AAPL")
print(f"
Apple Credit Ratings:")
print(f"Moody's: {ratings['moodys']}")
print(f"S&P: {ratings['sp']}")
print(f"Fitch: {ratings['fitch']}")
print(f"Outlook: {ratings['outlook']}")

ESG API

client.esg

Environmental, Social, and Governance (ESG) scores and metrics for publicly traded companies.

Available Methods

MethodDescription
data(ticker)Get comprehensive ESG data for a specific company
|

ESG API - Example

# Get ESG data for Microsoft
esg = client.esg.data("MSFT")
print(f"Overall ESG Score: {esg['score']}")
print(f"Environmental Score: {esg['environmental_score']}")
print(f"Environmental Grade: {esg['environmental_grade']}")
print(f"Social Score: {esg['social_score']}")
print(f"Social Grade: {esg['social_grade']}")
print(f"Governance Score: {esg['governance_score']}")
print(f"Governance Grade: {esg['governance_grade']}")

# Access detailed metrics
if 'controversies' in esg:
    print(f"
Controversies: {len(esg['controversies'])}")
for metric in esg['key_metrics']:
    print(f"{metric['name']}: {metric['value']}")

Web Traffic API

client.web_traffic

Website traffic and analytics data for publicly traded companies.

Available Methods

MethodDescription
traffic(ticker)Get website traffic and analytics data
|

Web Traffic API - Example

# Get web traffic data for Amazon
traffic = client.web_traffic.traffic("AMZN")
print(f"Monthly Visits: {traffic['monthly_visits']:,}")
print(f"Monthly Unique Visitors: {traffic['monthly_unique_visitors']:,}")
print(f"Pages per Visit: {traffic['pages_per_visit']}")
print(f"Average Visit Duration: {traffic['avg_visit_duration']}s")
print(f"Bounce Rate: {traffic['bounce_rate']}%")

# Traffic trends
print("
Traffic by Source:")
for source, percentage in traffic['traffic_sources'].items():
    print(f"{source}: {percentage}%")

# Geographic distribution
print("
Top Countries:")
for country in traffic['top_countries'][:5]:
    print(f"{country['name']}: {country['percentage']}%")

Error Handling

The SDK raises descriptive exceptions that can be caught and handled gracefully.

Common Exceptions

Error PatternDescription
HTTP Error 4xxClient error (invalid request, unauthorized, etc.)
HTTP Error 5xxServer error (API temporarily unavailable)
Connection ErrorNetwork failure or DNS resolution error
Timeout ErrorRequest exceeded timeout limit
Authentication ErrorMissing or invalid API key
|

Error handling with retry

import time
from axion import Axion

client = Axion(api_key="your_api_key_here")

def fetch_with_retry(func, *args, max_retries=3, base_delay=1):
    """Fetch data with exponential backoff retry logic."""
    for attempt in range(max_retries):
        try:
            return func(*args)
        except Exception as e:
            error_str = str(e)

            # Handle rate limiting (429)
            if "429" in error_str and attempt < max_retries - 1:
                delay = base_delay * (2 ** attempt)
                print(f"Rate limited. Retrying in {delay}s...")
                time.sleep(delay)
                continue

            # Handle authentication errors
            elif "Authentication" in error_str or "401" in error_str:
                print("Invalid API key. Please check your credentials.")
                break

            # Handle not found (404)
            elif "404" in error_str:
                print(f"Resource not found: {args}")
                break

            # Handle server errors (5xx)
            elif "500" in error_str or "502" in error_str or "503" in error_str:
                if attempt < max_retries - 1:
                    delay = base_delay * (2 ** attempt)
                    print(f"Server error. Retrying in {delay}s...")
                    time.sleep(delay)
                    continue
                else:
                    print("API server unavailable. Please try again later.")

            # Re-raise unexpected errors
            else:
                raise

    return None

# Usage
data = fetch_with_retry(client.stocks.quote, "AAPL")
if data:
    print(f"Price: {data['price']}")

Data Normalization

All responses are automatically normalized: string numbers → int/float, "true"/"false" → bool, recursively. This means you can use the returned data directly without manual type conversion.

String → Number

"150.42" → 150.42 (float), "42" → 42 (int)

String → Boolean

"true"/"false" → True/False (case-insensitive)

Deep recursion

Nested dictionaries and lists are traversed and normalized

Null handling

"null", "None" remain as None/null values

|

Automatic type conversion

# Raw API returns:
# {
#   "price": "150.42",
#   "volume": "12345678",
#   "active": "true",
#   "pe_ratio": "25.6",
#   "details": {
#     "has_dividend": "false",
#     "dividend_yield": "0.5"
#   }
# }

# After normalization:
# {
#   "price": 150.42,
#   "volume": 12345678,
#   "active": True,
#   "pe_ratio": 25.6,
#   "details": {
#     "has_dividend": False,
#     "dividend_yield": 0.5
#   }
# }

# Use directly without casting:
data = client.stocks.quote("AAPL")
price = data['price']        # Already a float
volume = data['volume']      # Already an int
if data['active']:           # Already a bool
    print(f"Trading active with P/E {data['pe_ratio']}")

Complete Example

A comprehensive script demonstrating multiple API calls, data analysis with pandas, and visualization.

#!/usr/bin/env python3
"""
Axion SDK Complete Example
Demonstrates multiple API endpoints and data analysis techniques
"""
from axion import Axion
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import time
import SEOMetadata from '@/components/SEOMetadata';

class CompanyAnalyzer:
    def __init__(self, api_key):
        self.client = Axion(api_key=api_key)

    def analyze_company(self, ticker):
        """Fetch and display comprehensive company data."""
        print(f"\n{'='*60}")
        print(f"COMPANY ANALYSIS: {ticker}")
        print('='*60)

        try:
            # Profile information
            profile = self.client.profiles.profile(ticker)
            print(f"\n PROFILE:")
            print(f"  Name: {profile.get('name')}")
            print(f"  Sector: {profile.get('sector')}")
            print(f"  Industry: {profile.get('industry')}")
            print(f"  Employees: {profile.get('full_time_employees'):,}")

            # Stock quote
            quote = self.client.stocks.quote(ticker)
            print(f"\n MARKET DATA:")
            print(f"  Price: {quote.get('price'):,.2f}")
            print(f"  Change: {quote.get('change')}%")
            print(f"  Volume: {quote.get('volume'):,}")
            print(f"  Market Cap: {quote.get('market_cap'):,.0f}")

            # ESG data
            esg = self.client.esg.data(ticker)
            print(f"\n ESG SCORES:")
            print(f"  Overall: {esg.get('score')}")
            print(f"  Environmental: {esg.get('environmental_grade')}")
            print(f"  Social: {esg.get('social_grade')}")
            print(f"  Governance: {esg.get('governance_grade')}")

            # Financial snapshot
            snapshot = self.client.financials.snapshot(ticker)
            print(f"\n FINANCIALS:")
            print(f"  Revenue (TTM): {snapshot.get('revenue_ttm'):,.0f}")
            print(f"  Gross Margin: {snapshot.get('gross_margin')}%")
            print(f"  Operating Margin: {snapshot.get('operating_margin')}%")
            print(f"  Debt/Equity: {snapshot.get('debt_to_equity')}")

            # Sentiment
            sentiment = self.client.sentiment.all(ticker)
            print(f"\n SENTIMENT:")
            print(f"  Overall Score: {sentiment.get('overall_score')}")
            print(f"  Sentiment: {sentiment.get('sentiment')}")

            # Recent news
            news = self.client.news.company(ticker)
            print(f"\n RECENT NEWS (Top 3):")
            for article in news[:3]:
                print(f"  • {article.get('title')}")
                print(f"    {article.get('published_at')} - {article.get('source')}")

            return {
                'ticker': ticker,
                'price': quote.get('price'),
                'market_cap': quote.get('market_cap'),
                'esg_score': esg.get('score'),
                'sentiment_score': sentiment.get('overall_score'),
                'revenue_ttm': snapshot.get('revenue_ttm'),
                'gross_margin': snapshot.get('gross_margin')
            }

        except Exception as e:
            print(f"Error analyzing {ticker}: {e}")
            return None

    def analyze_portfolio(self, tickers):
        """Analyze multiple companies and create comparison."""
        results = []
        for ticker in tickers:
            result = self.analyze_company(ticker)
            if result:
                results.append(result)
            time.sleep(1)  # Rate limiting

        if results:
            df = pd.DataFrame(results)

            print("\n" + "="*60)
            print("PORTFOLIO COMPARISON")
            print("="*60)
            print(df.to_string(index=False))

            # Create visualizations
            fig, axes = plt.subplots(2, 2, figsize=(14, 10))
            fig.suptitle('Portfolio Analysis', fontsize=16)

            # Market Cap comparison
            axes[0, 0].barh(df['ticker'], df['market_cap'])
            axes[0, 0].set_xlabel('Market Cap ($B)')
            axes[0, 0].set_title('Market Capitalization')

            # ESG Scores
            axes[0, 1].bar(df['ticker'], df['esg_score'], color='green')
            axes[0, 1].set_ylabel('ESG Score')
            axes[0, 1].set_title('ESG Scores')

            # Sentiment
            axes[1, 0].bar(df['ticker'], df['sentiment_score'], color='blue')
            axes[1, 0].set_ylabel('Sentiment Score')
            axes[1, 0].set_title('Sentiment Analysis')

            # Margins
            x = range(len(df))
            width = 0.35
            axes[1, 1].bar([i - width/2 for i in x], df['gross_margin'], width, label='Gross Margin', color='orange')
            axes[1, 1].set_xticks(x)
            axes[1, 1].set_xticklabels(df['ticker'])
            axes[1, 1].set_ylabel('Margin %')
            axes[1, 1].set_title('Profit Margins')
            axes[1, 1].legend()

            plt.tight_layout()
            plt.show()

            return df
        return None

    def historical_analysis(self, ticker, months=6):
        """Analyze historical price trends."""
        end_date = datetime.now()
        start_date = end_date - timedelta(days=30*months)

        print(f"\n HISTORICAL ANALYSIS: {ticker}")
        print(f"Period: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")

        # Get historical prices
        prices = self.client.stocks.prices(
            ticker,
            from_date=start_date.strftime('%Y-%m-%d'),
            to_date=end_date.strftime('%Y-%m-%d'),
            frame='daily'
        )

        if prices:
            df = pd.DataFrame(prices)
            df['date'] = pd.to_datetime(df['date'])
            df.set_index('date', inplace=True)

            # Calculate metrics
            df['daily_return'] = df['close'].pct_change() * 100
            df['sma_20'] = df['close'].rolling(window=20).mean()
            df['sma_50'] = df['close'].rolling(window=50).mean()

            # Print statistics
            print(f"\n STATISTICS:")
            print(f"  Start Price: {df['close'].iloc[0]:.2f}")
            print(f"  End Price: {df['close'].iloc[-1]:.2f}")
            print(f"  Total Return: {((df['close'].iloc[-1] / df['close'].iloc[0]) - 1) * 100:.2f}%")
            print(f"  Max Price: {df['close'].max():.2f}")
            print(f"  Min Price: {df['close'].min():.2f}")
            print(f"  Volatility (daily): {df['daily_return'].std():.2f}%")

            # Plot
            fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))

            # Price chart with moving averages
            ax1.plot(df.index, df['close'], label='Close Price', linewidth=1)
            ax1.plot(df.index, df['sma_20'], label='20-day SMA', linestyle='--', alpha=0.7)
            ax1.plot(df.index, df['sma_50'], label='50-day SMA', linestyle='--', alpha=0.7)
            ax1.set_ylabel('Price ($)')
            ax1.set_title(f'{ticker} - Historical Prices')
            ax1.legend()
            ax1.grid(True, alpha=0.3)

            # Daily returns histogram
            ax2.hist(df['daily_return'].dropna(), bins=50, edgecolor='black', alpha=0.7)
            ax2.set_xlabel('Daily Return (%)')
            ax2.set_ylabel('Frequency')
            ax2.set_title('Distribution of Daily Returns')
            ax2.grid(True, alpha=0.3)

            plt.tight_layout()
            plt.show()

            return df
        return None

def main():
    # Initialize
    analyzer = CompanyAnalyzer(api_key="your_api_key_here")

    # Analyze single company
    analyzer.analyze_company("AAPL")

    # Analyze portfolio
    portfolio = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
    analyzer.analyze_portfolio(portfolio)

    # Historical analysis
    analyzer.historical_analysis("AAPL", months=6)

if __name__ == "__main__":
    main()