Logo
AXION

Python SDK

Python SDK

The axionquant-sdk package: a pandas-friendly core client plus modules for models, technical analysis, utilities and Plotly visualisations.

AxionQuant Python SDK

The AxionQuant Python SDK (also called the Axion SDK) provides a comprehensive wrapper for interacting with the AxionQuant 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 AxionQuant 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
"""
AxionQuant 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';
import DocHeading from '@/docs/DocHeading';

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()