IEX Finance API
A Ruby client for the The IEX Cloud API.
Table of Contents
Installation
Add to Gemfile.
gem 'iex-ruby-client'
Run bundle install
.
Usage
Get an API Token
Create an account on IEX Cloud and get a publishable token from the IEX cloud console.
Configure
IEX::Api.configure do |config|
config.publishable_token = 'publishable_token'
config.secret_token = 'secret_token'
config.endpoint = 'https://cloud.iexapis.com/v1'
end
You can also configure an instance of a client directly.
client = IEX::Api::Client.new(
publishable_token: 'publishable_token',
secret_token: 'secret_token',
endpoint: 'https://cloud.iexapis.com/v1'
)
Get a Single Price
Fetches a single number, being the IEX real time price, the 15 minute delayed market price, or the previous close price.
client.price('MSFT')
See #price for detailed documentation.
Get a Quote
Fetches a single stock quote.
quote = client.quote('MSFT')
quote.latest_price
quote.change
quote.change_percent
quote.change_percent_s
See #quote for detailed documentation or quote.rb for returned fields.
Get a OHLC (Open, High, Low, Close) price
Fetches a single stock OHLC price. Open and Close prices contain timestamp.
ohlc = client.ohlc('MSFT')
ohlc.close.price
ohlc.close.time
ohlc.open.price
ohlc.open.time
ohlc.high
ohlc.low
Get a Market OHLC (Open, High, Low, Close) prices
Fetches a hash market OHLC prices.
market = client.market
market['SPY'].close.price
market['SPY'].close.time
market['SPY'].open.price
market['SPY'].open.time
market['SPY'].high
market['SPY'].low
Get Historical Prices
Fetches a list of historical prices.
There are currently a few limitations of this endpoint compared to the official IEX one.
Options for range
include:
max, ytd, 5y, 2y, 1y, 6m, 3m, 1m, 5d, date
NOTE: If you use the date
value for the range
parameter:
- The options must include a date entry,
{date: ...}
- The date value must be either a Date object, or a string formatted as
YYYYMMDD
. Anything else will result in an IEX::Errors::ClientError
. - The options must include
chartByDay: 'true'
or an ArgumentError
will be raised. - See below for examples.
Query params
supported include:
chartByDay
This is a complicated endpoint as there is a lot of granularity over the time period of data returned. See below for a variety of ways to request data, NOTE: this is NOT as exhaustive list.
historical_prices = client.historical_prices('MSFT')
historical_prices = client.historical_prices('MSFT', {range: 'max'})
historical_prices = client.historical_prices('MSFT', {range: 'ytd'})
historical_prices = client.historical_prices('MSFT', {range: '5y'})
historical_prices = client.historical_prices('MSFT', {range: '6m'})
historical_prices = client.historical_prices('MSFT', {range: '5d'})
historical_prices = client.historical_prices('MSFT', {range: 'date', date: '20200930', chartByDay: 'true'})
historical_prices = client.historical_prices('MSFT', {range: 'date', date: Date.parse('2020-09-30'), chartByDay: 'true'})
...
Once you have the data over the preferred time period, you can access the following fields
historical_prices = client.historical_prices('MSFT')
historical_price = historical_prices.first
historical_price.date
historical_price.open
historical_price.open_dollar
historical_price.close
historical_price.close_dollar
historical_price.high
historical_price.high_dollar
historical_price.low
historical_price.low_dollar
historical_price.volume
...
There are a lot of options here so I would recommend viewing the official IEX documentation #historical-prices or historical_prices.rb for returned fields.
Get Company Information
Fetches company information for a symbol.
company = client.company('MSFT')
company.ceo
company.company_name
See #company for detailed documentation or company.rb for returned fields.
Get a Company Logo
Fetches company logo for a symbol.
logo = client.logo('MSFT')
logo.url
See #logo for detailed documentation or logo.rb for returned fields.
Get Recent News
Fetches news for a symbol.
news = client.news('MSFT')
news.size
latest = news.first
latest.headline
latest.url
Retrieve a range between 1 and 50.
news = client.news('MSFT', 5)
See #news for detailed documentation or news.rb for returned fields.
Get Chart
Fetches charts for a symbol.
chart = client.chart('MSFT')
chart.size
first = chart.first
first.label
first.high
You can specify a chart range and additional options.
client.chart('MSFT', 'dynamic')
client.chart('MSFT', Date.new(2018, 3, 26))
client.chart('MSFT', '1d', chart_interval: 10)
Note that calling the chart API weighs more than 1 IEX message (you pay more than 1 call).
# 1 message per minute capped at 50 messages to intraday_prices
client.chart('MSFT', '1d')
# 2x22 trading days = 44 messages to historical_close_prices
client.chart('MSFT', '1m', chart_close_only: true)
# 2x251 trading days = 502 messages to historical_close_prices
client.chart('MSFT', '1y', chart_close_only: true)
Get Key Stats
Fetches company's key stats for a symbol.
key_stats = client.key_stats('MSFT')
key_stats.week_52_change_dollar
key_stats.week_52_high
key_stats.week_52_high_dollar
key_stats.week_52_low
key_stats.week_52_low_dollar
key_stats.market_cap
key_stats.market_cap_dollar
key_stats.employees
key_stats.day_200_moving_avg
key_stats.day_50_moving_avg
key_stats.float
key_stats.avg_10_volume
key_stats.avg_30_volume
key_stats.ttm_eps
key_stats.ttm_dividend_rate
key_stats.company_name
key_stats.shares_outstanding
key_stats.max_change_percent
key_stats.year_5_change_percent
key_stats.year_5_change_percent_s
key_stats.year_2_change_percent
key_stats.year_2_change_percent_s
key_stats.year_1_change_percent
key_stats.year_1_change_percent_s
key_stats.ytd_change_percent
key_stats.ytd_change_percent_s
key_stats.month_6_change_percent
key_stats.month_6_change_percent_s
key_stats.month_3_change_percent
key_stats.month_3_change_percent_s
key_stats.month_1_change_percent
key_stats.month_1_change_percent_s
key_stats.day_30_change_percent
key_stats.day_30_change_percent_s
key_stats.day_5_change_percent
key_stats.day_5_change_percent_s
key_stats.next_dividend_date
key_stats.dividend_yield
key_stats.next_earnings_date
key_stats.ex_dividend_date
key_stats.pe_ratio
key_stats.beta
You can also fetch a single stat for a symbol. Note that IEX uses lowerCamelCase
for the names of the stats.
client.key_stat('VTI', 'dividendYield')
See #key-stats for detailed documentation or key_stats.rb for returned fields.
Get Advanced Stats
Fetches company's advanced stats for a symbol, this will include all key stats as well.
advanced_stats = client.advanced_stats('MSFT')
advanced_stats.total_cash
advanced_stats.total_cash_dollars
advanced_stats.current_debt
advanced_stats.current_debt_dollars
advanced_stats.revenue
advanced_stats.revenue_dollars
advanced_stats.gross_profit
advanced_stats.gross_profit_dollar
advanced_stats.total_revenue
advanced_stats.total_revenue_dollar
advanced_stats.ebitda
advanced_stats.ebitda_dollar
advanced_stats.revenue_per_share
advanced_stats.revenue_per_share_dollar
advanced_stats.revenue_per_employee
advanced_stats.revenue_per_employee_dollar
advanced_stats.debt_to_equity
advanced_stats.profit_margin
advanced_stats.enterprise_value
advanced_stats.enterprise_value_dollar
advanced_stats.enterprise_value_to_revenue
advanced_stats.price_to_sales
advanced_stats.price_to_sales_dollar
advanced_stats.price_to_book
advanced_stats.forward_pe_ratio
advanced_stats.pe_high
advanced_stats.pe_low
advanced_stats.peg_ratio
advanced_stats.week_52_high_date
advanced_stats.week_52_low_date
advanced_stats.beta
advanced_stats.put_call_ratio
...
See #advanced-stats for detailed documentation or advanced_stats.rb for returned fields.
Get Dividends
Fetches dividends for a symbol.
dividends = client.dividends('MSFT', '6m')
dividends.payment_date
dividends.record_date
dividends.declared_date
dividends.amount
See #dividends for detailed documentation or dividends.rb for returned fields.
Get Earnings
Fetches earnings for a symbol.
earnings = client.earnings('MSFT')
earnings.actual_eps
earnings.consensus_eps
earnings.announce_time
earnings.number_of_estimates
earnings.eps_surprise_dollar
earnings.eps_report_date
earnings.fiscal_period
earnings.fiscal_end_date
earnings.year_ago
earnings.year_ago_change_percent
earnings.year_ago_change_percent_s
See #earnings for detailed documentation or earnings.rb for returned fields.
Get Income Statement
Fetches income statements for a symbol.
income_statements = client.income('MSFT')
income = income_statements.first
income.report_date
income.fiscal_date
income.currency
income.total_revenue
income.total_revenue_dollar
income.cost_of_revenue
income.cost_of_revenue_dollar
income.gross_profit
income.gross_profit_dollar
...
See #income-statement for detailed documentation or income.rb for returned fields.
Get Balance Sheet
Fetches balance sheets for a symbol.
balance_sheets = client.balance_sheet('MSFT')
balance_sheet = balance_sheets.first
balance_sheet.report_date
balance_sheet.fiscal_date
balance_sheet.currency
balance_sheet.current_cash
balance_sheet.current_cash_dollar
balance_sheet.short_term_investments
balance_sheet.short_term_investments_dollar
...
See #balance-sheet for detailed documentation or balance_sheet.rb for returned fields.
Get Cash Flow Statement
Fetches cash flow statements for a symbol.
cash_flow_statements = client.cash_flow('MSFT')
cash_flow = cash_flow_statements.first
cash_flow.report_date
cash_flow.fiscal_date
cash_flow.currency
cash_flow.net_income
cash_flow.net_income_dollar
cash_flow.depreciation
cash_flow.depreciation_dollar
...
See #cash-flow for detailed documentation or cash_flow.rb for returned fields.
Get Sector Performance
Fetches latest sector's performance.
sectors = client.sectors('MARKET')
sectors.type
sectors.name
sectors.performance
sectors.last_updated
See #sector-performance for detailed documentation or sectors.rb for returned fields.
Get Largest Trades
Fetches largest trades in the day for a specific stock. Ordered by largest trade on the top.
trades = client.largest_trades('aapl')
trades.first.price
trades.first.size
trades.first.time
trades.first.time_label
trades.first.venue
trades.first.venue_name
See #largest-trades for detailed documentation or largest_trades.rb for returned fields.
Get a Quote for Crypto Currencies
Fetches a crypto currency quote.
crypto = client.crypto('BTCUSDT')
crypto.symbol
crypto.company_name
crypto.primary_exchange
crypto.sector
crypto.calculation_price
crypto.open
crypto.open_dollar
crypto.open_time
crypto.close
crypto.close_dollar
crypto.close_time
crypto.high
crypto.high_dollar
See #crypto for detailed documentation or crypto.rb for returned fields.
ISIN Mapping
Convert ISIN to IEX Cloud symbols.
symbols = client.ref_data_isin('US0378331005')
symbols.first.exchange
symbols.first.iex_id
symbols.first.region
symbols.first.symbol
The API also lets you convert multiple ISINs to IEX Cloud symbols.
symbols = client.ref_data_isin(['US0378331005', 'US0378331006'])
You can use mapped: true
option to receive symbols grouped by their ISINs.
client.ref_data_isin(['US0378331005', 'US5949181045'], mapped: true)
See #ISIN Mapping for detailed documentation or isin_mapping.rb for returned fields.
Get Symbols
Returns an array of symbols.
symbols = client.ref_data_symbols()
symbol = symbols.first
symbol.exchange
symbol.iex_id
symbol.region
symbol.symbol
See #symbols for detailed documentation or symbols.rb for returned fields.
Get Symbols for an Exchange
Returns an array of symbols for an exchange identified by a market identifier code.
symbols = client.ref_data_symbols_for_exchange('XTSE')
symbol = symbols.first
symbol.exchange
symbol.iex_id
symbol.region
symbol.symbol
See #international-symbols for returned fields.
Get Symbols for a Region
Returns an array of symbols for a region.
symbols = client.ref_data_symbols_for_region('ca')
symbol = symbols.first
symbol.exchange
symbol.iex_id
symbol.region
symbol.symbol
Get Latest Foreign Exchange Rates
Returns an array of foreign exchange rates for a given list of symbols.
rates = client.fx_latest(['USDCAD', 'USDGBP', 'USDJPY'])
rate = rates.first
rate.symbol
rate.rate
rate.timestamp
See #latest-currency-rates for returned fields.
Get List
Returns an array of quotes for the top 10 symbols in a specified list.
client.stock_market_list(:mostactive)
See #list for detailed documentation or quote.rb for returned fields.
Other Requests
Public endpoints that aren't yet supported by the client can be called using client.get
, client.post
, client.put
and client.delete
methods. Pass the required token explicitly:
client.post('ref-data/isin', isin: ['US0378331005'], token: 'secret_token')
Configuration
You can configure client options globally or directly with a IEX::Api::Client
instance.
IEX::Api.configure do |config|
config.publishable_token = ENV['IEX_API_PUBLISHABLE_TOKEN']
config.endpoint = 'https://sandbox.iexapis.com/v1'
end
client = IEX::Api::Client.new(
publishable_token: ENV['IEX_API_PUBLISHABLE_TOKEN'],
endpoint: 'https://cloud.iexapis.com/v1'
)
The following settings are supported.
setting | description |
---|
user_agent | User-agent, defaults to IEX Ruby Client/version. |
proxy | Optional HTTP proxy. |
ca_path | Optional SSL certificates path. |
ca_file | Optional SSL certificates file. |
logger | Optional Logger instance or logger configuration to log HTTP requests. |
timeout | Optional open/read timeout in seconds. |
open_timeout | Optional connection open timeout in seconds. |
publishable_token | IEX Cloud API publishable token. |
endpoint | Defaults to https://cloud.iexapis.com/v1 . |
referer | Optional string for HTTP Referer header, enables token domain management. |
Logging
Faraday will not log HTTP requests by default. In order to do this you can either provide a logger
instance or configuration attributes to IEX::Api::Client
. Configuration allows you to supply the instance
, options
, and proc
to Faraday.
logger_instance = Logger.new(STDOUT)
IEX::Api.configure do |config|
config.logger.instance = logger_instance
config.logger.options = { bodies: true }
config.logger.proc = proc { |logger| logger.filter(/T?[sp]k_\w+/i, '[REMOVED]') }
end
IEX::Api.logger do |logger|
logger.instance = logger_instance
logger.options = …
logger.proc = …
end
IEX::Api.logger = logger_instance
IEX::Api::Client.new(logger: logger_instance)
Sandbox Environment
IEX recommends you use a sandbox token and endpoint for testing.
However, please note that data in the IEX sandbox environment is scrambled. Therefore elements such as company and people names, descriptions, tags, and website URLs don't render any coherent data. In addition, results, such as closing market prices and dividend yield, are not accurate and vary on every call.
See IEX sandbox environment for more information.
Errors
SymbolNotFound
If a symbol cannot be found an IEX::Errors::SymbolNotFound exception is raised.
PermissionDeniedError
All errors that return HTTP code 403 result in a IEX::Errors::PermissionDeniedError exception.
ClientError
All errors that return HTTP codes 400-600 result in a IEX::Errors::ClientError exception.
Contributing
See CONTRIBUTING.
Copyright and License
Copyright (c) 2018-2019, Daniel Doubrovkine and Contributors.
This project is licensed under the MIT License.
Data provided for free by IEX, see terms.