Skip to main content

pyhood

pyhood logo

A modern, reliable Python client for the Robinhood API.

CI PyPI Docs Python 3.10+ License: MIT Coverage Security Code style: ruff

A modern, reliable Python client for the Robinhood API.

Built for automated trading — with auth that doesn't break, proper error handling, and sane defaults.

How pyhood compares

Against robin_stocks and its actively maintained fork robin_stocks_v2:

pyhood robin_stocks robin_stocks_v2
Silent session refresh — renew a session with no credentials and no device approval ✅ ❌ ❌
IRA / retirement accounts — trade stocks and options in Traditional and Roth IRAs ✅ ❌ ❌
Official Crypto Trading API — Ed25519 key auth, not the unofficial endpoints ✅ ❌ ❌
Futures positions ✅ ❌ stub, returns None
Futures contracts & quotes ✅ ❌ ✅
IPO Access ✅ ❌ ✅
Typed responses — dataclasses with full annotations, not raw dicts ✅ ❌ partial
Index options (SPX, NDX, VIX, RUT, XSP) ✅ partial ✅
Session storage JSON pickle JSON
Order history date filter ✅ ✅ ✅
Minimum Python 3.10 3.9 3.10

If your automation keeps dying because a session expired and nobody was around to approve a device prompt, that is the row that matters. Silent refresh, retirement accounts, and the official crypto API are pyhood-only.

On futures positions: the endpoint lives at ceres/v1/accounts/{id}/positions/. It was previously undiscovered — the fork ships a placeholder that prints "endpoint not yet discovered" and returns None.

On pickle: robin_stocks stores sessions with pickle, which deserializes arbitrary objects (CWE-502); a fix has been open since March 2026. pyhood has always used JSON; the fork has since switched.

robin_stocks is the original and by far the most widely used — it earned that. But its last merge was February 2026, and its own issue tracker now points newcomers to the fork. If you are migrating, pyhood is worth a look.

Verified against both repositories on 2026-08-09 by reading their source, not their docs. Corrections welcome — open an issue if anything here is out of date.

Why pyhood?

  • 🪙 Dual API support — The only Python library that wraps both Robinhood's unofficial stocks/options API and their official Crypto Trading API. One library, full coverage.

  • 🔐 Auth that just works — Login with timeouts, automatic token refresh, and session persistence. Authenticate once, stay connected for days. No more scripts that hang forever waiting for device approval.

  • 🔄 Automatic token refresh — pyhood uses OAuth refresh tokens to renew your session silently — no credentials, no device approval, no human in the loop. Built for unattended automation.

  • 🏷️ Type hints everywhere — Full type annotations, dataclass responses, IDE-friendly. No more guessing what's in a dict.

  • 🛡️ Built-in rate limiting — Automatic request throttling and retry logic so you don't get locked out.

  • 📊 Options-first — Deep options chain support with Greeks, volume/OI analysis, and earnings integration. Supports both equity and index options (SPX, NDX, VIX, RUT).

  • 📈 Futures trading — Contract details, real-time quotes, open positions, order history, and P&L calculation for Robinhood futures.

  • 🎯 IPO Access — Read Robinhood's retail IPO allocation program: available offerings, eligibility, allocation results, and your IPO orders.

  • 🏦 IRA/Retirement accounts — Trade stocks and options in Traditional and Roth IRAs. The only Python Robinhood library with retirement account support.

  • 💰 Banking & dividends — Query ACH transfers, linked bank accounts, debit card transactions, and dividend history.

  • 📋 Watchlists — Create, manage, and modify your Robinhood watchlists programmatically.

  • 🔍 Research & discovery — Analyst ratings, news feed, S&P 500 movers, trending stocks, instrument popularity, and stock splits.

  • 📑 Portfolio & documents — Portfolio historicals, option historicals, account statements, and trade confirmations.

  • 🧪 Tested and maintained — 259 tests, CI across Python 3.10-3.13, linted with ruff. If it breaks, we know immediately.

Quick Start

import pyhood
from pyhood.client import PyhoodClient

# Login (with timeout — never hangs)
session = pyhood.login(username="you@email.com", password="...", timeout=90)
client = PyhoodClient(session)

# Stock data
quote = client.get_quote("AAPL")
print(f"AAPL: ${quote.price:.2f} ({quote.change_pct:+.1f}%)")

# Options chains (works for equities and indexes)
chain = client.get_options_chain("SPX", expiration="2026-04-17")
for option in chain.calls:
    print(f"  {option.strike} call | IV: {option.iv:.0%} | Delta: {option.delta:.2f}")

# Account
positions = client.get_positions()
balance = client.get_buying_power()

IRA Trading

pyhood can discover and trade in IRA/retirement accounts — something no other Python Robinhood library supports.

# Discover all accounts (including IRA)
accounts = client.get_all_accounts()

