Skip to main content

Rest API to IEX

Project description

pyEX

Python interface to IEX Cloud (https://iexcloud.io/docs/api/)

Build Status Coverage License PyPI Docs

Referral

Please subscribe to IEX Cloud using my referral code.

Getting Started

Install

Install from pip

pip install pyEX

of from source

python setup.py install

Extensions

  • pyEX[async]: asyncio integration for streaming APIs
  • pyEX[studies]: Technical indicators and other calculations

Demos + Docs

Overview

pyEX supports the IEX Cloud api through 2 interfaces. The first is a simple function call, passing in the api version and token as arguments

In [1]: import pyEX as p

In [2]: p.chart?
Signature: p.chart(symbol, timeframe='1m', date=None, token='', version='', filter='')
Docstring:
Historical price/volume data, daily and intraday

https://iexcloud.io/docs/api/#historical-prices
Data Schedule
1d: -9:30-4pm ET Mon-Fri on regular market trading days
    -9:30-1pm ET on early close trading days
All others:
    -Prior trading day available after 4am ET Tue-Sat

Args:
    symbol (str); Ticker to request
    timeframe (str); Timeframe to request e.g. 1m
    date (datetime): date, if requesting intraday
    token (str); Access token
    version (str); API version
    filter (str); filters: https://iexcloud.io/docs/api/#filter-results

Returns:
    dict: result

For most calls, there is a convenience method that returns a dataframe as well:

In [5]: [_ for _ in dir(p) if _.endswith('DF')]
Out[5]:
['advancedStatsDF',
 'auctionDF',
 'balanceSheetDF',
 'batchDF',
 'bookDF',
 'bulkBatchDF',
 'bulkMinuteBarsDF',
 'calendarDF',
...

Since the token rarely changes, we have a Client object for convenience:

In [6]: p.Client?
Init signature: p.Client(api_token=None, version='v1', api_limit=5)
Docstring:
IEX Cloud Client

Client has access to all methods provided as standalone, but in an authenticated way

Args:
    api_token (str): api token (can pickup from IEX_TOKEN environment variable)
    version (str): api version to use (defaults to v1)
                      set version to 'sandbox' to run against the IEX sandbox
    api_limit (int): cache calls in this interval
File:           ~/Programs/projects/iex/pyEX/pyEX/client.py
Type:           type
Subclasses:

The client will automatically pick up the API key from the environment variable IEX_TOKEN, or it can be passed as an argument. To use the IEX Cloud test environment, simple set version='sandbox'.

In [8]: c = p.Client(version='sandbox')

In [9]: c.chartDF('AAPL').head()
Out[9]:
              open   close    high     low    volume   uOpen  uClose   uHigh    uLow   uVolume  change  changePercent   label  changeOverTime
date
2019-11-27  271.31  274.04  277.09  268.75  16994433  267.69  271.99  271.82  266.32  16811747    0.00         0.0000  Nov 27        0.000000
2019-11-29  271.30  272.19  280.00  279.20  12135259  270.90  275.02  270.00  267.10  11927464   -0.60        -0.2255  Nov 29       -0.002232
2019-12-02  279.96  265.23  276.41  267.93  23831255  279.97  266.80  281.32  269.29  24607845   -3.20        -1.1646   Dec 2       -0.013820
2019-12-03  261.54  271.05  259.96  262.09  30331487  259.87  271.34  269.02  260.71  30518449   -4.93        -1.8450   Dec 3       -0.032745
2019-12-04  272.81  273.56  271.26  267.06  17109161  267.30  262.82  274.99  270.83  17230517    2.39         0.8955   Dec 4       -0.023411

Improvements over native API, other libraries, etc

  • pyEX will transparently cache requests according to the refresh interval as defined on the IEX Cloud website (and in the docstrings), to avoid wasting credits. It can also cache to disk, or integrate with your own custom caching scheme.
  • pyEX fully implements the streaming APIs

Other enhancements

  • pyEX-studies: pyEX integration with TA-Lib and other libraries, for technical analysis and other metrics on top of the IEX data
  • pyEX-caching: persistent, queryable caching for pyEX function calls. Minimize your spend and maximize your performance
  • pyEX-zipline: Zipline integration for IEX data

Demo

Rules Engine

pyEX implements methods for interacting with the Rules Engine.

rule = {
        'conditions': [['changePercent','>',500],
                       ['latestPrice','>',100000]],
        'outputs': [{'frequency': 60,
                     'method': 'email',
                     'to': 'your_email@domain'
                    }]
        }

c.createRule(rule, 'MyTestRule', 'AAPL', 'all')  # returns {"id": <ruleID>, "weight": 2}

c.rules()  # list all rules
c.ruleInfo("<ruleID>")
c.ruleOutput("<ruleID>")
c.pauseRule("<ruleID>")
c.resumeRule("<ruleID>")
c.deleteRule("<ruleID>")

We also provide helper classes in python for constructing rules such that they abide by the rules schema (dictated in the schema() helper function)

Methods

Data

pyEX provides wrappers around both static and SSE streaming data. For most static data endpoints, we provide both JSON and DataFrame return functions. For market data endpoints, we provide async wrappers as well using aiohttp (to install the dependencies, pip install pyEX[async]).

DataFrame functions will have the suffix DF, and async functions will have the suffix Async.

SSE streaming data can either be used with callbacks:

newsSSE('AAPL', on_data=my_function_todo_on_data)

or via async generators (after installing pyEX[async]):

async for data in newsSSE('AAPL'):

Full API

Please see the readthedocs for a full API spec

Currently, the following methods are implemented:

Data Points

Markets

  • markets
  • marketsDF

Account

Stocks

Stock Prices

Stock Profiles

Stock Fundamentals

Stock Research

Corporate Actions

Market Info

News

Time Series

Bulk

  • batch
  • batchDF
  • bulkBatch
  • bulkBatchDF
  • bulkMinuteBars
  • bulkMinuteBarsDF

Old/Unknown/Deprecated

  • spread
  • spreadDF
  • shortInterest
  • shortInterestDF
  • marketShortInterest
  • marketShortInterestDF
  • relevant
  • relevantDF

Crypto

FX

EOD Options

CEO Compensation

Treasuries

Daily Treasury Rates

Commodities

Economic Data

Reference Data

Other Reference

  • corporateActions
  • corporateActionsDF
  • refDividends
  • refDividendsDF
  • nextDayExtDate
  • nextDayExtDateDF
  • directory
  • directoryDF
  • calendar
  • calendarDF

IEX Data

TOPS

Stats

  • daily
  • dailyDF
  • summary
  • summaryDF
  • systemStats
  • systemStatsDF
  • recent
  • recentDF
  • records
  • recordsDF

Alternative

  • crypto
  • cryptoDF
  • sentiment
  • sentimentDF

Streaming Data

SSE Streaming

Stocks

News

Sentiment

  • sentimentSSE
  • sentimentSSEAsync

FX

  • fxSSE
  • fxSSEAsync

Crypto

  • cryptoBookSSE
  • cryptoBookSSEAsync
  • cryptoEventsSSE
  • cryptoEventsSSEAsync
  • cryptoQuotesSSE
  • cryptoQuotesSSEAsync

Premium Data

Wall Street Horizon

Fraud Factors

Extract Alpha

Precision Alpha

BRAIN Company

Kavout

Audit Analytics

ValuEngine

StockTwits Sentiment

Studies

Available via pyEX[studies].

Studies

  • peerCorrelation

Technicals

These are built on TA-lib. Note that these are different from the technicals available via IEX Cloud's technicals endpoint.

Cycle

  • ht_dcperiod: Hilbert Transform - Dominant Cycle Period
  • ht_dcphase: Hilbert Transform - Dominant Cycle Phase
  • ht_phasor: Hilbert Transform - Phasor Components
  • ht_sine: Hilbert Transform - SineWave
  • ht_trendmode: Hilbert Transform - Trend vs Cycle Mode

Math

  • acos: Vector Trigonometric ACos
  • asin: Vector Trigonometric ASin
  • atan: Vector Trigonometric ATan
  • ceil: Vector Ceil
  • cos: Vector Trigonometric Cos
  • cosh: Vector Trigonometric Cosh
  • exp: Vector Arithmetic Exp
  • floor: Vector floor
  • ln: Vector Log natural
  • log10: Vector Log10
  • sin: Vector Trigonometric Sin
  • sinh: Vector Trigonometric Sinh
  • sqrt: Vector Square Root
  • tan: Vector Trigonometric Tan
  • tanh: Vector Trigonometric Tanh
  • add: Vector Arithmetic Add
  • div: Vector Arithmetic Div
  • max: Highest value over a specified period
  • maxindex: Index of highest value over a specified period
  • min: Lowest value over a specified period
  • minindex: Index of lowest value over a specified period
  • minmax: Lowest and highest values over a specified period
  • minmaxindex: Index of lowest and highest values over a specified period
  • mult: Vector Arithmetic Mult
  • sub: Vector Arithmetic Subtraction
  • sum: Summation

Momentum

  • adx: Average Directional Movement Index
  • adxr: Average Directional Movement Index Rating
  • apo: Absolute Price Oscillator
  • aroon: Aroon
  • aroonosc: Aroon Oscillator
  • bop: Balance Of Power
  • cci: Commodity Channel Index
  • cmo: Chande Momentum Oscillator
  • dx: Directional Movement Index
  • macd: Moving Average Convergence/Divergence
  • macdext: MACD with controllable MA type
  • mfi: Money Flow Index
  • minus_di: Minus Directional Indicator
  • minus_dm: Minus Directional Movement
  • mom: Momentum
  • plus_di: Plus Directional Indicator
  • plus_dm: Plus Directional Movement
  • ppo: Percentage Price Oscillator
  • roc: Rate of change : ((price/prevPrice)-1)*100
  • rocp: Rate of change Percentage: (price-prevPrice)/prevPrice
  • rocr: Rate of change ratio: (price/prevPrice)
  • rocr100: Rate of change ratio 100 scale: (price/prevPrice)*100
  • rsi: Relative Strength Index
  • stoch: Stochastic
  • stochf: Stochastic Fast
  • stochrsi: Stochastic Relative Strength Index
  • trix: 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
  • ultosc: Ultimate Oscillator
  • willr: Williams' %R

Overlap

  • bollinger: Bollinger Bands
  • dema: Double Exponential Moving Average
  • ema: Exponential Moving Aberage
  • ht_trendline: Hilbert Transform - Instantaneous Trendline
  • kama: Kaufman Adaptive Moving Average
  • mama: MESA Adaptive Moving Average
  • mavp: Moving average with variable period
  • midpoint: Midpoint over period
  • midpice: Midpoint price over period
  • sar: Parabolic SAR
  • sarext: Parabolic SAR - Extended
  • sma: Moving Average
  • t3: Triple Exponential Moving Average (T3)
  • tema: Triple Exponential Moving Average
  • trima: Triangular Moving Average
  • wma: Weighted Moving Average

Pattern

  • cdl2crows: Two Crows
  • cdl3blackcrows: Three Black Crows
  • cdl3inside: Three Inside Up/Down
  • cdl3linestrike: Three-Line Strike
  • cdl3outside: Three Outside Up/Down
  • cdl3starsinsouth: Three Stars In The South
  • cdl3whitesoldiers: Three Advancing White Soldiers
  • cdlabandonedbaby: Abandoned Baby
  • cdladvanceblock: Advance Block
  • cdlbelthold: Belt-hold
  • cdlbreakaway: Breakaway
  • cdlclosingmarubozu: Closing Marubozu
  • cdlconcealbabyswall: Concealing Baby Swallow
  • cdlcounterattack: Counterattack
  • cdldarkcloudcover: Dark Cloud Cover
  • cdldoji: Doji
  • cdldojistar: Doji Star
  • cdldragonflydoji: Dragonfly Doji
  • cdlengulfing: Engulfing Pattern
  • cdleveningdojistar: Evening Doji Star
  • cdleveningstar: Evening Star
  • cdlgapsidesidewhite: Up/Down-gap side-by-side white lines
  • cdlgravestonedoji: Gravestone Doji
  • cdlhammer: Hammer
  • cdlhangingman: Hanging Man
  • cdlharami: Harami Pattern
  • cdlharamicross: Harami Cross Pattern
  • cdlhighwave: High-Wave Candle
  • cdlhikkake: Hikkake Pattern
  • cdlhikkakemod: Modified Hikkake Pattern
  • cdlhomingpigeon: Homing Pigeon
  • cdlidentical3crows: Identical Three Crows
  • cdlinneck: In-Neck Pattern
  • cdlinvertedhammer: Inverted Hammer
  • cdlkicking: Kicking
  • cdlkickingbylength: Kicking - bull/bear determined by the longer marubozu
  • cdlladderbottom: Ladder Bottom
  • cdllongleggeddoji: Long Legged Doji
  • cdllongline: Long Line Candle
  • cdlmarubozu: Marubozu
  • cdlmatchinglow: Matching Low
  • cdlmathold: Mat Hold
  • cdlmorningdojistar: Morning Doji Star
  • cdlmorningstar: Morning Star
  • cdlonneck: On-Neck Pattern
  • cdlpiercing: Piercing Pattern
  • cdlrickshawman: Rickshaw Man
  • cdlrisefall3methods: Rising/Falling Three Methods
  • cdlseparatinglines: Separating Lines
  • cdlshootingstar: Shooting Star
  • cdlshortline: Short Line Candle
  • cdlspinningtop: Spinning Top
  • cdlstalledpattern: Stalled Pattern
  • cdlsticksandwich: Stick Sandwich
  • cdltakuri: Takuri (Dragonfly Doji with very long lower shadow)
  • cdltasukigap: Tasuki Gap
  • cdlthrusting: Thrusting Pattern
  • cdltristar: Tristar Pattern
  • cdlunique3river: Unique 3 River
  • cdlupsidegap2crows: Upside Gap Two Crows
  • cdlxsidegap3methods: Upside/Downside Gap Three Methods

Price

  • avgprice: Average Price
  • medprice: Median Price
  • typprice: Typical Price
  • wclprice: Weighted Close Price

Statistic

  • beta: Beta
  • correl: Pearson's Correlation Coefficient (r)
  • linearreg: Linear Regression
  • linearreg_angle: Linear Regression Angle
  • linearreg_intercept: Linear Regression Intercept
  • linearreg_slope: Linear Regression Slope
  • stddev: Standard Deviation
  • tsf: Time Series Forecast
  • var: Variance

Volatility

  • atr: Average True Range
  • natr: Normalized Average True Range
  • trange: True Range

Volume

  • ad: Chaikin A/D Line
  • adosc: Chaikin A/D Oscillator
  • obv: On Balance Volume

Attribution

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for pyEX, version 0.2.8
Filename, size File type Python version Upload date Hashes
Filename, size pyEX-0.2.8-py2.py3-none-any.whl (136.4 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size pyEX-0.2.8.tar.gz (120.5 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page