Trading at Alpaca





Kerry Back and Kevin Crotty

Create alpaca account

  • After logging into Alpaca at https://alpaca.markets, you DO NOT need to enter name, address, etc. - that is only for real trading accounts.
  • By clicking Home on the left toolbar, you should get to the screen on the following slide.
  • Click on View API Keys, then Generate New Keys to see your key and your secret key. Copy and save them somewhere.

Install alpaca-py

Connect to alpaca

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

KEY = "your_key"
SECRET_KEY = "your_secret_key"

trading_client = TradingClient(KEY, SECRET_KEY, paper=True)

Check your account

account = trading_client.get_account()
account
{   'account_blocked': False,
    'account_number': 'PA326D2U1D75',
    'accrued_fees': '0',
    'buying_power': '194344.44',
    'cash': '96279.78',
    'created_at': datetime.datetime(2023, 12, 21, 14, 56, 37, 240661, tzinfo=datetime.timezone.utc),
    'crypto_status': <AccountStatus.ACTIVE: 'ACTIVE'>,
    'currency': 'USD',
    'daytrade_count': 6,
    'daytrading_buying_power': '0',
    'equity': '100005.41',
    'id': UUID('22f9a871-da4e-45c6-a8d7-e034a2f61fc1'),
    'initial_margin': '2833.19',
    'last_equity': '100000',
    'last_maintenance_margin': '0',
    'long_market_value': '4696',
    'maintenance_margin': '1699.91',
    'multiplier': '2',
    'non_marginable_buying_power': '95172.21',
    'pattern_day_trader': False,
    'pending_transfer_in': '0',
    'pending_transfer_out': None,
    'portfolio_value': '100005.41',
    'regt_buying_power': '194344.44',
    'short_market_value': '-970.38',
    'shorting_enabled': True,
    'sma': '0',
    'status': <AccountStatus.ACTIVE: 'ACTIVE'>,
    'trade_suspended_by_user': False,
    'trading_blocked': False,
    'transfers_blocked': False}

Check buying power and account balance

print(f'Available buying power:\t${float(account.buying_power):,.2f}')
print(f'Portfolio value:\t\t${float(account.portfolio_value):,.2f}')
Available buying power: $194,344.44
Portfolio value:        $100,005.41

Asset Information

asset_info = trading_client.get_asset('SPY')
asset_info
{   'asset_class': <AssetClass.US_EQUITY: 'us_equity'>,
    'easy_to_borrow': True,
    'exchange': <AssetExchange.ARCA: 'ARCA'>,
    'fractionable': True,
    'id': UUID('b28f4066-5c6d-479b-a2af-85dc1a8f16fb'),
    'maintenance_margin_requirement': 30.0,
    'marginable': True,
    'min_order_size': None,
    'min_trade_increment': None,
    'name': 'SPDR S&P 500 ETF Trust',
    'price_increment': None,
    'shortable': True,
    'status': <AssetStatus.ACTIVE: 'active'>,
    'symbol': 'SPY',
    'tradable': True}

Current Quotes

from alpaca.data import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
data_client = StockHistoricalDataClient(KEY, SECRET_KEY)
params = StockLatestQuoteRequest(symbol_or_symbols=['SPY'])
quotes = data_client.get_stock_latest_quote(params)
quotes
{'SPY': {   'ask_exchange': 'V',
     'ask_price': 469.6,
     'ask_size': 1.0,
     'bid_exchange': 'V',
     'bid_price': 469.55,
     'bid_size': 2.0,
     'conditions': ['R'],
     'symbol': 'SPY',
     'tape': 'B',
     'timestamp': datetime.datetime(2023, 12, 21, 17, 27, 45, 137877, tzinfo=datetime.timezone.utc)}}

Buy SPY

order = MarketOrderRequest(
    symbol="SPY",
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
    )
_ = trading_client.submit_order(order)

Short AAPL

order = MarketOrderRequest(
    symbol="AAPL",
    qty=5,
    side=OrderSide.SELL,
    time_in_force=TimeInForce.DAY
    )
_ = trading_client.submit_order(order)

Check your positions

positions = trading_client.get_all_positions()
for p in positions:
    print("{} shares of {}".format(p.qty, p.symbol))
-5 shares of AAPL
10 shares of SPY
account = trading_client.get_account()
print(f'Cash Balance: ${float(account.cash):,.2f}')
Cash Balance: $96,279.78