# Check IRA buying power
bp = client.get_buying_power(account_number="YOUR_IRA_ACCOUNT")

# Buy options in your Roth IRA
order = client.buy_option(
    symbol="NKE", strike=55.0, expiration="2026-04-02",
    option_type="call", quantity=3, price=1.60,
    account_number="YOUR_IRA_ACCOUNT",
)

See the Account documentation for details on IRA account discovery and limitations.

Authentication

Robinhood requires device approval on first login. After that, pyhood keeps your session alive automatically.

First Login

  1. Have the Robinhood mobile app open on your phone
  2. Call pyhood.login() — it will trigger a device approval request
  3. Tap "Yes, it's me" in the Robinhood app when prompted
  4. pyhood saves the session token to ~/.pyhood/session.json for reuse
import pyhood

# First login — will wait up to 90s for you to approve on phone
session = pyhood.login(
    username="you@email.com",
    password="your_password",
    timeout=90,  # seconds to wait for device approval
)

Staying Authenticated

Once you've approved the device, pyhood handles the rest:

# Reuses cached session — no approval needed
session = pyhood.login(username="you@email.com", password="your_password")

# Or refresh explicitly — no credentials needed at all
session = pyhood.refresh()

Sessions last several days (observed 5-8 days). When the access token expires, pyhood automatically refreshes it using the stored refresh token — no device approval, no credentials, no human interaction. This is what makes pyhood safe for automated scripts and cron jobs.

Device approval is only needed again if the refresh token itself expires (typically much longer than the access token).

Error Handling

pyhood raises specific exceptions so you know exactly what went wrong:

from pyhood.exceptions import (
    LoginTimeoutError,            # Timed out waiting for device approval
    DeviceApprovalRequiredError,  # Approval prompt sent but not completed
    MFARequiredError,             # SMS/email code needed — pass mfa_code parameter
    TokenExpiredError,            # Refresh token expired — full re-login needed
    AuthError,                    # Generic auth failure
)

try:
    session = pyhood.login(username="...", password="...", timeout=90)
except LoginTimeoutError:
    print("Open Robinhood app and approve the device, then try again")
except MFARequiredError:
    code = input("Enter the code from SMS/email: ")
    session = pyhood.login(username="...", password="...", mfa_code=code)
except AuthError as e:
    print(f"Login failed: {e}")

⚠️ Rate Limits

Robinhood aggressively rate-limits authentication. If login fails:

  • Do NOT retry immediately — wait at least 5 minutes
  • 2-3 failed attempts will lock out your account's API access for 5-10 minutes
  • Each login attempt generates a new device approval — old approvals don't carry over
  • See the Rate Limits documentation for details

Install

pip install pyhood

Crypto Trading (Official API)

pyhood also supports Robinhood's official Crypto Trading API — no device approval needed, just API keys.

from pyhood.crypto import CryptoClient

# API key auth — generate keys at robinhood.com/account/crypto
crypto = CryptoClient(api_key="rh-api-...", private_key_base64="...")

# Market data
quotes = crypto.get_best_bid_ask("BTC-USD", "ETH-USD")
price = crypto.get_estimated_price("BTC-USD", "buy", 0.001)

# Historical OHLCV data
candles = crypto.get_historicals("BTC-USD", interval="hour", span="week")
for c in candles:
    print(f"{c.begins_at}  O:{c.open_price}  H:{c.high_price}  L:{c.low_price}  C:{c.close_price}")

# Account & holdings
account = crypto.get_account()
holdings = crypto.get_holdings(account.account_number, "BTC")

# Place an order
order = crypto.place_order(
    account_number=account.account_number,
    side="buy",
    order_type="market",
    symbol="BTC-USD",
    order_config={"asset_quantity": "0.001"},
)

Generate your API keys at robinhood.com/account/crypto. See the Crypto documentation for full details.

Futures Trading

pyhood supports Robinhood's futures API — contracts, quotes, orders, and P&L tracking.

client = PyhoodClient(session)

# Contract details
contract = client.get_futures_contract("ESH26")
print(f"{contract.name} — multiplier: {contract.multiplier}")

# Real-time quote
quote = client.get_futures_quote("ESH26")
print(f"Last: {quote.last_price}  Bid: {quote.bid}  Ask: {quote.ask}")

# P&L across all closed futures trades
pnl = client.calculate_futures_pnl()
print(f"Realized P&L: ${pnl:.2f}")

See the Futures documentation for full details.

Banking & Dividends

# Check linked bank accounts
accounts = client.get_bank_accounts()

# View transfer history
transfers = client.get_transfers()

# Initiate a deposit
transfer = client.initiate_transfer(
    amount=500.00,
    direction="deposit",
    ach_relationship_url=accounts[0].url,
)

