Download stock data with Python and Alpaca.

Download stock data with Python and Alpaca.

This is a very basic code snippet for downloading data using the Alpaca API. You can get a free API for paper-trading through alpaca which will give you access to their IEX data. Once you get your alpaca API keys you can start using most of the code examples on TradeTechie.

The Python script will only download the data and print out the low, high, close and open prices.

Make sure to drop in your KEY and SECRET key from Alpaca!

import alpaca_trade_api as tradeapi
import pandas as pd


KEY = '#'

SECRET_KEY = '#'


api = tradeapi.REST(KEY, SECRET_KEY, base_url='https://paper-api.alpaca.markets', api_version='v2') 
account = api.get_account()
api.list_positions()


def get_barset(symbols,end_dt):
    start_dt = end_dt - pd.Timedelta('100 days')
    start = start_dt.strftime('%Y-%m-%d')
    end = end_dt.strftime('%Y-%m-%d')
    return api.get_barset(
        symbols,
        'day',
        limit = 100,
        start=start,
        end=end
    )

def main():
    now = pd.Timestamp.now(tz='US/Eastern')
    tickers = ['GUSH','AMD']
    barset = get_barset(tickers,now)
    for ticker in tickers:
        count = 0
        for bar in barset[ticker]:
            count = count + 1
            print(count,ticker, bar.l,bar.o,bar.c,bar.h)
        count = 0
  
    pass

if __name__ == '__main__':
    main()

Leave a Reply