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
- Import the
Axionclass fromaxion - Create a client with your API key
- Call methods on category attributes (e.g.,
client.stocks.quote("AAPL")) - 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
| Parameter | Type | Required | Description |
|---|---|---|---|
| api_key | str | Optional* | 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 metricsclient.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.stocksMethods for accessing stock market data including tickers, quotes, and historical prices.
Available Methods
| Method | Description | Parameters |
|---|---|---|
| tickers(country, exchange) | Get all stock tickers with optional filtering | country: str = None, exchange: str = None |
| ticker(ticker) | Get a single stock ticker by its symbol | ticker: str |
| quote(ticker) | Get current quote for a stock | ticker: str |
| prices(ticker, from_date, to_date, frame) | Get historical stock prices | ticker: str, from_date: str = None, to_date: str = None, frame: str = 'daily' |
| gainers(days, limit, market) | Get top stock gainers | days: int = None, limit: int = None, market: str = None |
| losers(days, limit, market) | Get top stock losers | days: 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.cryptoMethods for accessing cryptocurrency data including tickers, quotes, and historical prices.
Available Methods
| Method | Description | Parameters |
|---|---|---|
| tickers(type) | Get all cryptocurrency tickers with optional filtering by type | type: str = None |
| ticker(ticker) | Get a single cryptocurrency ticker by its symbol | ticker: str |
| quote(ticker) | Get current quote for a cryptocurrency | ticker: str |
| prices(ticker, from_date, to_date, frame) | Get historical prices for a cryptocurrency | ticker: str, from_date: str = None, to_date: str = None, frame: str = 'daily' |
| gainers(days, limit) | Get top crypto gainers | days: int = None, limit: int = None |
| losers(days, limit) | Get top crypto losers | days: 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.profilesComprehensive company profiles, business summaries, and market data.
Available Methods
| Method | Description |
|---|---|
| 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.financialsComprehensive 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.filingsAccess SEC filings data for public companies.
Available Methods
| Method | Description |
|---|---|
| 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.insidersAccess insider trading data, institutional ownership, and fund holdings.
Available Methods
| Method | Description |
|---|---|
| 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.earningsHistorical earnings data, trends, and estimates.
Available Methods
| Method | Description |
|---|---|
| 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.econEconomic indicators, datasets, and calendar events.
Available Methods
| Method | Description |
|---|---|
| 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.sentimentSocial media sentiment, news sentiment, and analyst sentiment data.
Available Methods
| Method | Description |
|---|---|
| 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.newsFinancial news articles by company, country, or category.
Available Methods
| Method | Description |
|---|---|
| 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_chainCompany relationships including customers, suppliers, and industry peers.
Available Methods
| Method | Description |
|---|---|
| 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.etfsComprehensive ETF data including fund information, holdings, and exposure analysis.
Available Methods
| Method | Description |
|---|---|
| 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.forexForeign exchange currency data including tickers, quotes, and historical prices.
Available Methods
| Method | Description |
|---|---|
| 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.futuresCommodity and financial futures data including tickers, quotes, and historical prices.
Available Methods
| Method | Description |
|---|---|
| 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.indicesStock market indices data including tickers, quotes, and historical prices.
Available Methods
| Method | Description |
|---|---|
| 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.creditCredit ratings and entity search for companies and financial instruments.
Available Methods
| Method | Description |
|---|---|
| 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.esgEnvironmental, Social, and Governance (ESG) scores and metrics for publicly traded companies.
Available Methods
| Method | Description |
|---|---|
| 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_trafficWebsite traffic and analytics data for publicly traded companies.
Available Methods
| Method | Description |
|---|---|
| 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 Pattern | Description |
|---|---|
| HTTP Error 4xx | Client error (invalid request, unauthorized, etc.) |
| HTTP Error 5xx | Server error (API temporarily unavailable) |
| Connection Error | Network failure or DNS resolution error |
| Timeout Error | Request exceeded timeout limit |
| Authentication Error | Missing 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()Time Series Models
Statistical and machine learning models for time series forecasting and analysis.
linearRegression
linearRegression(df, x, target, n_preds=10, scale='D')Simple linear regression model for time series forecasting using scikit-learn's LinearRegression.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas frequency string for future dates (default: 'D' for daily) |
Returns
Returns a pandas.DataFrame with two columns: the x column (future dates) and target column (predicted values).
Usage Example
Python
from axion import models
import pandas as pd
# Sample data
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=100, freq='D'),
'value': range(100)
})
# Make predictions
predictions = models.linearRegression(
df=df,
x='date',
target='value',
n_preds=5,
scale='D'
)
print(predictions)multiLinearRegression
multiLinearRegression(df, x, target, features, n_preds=10, scale='D')Multiple linear regression model that uses additional features for time series forecasting.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| features | list | Required | List of feature column names to use for prediction |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas frequency string for future dates (default: 'D') |
Returns
Returns a pandas.DataFrame with 'time' and target columns containing future predictions.
Usage Example
Python
from axion import models
import pandas as pd
# Sample data with features
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=100, freq='D'),
'value': range(100),
'feature1': [i * 1.5 for i in range(100)],
'feature2': [i * 0.5 for i in range(100)]
})
# Make predictions using multiple features
predictions = models.multiLinearRegression(
df=df,
x='date',
target='value',
features=['feature1', 'feature2'],
n_preds=5,
scale='D'
)
print(predictions)beta
beta(df, x, y)Calculates the beta coefficient (slope) between two time series using linear regression.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing both time series |
| x | string | Required | Column name for dependent variable |
| y | string | Required | Column name for independent variable |
Returns
Returns a float representing the beta coefficient (regression slope) of x on y.
Usage Example
Python
from axion import models
import pandas as pd
# Sample data
df = pd.DataFrame({
'stock_returns': [0.01, 0.02, -0.01, 0.03, 0.01],
'market_returns': [0.005, 0.015, -0.005, 0.025, 0.01]
})
# Calculate beta coefficient
beta_value = models.beta(
df=df,
x='stock_returns',
y='market_returns'
)
print(f"Beta: {beta_value}")lstm
lstm(df, x, target, features=[], n_preds=10, scale='D')LSTM (Long Short-Term Memory) neural network for time series forecasting using TensorFlow/Keras.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| features | list | Optional | List of additional feature columns (default: empty list) |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas frequency string for future dates (default: 'D') |
Returns
Returns a pandas.DataFrame with 'time' and target columns containing future predictions.
Helper Function
create_sequences(data, sequence_length, n_preds) - Creates sequences for LSTM training.
Usage Example
Python
from axion import models
import pandas as pd
import SEOMetadata from '@/components/SEOMetadata';
# Sample data
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=200, freq='D'),
'value': [i + 10 * (i % 7) for i in range(200)],
'feature': [i * 0.5 for i in range(200)]
})
# Make predictions using LSTM
predictions = models.lstm(
df=df,
x='date',
target='value',
features=['feature'],
n_preds=5,
scale='D'
)
print(predictions)Technical Analysis Indicators
A comprehensive collection of technical analysis indicators for financial data analysis. These functions calculate various market indicators used in technical trading strategies.
Rate of Change (ROC)
roc(df, column="close", period=10)Calculates the Rate of Change percentage over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 10 | Lookback period for ROC calculation |
Returns
Returns a pandas Series with ROC percentage values.
Formula
ROC Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period ROC
roc_series = ta.roc(df, column='close', period=5)
print(roc_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 4.000000
6 3.921569
7 3.883495
8 1.923077
9 3.809524
Name: roc, dtype: float64Momentum
mom(df, column="close", period=10)Calculates the difference between current price and price n periods ago.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 10 | Lookback period for momentum calculation |
Returns
Returns a pandas Series with momentum values (price difference).
Formula
Momentum Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 104, 103, 105, 107, 106, 108, 110, 109]
})
# Calculate 5-period momentum
momentum_series = ta.mom(df, column='close', period=5)
print(momentum_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 7.0
6 4.0
7 5.0
8 5.0
9 2.0
Name: mom, dtype: float64Simple Moving Average
sma(df, column="close", period=14)Calculates the Simple Moving Average over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for SMA calculation |
Returns
Returns a pandas Series with Simple Moving Average values.
Formula
SMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period SMA
sma_series = ta.sma(df, column='close', period=5)
print(sma_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.2
5 103.0
6 103.8
7 105.2
8 106.0
9 106.8
Name: sma, dtype: float64Simple Moving Median
smm(df, column="close", period=14)Calculates the median value over a specified rolling window.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for median calculation |
Returns
Returns a pandas Series with moving median values.
Formula
SMM Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period SMM
smm_series = ta.smm(df, column='close', period=5)
print(smm_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.0
5 103.0
6 104.0
7 105.0
8 106.0
9 107.0
Name: smm, dtype: float64Smoothed Simple Moving Average
ssma(df, column="close", period=14)Calculates a smoothed version of the Simple Moving Average using exponential smoothing.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for SSMA calculation |
Returns
Returns a pandas Series with smoothed moving average values.
Formula
SSMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period SSMA
ssma_series = ta.ssma(df, column='close', period=5)
print(ssma_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.200000
5 102.533333
6 103.355556
7 104.570370
8 105.046914
9 106.031276
Name: ssma, dtype: float64Exponential Moving Average
ema(df, column="close", period=14)Calculates the Exponential Moving Average which gives more weight to recent prices.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for EMA calculation |
Returns
Returns a pandas Series with Exponential Moving Average values.
Formula
where k = 2/(period + 1)
EMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period EMA
ema_series = ta.ema(df, column='close', period=5)
print(ema_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.200000
5 102.800000
6 103.866667
7 105.244444
8 105.829630
9 106.886420
Name: ema, dtype: float64Double Exponential Moving Average
dema(df, column="close", period=14)Calculates the Double EMA, which applies EMA smoothing twice for reduced lag.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for DEMA calculation |
Returns
Returns a pandas Series with Double Exponential Moving Average values.
Formula
DEMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period DEMA
dema_series = ta.dema(df, column='close', period=5)
print(dema_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.200000
5 103.137778
6 105.029630
7 107.159012
8 107.264198
9 109.159538
Name: dema, dtype: float64Triangular Moving Average
trima(df, column="close", period=14)Calculates a double-smoothed moving average for reduced noise.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for TRIMA calculation |
Returns
Returns a pandas Series with Triangular Moving Average values.
Formula
TRIMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period TRIMA
trima_series = ta.trima(df, column='close', period=5)
print(trima_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 104.2
9 104.8
Name: trima, dtype: float64Average True Range
atr(df, period=14)Measures market volatility by calculating the average of true ranges over a period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for ATR calculation |
Returns
Returns a pandas Series with Average True Range values.
True Range Calculation
ATR = SMA(TR, period)
ATR Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110],
'low': [99, 101, 100, 102, 104],
'close': [102, 104, 103, 105, 107]
})
# Calculate 3-period ATR
atr_series = ta.atr(df, period=3)
print(atr_series)Output
0 NaN
1 NaN
2 4.666667
3 4.222222
4 4.148148
Name: atr, dtype: float64Stochastic Oscillator
stochastic_oscillator(df, k_period=14, d_period=3)Calculates %K and %D stochastic oscillator values to identify overbought/oversold conditions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| k_period | int | 14 | Lookback period for %K calculation |
| d_period | int | 3 | Smoothing period for %D |
Returns
Returns two pandas Series: %K (fast stochastic) and %D (slow stochastic).
Formula
%D = SMA(%K, d_period)
Stochastic Oscillator Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110, 109, 111],
'low': [99, 101, 100, 102, 104, 103, 105],
'close': [102, 104, 103, 105, 107, 106, 108]
})
# Calculate stochastic oscillator
stoch_k, stoch_d = ta.stochastic_oscillator(df, k_period=5, d_period=3)
print("Stochastic %K:", stoch_k)
print("Stochastic %D:", stoch_d)Output
Stochastic %K: 0 NaN
1 NaN
2 NaN
3 NaN
4 50.000000
5 66.666667
6 57.142857
Name: stoch_k, dtype: float64
Stochastic %D: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 57.936508
Name: stoch_d, dtype: float64Chande Momentum Oscillator
cmo(df, column="close", period=20)Measures momentum by comparing sum of gains to sum of losses over a period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 20 | Lookback period for CMO calculation |
Returns
Returns a pandas Series with CMO values ranging from -100 to +100.
Formula
CMO Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period CMO
cmo_series = ta.cmo(df, column='close', period=5)
print(cmo_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 60.000000
6 33.333333
7 60.000000
8 20.000000
9 60.000000
Name: cmo, dtype: float64On Balance Volume
obv(df)Cumulatively adds or subtracts volume based on price direction to measure buying/selling pressure.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'close' and 'volume' columns |
Returns
Returns a pandas Series with cumulative On Balance Volume values.
Formula
volumeₜ if closeₜ > closeₜ-₁
-volumeₜ if closeₜ > closeₜ-
0 if closeₜ = closeₜ-₁
OBV Example
Python
from axion import ta
import pandas as pd
# Sample OHLCV data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105],
'volume': [1000, 1500, 1200, 1800, 2000]
})
# Calculate OBV
obv_series = ta.obv(df)
print(obv_series)Output
0 1000
1 2500
2 1300
3 3100
4 5100
Name: obv, dtype: int64Volume Price Trend
vpt(df)Measures the relationship between volume and price changes by cumulating volume adjusted by price percentage changes.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'close' and 'volume' columns |
Returns
Returns a pandas Series with cumulative Volume Price Trend values.
Formula
VPT Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105],
'volume': [1000, 1500, 1200, 1800, 2000]
})
# Calculate VPT
vpt_series = ta.vpt(df)
print(vpt_series)Output
0 0.000000
1 30.000000
2 18.235294
3 53.184466
4 91.962275
Name: vpt, dtype: float64Volume-Weighted Average Price
vwap(df, period=14)Calculates the average price weighted by volume over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close', 'volume' columns |
| period | int | 14 | Rolling period for VWAP calculation |
Returns
Returns a pandas Series with Volume-Weighted Average Price values.
Formula
typical_price = (high + low + close) / 3
VWAP Example
Python
from axion import ta
import pandas as pd
# Sample OHLCV data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110],
'low': [99, 101, 100, 102, 104],
'close': [102, 104, 103, 105, 107],
'volume': [1000, 1500, 1200, 1800, 2000]
})
# Calculate VWAP
vwap_series = ta.vwap(df, period=3)
print(vwap_series)Output
0 NaN
1 NaN
2 103.175676
3 104.557377
4 105.595745
Name: vwap, dtype: float64Bollinger Bands
bbands(df, column="close", period=20, num_std_dev=2)Calculates upper and lower Bollinger Bands around a simple moving average.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 20 | Lookback period for SMA calculation |
| num_std_dev | int/float | 2 | Number of standard deviations for bands |
Returns
Returns three pandas Series: upper_band, middle_band (SMA), lower_band.
Formula
upper_band = middle_band + (std_dev × num_std_dev)
lower_band = middle_band - (std_dev × num_std_dev)
Bollinger Bands Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate Bollinger Bands
upper, middle, lower = ta.bbands(df, period=5, num_std_dev=2)
print("Upper Band:", upper)
print("Middle Band:", middle)
print("Lower Band:", lower)Output
Upper Band: 4 106.549742
5 107.303261
6 109.063901
7 111.133918
8 111.207841
9 112.456119
Name: bbands_upper, dtype: float64
Middle Band: 4 102.2
5 103.0
6 103.8
7 105.2
8 106.0
9 106.8
Name: bbands_middle, dtype: float64
Lower Band: 4 97.850258
5 98.696739
6 98.536099
7 99.266082
8 100.792159
9 101.143881
Name: bbands_lower, dtype: float64Keltner Channels
kc(df, period=20, atr_period=10, multiplier=2)Calculates volatility-based channels using ATR around an exponential moving average.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 20 | EMA period for middle line |
| atr_period | int | 10 | Period for ATR calculation |
| multiplier | int/float | 2 | ATR multiplier for channel width |
Returns
Returns three pandas Series: upper_channel, middle_line, lower_channel.
Formula
upper_channel = middle_line + (ATR × multiplier)
lower_channel = middle_line - (ATR × multiplier)
Keltner Channels Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110],
'low': [99, 101, 100, 102, 104],
'close': [102, 104, 103, 105, 107]
})
# Calculate Keltner Channels
upper, middle, lower = ta.kc(df, period=3, atr_period=3, multiplier=2)
print("Upper Channel:", upper)
print("Middle Line:", middle)
print("Lower Channel:", lower)Output
Upper Channel: 0 NaN
1 NaN
2 109.888889
3 110.666667
4 112.296296
Name: kc_upper, dtype: float64
Middle Line: 0 NaN
1 NaN
2 103.000000
3 104.000000
4 105.666667
Name: kc_middle, dtype: float64
Lower Channel: 0 NaN
1 NaN
2 96.111111
3 97.333333
4 99.037037
Name: kc_lower, dtype: float64Kaufman's Adaptive Moving Average
kama(df, column="close", period=14, fast=14, slow=30)Adaptive moving average that adjusts its sensitivity based on market volatility.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Efficiency ratio period |
| fast | int | 14 | Fast EMA constant period |
| slow | int | 30 | Slow EMA constant period |
Returns
Returns a pandas Series with Kaufman's Adaptive Moving Average values.
Formula
SC = [ER × (fastest - slowest) + slowest]²
KAMAₜ = KAMAₜ-₁ + SC × (price - KAMAₜ-₁)
KAMA Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate KAMA
kama_series = ta.kama(df, column='close', period=5)
print(kama_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 102.200000
5 103.103252
6 104.383699
7 106.149310
8 106.431297
9 107.774876
Name: kama, dtype: float64Vortex Indicator
vi(df, period=14)Measures trend direction and strength using positive and negative vortex movements.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for VI calculation |
Returns
Returns two pandas Series: VI_plus (positive vortex) and VI_minus (negative vortex).
Vortex Indicator Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110, 109, 111],
'low': [99, 101, 100, 102, 104, 103, 105],
'close': [102, 104, 103, 105, 107, 106, 108]
})
# Calculate Vortex Indicator
vi_plus, vi_minus = ta.vi(df, period=5)
print("VI+:", vi_plus)
print("VI-:", vi_minus)Output
VI+: 0 NaN
1 NaN
2 NaN
3 NaN
4 1.245192
5 1.183790
6 1.193062
Name: vi_plus, dtype: float64
VI-: 0 NaN
1 NaN
2 NaN
3 NaN
4 0.832453
5 0.822703
6 0.844121
Name: vi_minus, dtype: float64Moving Average Convergence Divergence
macd(df, column="close", fast_period=12, slow_period=26, signal_period=9)Calculates MACD line, signal line, and histogram for trend-following momentum indicator.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| fast_period | int | 12 | Fast EMA period |
| slow_period | int | 26 | Slow EMA period |
| signal_period | int | 9 | Signal line EMA period |
Returns
Returns three pandas Series: macd_line, signal_line, histogram.
Formula
Signal = EMA(MACD, signal_period)
Histogram = MACD - Signal
MACD Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate MACD
macd_line, signal_line, histogram = ta.macd(df, fast_period=5, slow_period=8, signal_period=3)
print("MACD Line:", macd_line)
print("Signal Line:", signal_line)
print("Histogram:", histogram)Output
MACD Line: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 0.881433
8 0.495703
9 1.079230
Name: macd, dtype: float64
Signal Line: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 0.881433
8 0.688568
9 0.883899
Name: signal, dtype: float64
Histogram: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 0.000000
8 -0.192865
9 0.195331
Name: histogram, dtype: float64Williams %R
williams_r(df, period=14)Momentum indicator measuring overbought/oversold levels, similar to stochastic oscillator.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for Williams %R |
Returns
Returns a pandas Series with Williams %R values ranging from -100 to 0.
Formula
Williams %R Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110],
'low': [99, 101, 100, 102, 104],
'close': [102, 104, 103, 105, 107]
})
# Calculate Williams %R
williams_r_series = ta.williams_r(df, period=5)
print(williams_r_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 -50.000000
Name: williams_r, dtype: float64Average Directional Index
adx(df, period=14)Measures trend strength without regard to direction.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for ADX calculation |
Returns
Returns a pandas Series with Average Directional Index values.
Formula
-DI = 100 × SMA(-DM) / ATR
DX = 100 × |+DI - -DI| / (+DI + -DI)
ADX = SMA(DX, period)
ADX Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110, 109, 111],
'low': [99, 101, 100, 102, 104, 103, 105],
'close': [102, 104, 103, 105, 107, 106, 108]
})
# Calculate ADX
adx_series = ta.adx(df, period=5)
print(adx_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 32.495897
Name: adx, dtype: float64Relative Strength Index
rsi(df, column="close", period=14)Measures speed and change of price movements to identify overbought/oversold conditions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for RSI calculation |
Returns
Returns a pandas Series with RSI values ranging from 0 to 100.
Formula
RS = average_gain / average_loss
RSI Example
Python
from axion import ta
import pandas as pd
# Sample data
df = pd.DataFrame({
'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})
# Calculate 5-period RSI
rsi_series = ta.rsi(df, column='close', period=5)
print(rsi_series)Output
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 61.904762
6 55.555556
7 70.000000
8 57.142857
9 70.000000
Name: rsi, dtype: float64Ichimoku Cloud
ichi(df)Comprehensive indicator that provides support/resistance, trend direction, and momentum.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
Returns
Returns five pandas Series: conversion_line, base_line, leading_span_a, leading_span_b, lagging_span.
Formula
Base Line = (26-period high + 26-period low) / 2
Leading Span A = (Conversion Line + Base Line) / 2 (shifted forward 26 periods)
Leading Span B = (52-period high + 52-period low) / 2 (shifted forward 26 periods)
Lagging Span = Close (shifted back 26 periods)
Ichimoku Cloud Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data (typically requires more data points)
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110, 109, 111, 112, 113, 114],
'low': [99, 101, 100, 102, 104, 103, 105, 106, 107, 108],
'close': [102, 104, 103, 105, 107, 106, 108, 109, 110, 111]
})
# Calculate Ichimoku Cloud
conversion, base, span_a, span_b, lag = ta.ichi(df)
print("Conversion Line:", conversion)
print("Base Line:", base)
print("Leading Span A:", span_a)
print("Leading Span B:", span_b)
print("Lagging Span:", lag)Output
Conversion Line: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 107.5
9 108.5
Name: conversion_line, dtype: float64
Base Line: 0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 108.0
9 108.5
Name: base_line, dtype: float64
...Parabolic SAR
sar(df, af=0.02, af_max=0.2)Trend-following indicator that provides potential reversal points.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| af | float | 0.02 | Acceleration factor increment |
| af_max | float | 0.2 | Maximum acceleration factor |
Returns
Returns a pandas Series with Parabolic SAR values.
Formula
where EP is the extreme point (highest high in uptrend, lowest low in downtrend)
Parabolic SAR Example
Python
from axion import ta
import pandas as pd
# Sample OHLC data
df = pd.DataFrame({
'high': [105, 107, 106, 108, 110, 109, 111],
'low': [99, 101, 100, 102, 104, 103, 105],
'close': [102, 104, 103, 105, 107, 106, 108]
})
# Calculate Parabolic SAR
sar_series = ta.sar(df, af=0.02, af_max=0.2)
print(sar_series)Output
0 99.000000
1 99.000000
2 99.000000
3 99.000000
4 99.000000
5 99.000000
6 104.060000
Name: sar, dtype: float64Fibonacci Pivot Points
fib(df)Calculates Fibonacci-based support and resistance levels using previous period's high, low, and close.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
Returns
Returns seven pandas Series: PP, R1, S1, R2, S2, R3, S3.
Formulas
R1 = PP + 0.382 × (high - low)
S1 = PP - 0.382 × (high - low)
R2 = PP + 0.618 × (high - low)
S2 = PP - 0.618 × (high - low)
R3 = PP + 1.000 × (high - low)
S3 = PP - 1.000 × (high - low)
Fibonacci Pivot Points Example
Python
from axion import ta
import pandas as pd
import SEOMetadata from '@/components/SEOMetadata';
# Sample OHLC data
df = pd.DataFrame({
'high': [110, 108, 107],
'low': [100, 102, 101],
'close': [105, 106, 104]
})
# Calculate Fibonacci Pivot Points
PP, R1, S1, R2, S2, R3, S3 = ta.fib(df)
print("PP:", PP)
print("R1:", R1)
print("S1:", S1)
print("R2:", R2)
print("S2:", S2)
print("R3:", R3)
print("S3:", S3)Output
PP: 0 105.0
1 105.0
2 104.0
dtype: float64
R1: 0 108.82
1 107.29
2 106.29
dtype: float64
S1: 0 101.18
1 102.71
2 101.71
dtype: float64
R2: 0 111.18
1 108.71
2 107.71
dtype: float64
S2: 0 98.82
1 101.29
2 100.29
dtype: float64
R3: 0 115.0
1 111.0
2 110.0
dtype: float64
S3: 0 95.0
1 99.0
2 98.0
dtype: float64Data Requirements
Most functions require specific columns in the DataFrame. Below are the common requirements:
Basic Price Data
close- Closing pricehigh- Highest pricelow- Lowest pricevolume- Trading volume
Indicator Categories
- Trend Indicators: SMA, EMA, MACD, ADX
- Momentum Indicators: RSI, Stochastic, Williams %R
- Volatility Indicators: Bollinger Bands, ATR, Keltner Channels
- Volume Indicators: OBV, VPT, VWAP