# Debit card transactions (Cash Management)
txns = client.get_card_transactions()
pending = client.get_card_transactions(card_type="pending")

# Dividend history
dividends = client.get_dividends()
aapl_divs = client.get_dividends_by_symbol("AAPL")

Watchlists

# Get all watchlists
watchlists = client.get_watchlists()

# Get a specific watchlist
default = client.get_watchlist("Default")
print(default.symbols)  # ['AAPL', 'MSFT', ...]

# Add / remove symbols
client.add_to_watchlist(["NVDA", "TSLA"])
client.remove_from_watchlist(["TSLA"])

Markets & Trading Hours

# List available exchanges
markets = client.get_markets()

# Check if NYSE is open on a specific date
hours = client.get_market_hours("XNYS", "2026-03-30")
print(f"Open: {hours.is_open}, {hours.opens_at} — {hours.closes_at}")

Research & Discovery

# Analyst ratings
rating = client.get_ratings("AAPL")
print(f"Buy: {rating.num_buy}, Hold: {rating.num_hold}, Sell: {rating.num_sell}")

# News articles
articles = client.get_news("AAPL")
for a in articles:
    print(f"{a.source}: {a.title}")

# S&P 500 movers
movers = client.get_movers("up")

# Trending stocks (100 most popular on Robinhood)
popular = client.get_tags("100-most-popular")

# How many RH users hold a stock
count = client.get_popularity("AAPL")

# Stock split history
splits = client.get_splits("AAPL")

Portfolio & Option Historicals

# Portfolio value over time
history = client.get_portfolio_historicals(
    account_number="123456", interval="day", span="year",
)
for candle in history:
    print(f"{candle.begins_at}: ${candle.adjusted_close_equity:.2f}")

# Historical option pricing
candles = client.get_option_historicals("option-id-here", interval="day", span="month")

# Account documents (statements, trade confirms, tax docs)
docs = client.get_documents(doc_type="account_statement")

Development Status

  • ✅ Stocks/options market data (unofficial API) — functional (equity + index options)
  • ✅ Futures trading (contracts, quotes, orders, P&L) — functional
  • ✅ Crypto trading (official API) — functional
  • ✅ Authentication with automatic token refresh — functional
  • ✅ Full order management for stocks/options — functional
  • ✅ Banking (ACH transfers, deposits/withdrawals) — functional
  • ✅ Watchlists (create/manage) — functional
  • ✅ Dividends (query history) — functional
  • ✅ Markets/Trading Hours (exchange schedules) — functional
  • ✅ User profile & notification settings — functional
  • ✅ Research & discovery (ratings, news, movers, tags, popularity) — functional
  • ✅ Portfolio historicals & option historicals — functional
  • ✅ Documents & statements — functional
  • ✅ Day trades, margin calls, deposit schedules — functional

Acknowledgments

pyhood stands on the shoulders of the community that figured out Robinhood's unofficial API:

  • robin_stocks by Josh Fernandes — The most widely used Python library for Robinhood. Its auth flow, endpoint mapping, and API patterns laid the groundwork that pyhood builds from.
  • pyrh by Robinhood Unofficial — An early Python client that pioneered OAuth token refresh and session management patterns for the Robinhood API.
  • Robinhood by Sanko — The original unofficial API documentation that mapped out Robinhood's endpoints and made all of these libraries possible.

These projects made Robinhood accessible to developers. pyhood continues that mission with a focus on reliability and automation.

License

MIT

Metadata

Release files for pyhood 0.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyhood 0.10.0
File Size Uploaded Provenance Actions
pyhood-0.10.0.tar.gz 76.4 kB With provenance Details for pyhood-0.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyhood 0.10.0
File Interpreter ABI Platform Actions
pyhood-0.10.0-py3-none-any.whl Python 3 none any Details for pyhood-0.10.0-py3-none-any.whl

Total release size: 126.5 kB

Release files / pyhood-0.10.0.tar.gz

Download URL pyhood-0.10.0.tar.gz
Size 76.4 kB
Tags Source
SHA-256 checksum
How to use checksums
b95375dc1d059c2f58da725e99f2dccdc846cfbd463014901c73adcdf0fde345
BLAKE2b-256 checksum
How to use checksums
e178b2a641d33c1990e73466203ac48e0f03e7e8435cd1f84a08c021f1141f36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 9, 2026.

Transparency log

Release files / pyhood-0.10.0-py3-none-any.whl

Download URL pyhood-0.10.0-py3-none-any.whl
Size 50.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
628b7a444ff62f536551c3820587727ea3844072a4639ebb1e5fbebce4bf0d9c
BLAKE2b-256 checksum
How to use checksums
ba0ad2f93d31d6646ef174bce9749335af9b9f75712add6b34dfef0a0f178d57
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 9, 2026.

Transparency log

Security for pyhood 0.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pyhood-0.10.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page