Skip to main content

Ally Invest API Wrapper

Project description

PyAlly

Python3 wrapper for Ally Invest brokerage API

Ally Bank's investment platform is perfect for smaller investors who value a mature web/mobile interface, and low brokerage fees. I made this wrapper so that I could more easily integrate the platform with Python, and reduce the need for human oversight on my account.

After setting up API keys, PyAlly can provide the basic/essential Ally brokerage transaction functions from a simple python request.

Supported features

  • Stock buy/sell/short/buy-to-cover orders
  • Query account transaction history
  • Represent account holdings
  • Query account holdings
  • Orders supported:
    • Market
    • Stop
    • Limit
    • Stop Limit
    • Stop Loss
  • Instrument quotes
  • Option trading

Requirements

  • requests-oathlib
  • matplotlib

Installation

pip3 install pyally

Once the package is downloaded, we recommend setting environment variables to store Ally API credentials.

Log into Ally Invest, go to the specific account page, click Tools->API

Tools

Fill out the API token application as a Personal Application

New Application

Enter the API tokens and secrets into your environment variables

Details

Insert the following into ~/.bashrc:

export ALLY_CONSUMER_KEY=XXXXXXXXXXXXXXXXXXXXXXXX
export ALLY_CONSUMER_SECRET=XXXXXXXXXXXXXXXXXXXXX
export ALLY_OATH_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXX
export ALLY_OATH_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXX

Documentation

Initialize

import ally
a = ally.Ally()

Account Functions

Transaction History

#	Get transaction history in JSON dictionary form
#		- Optionally specify account, if not in set in
#		environment
#		- Optionally specify type of transaction, must be 
#			"all", "bookkeeping", or "trade"
#            [default "all"]
#        - Optionally specify time window for transactions, must be in 
#            "all", "today", "current_week", "current_month", "last_month"
#            [default "all"]
trans_history = a.account_history(
	account=12345678,
	type="all",
    range="current_week"
)

Current Account Holdings

#    Get current holdings for an account in JSON dict format
#        Uses default account if not specified
#        Optionally dump json to file
current_holdings = a.get_holdings(
    account=12345678,
    outfile="./holdings.json"
)

Holdings Pie Chart

#    Create pie graph of asset allocations for account, using matplotib
#    Dumps to file ./graph.png by default
#        Specify account optionally
#        - specify regen=True to prevent outputting cached graph [default False]
pie_file = a.holdings_chart(
    account=12345678,
    graph_file="./my_graph_file.png",
    regen=True
)

Live Quotes

#    Get quote:
#        Go to
#            https://www.ally.com/api/invest/documentation/market-ext-quotes-get-post/
#        to see available fields options
#        [defaults to None]
quote = a.get_quote(
    symbols="SPY,ALLY",
    fields="ask,bid,vol"
)

Instruments

Equity

Equity("SPY")     # Perfectly equivalent statements
Instrument('spy') # Perfectly equivalent statements

Option

Call (
    instrument    = Equity("spy"), # Underlying
    maturity_date = "2019-09-30",  # Expiration date
    strike        = 290            # Strike
)

Put (
    instrument    = Instrument("ALLY"), # Underlying
    maturity_date = "2019-10-18",       # Expiration date
    strike        = 300                 # Strike
)

Orders

Order( timespan, type, price, instrument, quantity)

market_buy = ally.order.Order(

    # Good for day order
    timespan   = ally.order.Timespan('day'),

    # Buy order (to_open is True by defaul)
    type       = ally.order.Buy(),

    # Market order
    price      = ally.order.Market(),

    # Stock, symbol F
    instrument = ally.instrument.Equity('f'),

    # 1 share
    quantity   = ally.order.Quantity(1)
)

TimeInForce (Timespans)

#### Timespans
Timespan('day')
Timespan('gtc')
Timespan('marketonclose')

Types

Buy()              # Buy to open (default)
Buy(to_open=False) # Buy to cover

Sell()              # Sell short (default)
Sell(to_open=False) # Sell to close

Pricing

Market ()         # Give me anything
Limit (69)        # Execute at least as favorably as $69.00
Stop (4.20)       # Stop order at $4.20
StopLimit (
    Stop  (10),   # Stop at $10.00
    Limit (9.50)  # No worse than $9.50
)
StopLoss (
    isBuy=False,  # Interpret stop as less than current price
    pct=True,     # Treat 'stop' as pct
    stop=5.0      # Stop at 5% from highest achieved after order placed
)
StopLoss (
    isBuy=True,   # Interpret stop as less than current price
    pct=False,    # Treat 'stop' as pct
    stop=5.0      # Stop at $5.00 above lowest price
)

Quantity

Quantity ( 15 )  # In shares or lots, for an option

Submitting an Order

exec_status = a.submit_order(

    # specify order created, see above
    order=,

    # Can dry-run using preview=True, defaults to True
    # Must specify preview=False to actually execute
    preview=True,

    # Like always, if not specified in environment, use a specific account
    account=12345678
)

Author

Contributing

Please contact me if you enjoyed the project or thought it could be improved. I do my best to code with quality but sometimes it is easier said than done. Anyone with an interest with an eye for detail is welcome to contribute.

Project details


Download files

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

Source Distribution

pyally-0.2.2.tar.gz (12.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyally-0.2.2-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file pyally-0.2.2.tar.gz.

File metadata

  • Download URL: pyally-0.2.2.tar.gz
  • Upload date:
  • Size: 12.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.8.0 tqdm/4.33.0 CPython/3.7.3

File hashes

Hashes for pyally-0.2.2.tar.gz
Algorithm Hash digest
SHA256 47aefeace20c4d7f9b22841c28e0f996766b74c85eef19d3128eca5320fa4268
MD5 f5f70ebc2836d11cca7ea0facef0d9bb
BLAKE2b-256 7075568a9a0bfd84ecbbd36ad192b49d3a7a14d770b01c53667d2ff4e6f7402d

See more details on using hashes here.

File details

Details for the file pyally-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: pyally-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 11.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.8.0 tqdm/4.33.0 CPython/3.7.3

File hashes

Hashes for pyally-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 bd3ea648f1bf7097775b4cd09524e6129176417e4b993733e3e6e7d81cf03578
MD5 3a8b6fbb8a52277bf9f2621ff5e73b89
BLAKE2b-256 9fc2d0a671cd9ccdc4df83abf08befaf8b2e74f423e5fbda599eecc6047706ac

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page