Algo Trading Part 1: How to get stock data with Python.

Algo Trading Part 1: How to get stock data with Python.

Welcome to Part 1 of my Algo Trading series where we will write a stock trading bot in Python.

Algo Trading as been made to sound like some kind of complicated technique for making money on the stock market. This could be the case when it comes to the high frequency traders of wall-street but when it comes to us software engineers and programming nerds, it simply means automating the buying and selling of stocks in a program

In this tutorial you will learn how to get stock data from the Alpaca API. Alpaca is a stock brokerage much like Robinhood and Webull except Alpaca provides a programming API to allow use to write our own trading programs.

To start off with, lets learn how to get data from Alpaca.

Click here to watch the video!


How to get stock market data with Python

In order to use this code you will need to create an account on Alpaca and obtain your API keys. Don’t worry you won’t need to deposit in money to use their AlgoTrading sandbox.

Look for the “Generate” or “Regenerate” button from the Home screen when you log into Aplaca.

Here is the code for getting stock market data with Python and the Alpaca API.

from alpaca.data import StockHistoricalDataClient
from alpaca.data.timeframe import TimeFrame
from alpaca.data.requests import StockBarsRequest
import datetime


ENDPOINT = 'https://paper-api.alpaca.markets'
KEY = ''
SECRET = ''
paper=True


client = StockHistoricalDataClient(api_key=KEY, secret_key=SECRET)

request_params = StockBarsRequest(
                        symbol_or_symbols="QQQ",
                        timeframe=TimeFrame.Day,
                        start=datetime.datetime(2024,4,1)
                 )

bars = client.get_stock_bars(request_params)

timestamp = [row[1] for row in bars.df.index]

close = bars.df['close']

volume = bars.df['volume']

for now in range(0,len(bars.df.index)):
    #Calculate the difference from the 
    #previous days price
    close_diff = close.iloc[now] - close.iloc[now - 1]


    # Print the timestamp, the closing proce and the
    # difference
    print(timestamp[now],close.iloc[now],close_diff)
    

About the author

Jim Burnett is a senior software engineer specializing in C++ and Python application development on Linux and Unix like operating systems.