img

Python Stock Trading Bot

img
valuezone 21 December 2022

Python Stock Trading Bot

This article will explain how to create an automated system that trades stocks when you are away from your computer. This article is not intended to provide financial advice, but rather to educate. The first step is to discuss the trading strategy, then we will prepare the data and develop the trade execution strategy.

Trading Strategy Development

Using a slower and faster moving average, we will implement a simple cross-over strategy. Recursively taking the average of the closed price of a stock over x days is how moving averages are calculated. By taking a smaller number for x, the moving average will respond faster to the original closed price, giving the illusion that it is moving more quickly. Similarly, using a larger number for x will result in a moving average that responds more slowly to the original closed price and appear to move more slowly. This type of indicator is known as a “Golden Cross” and indicates that the price will rise when the faster moving average goes above the slower moving average. “Death Cross” occurs when the faster moving average falls below the slower moving average, indicating that the price will fall. This is an optimal time to sell, when the faster moving average falls below the slower moving average.

Testing the strategy in the past

On the trading view site, you can test the strategy. Signing up is free, and all strategies can be backtested on their free tier. As shown below, the code for the trading strategy under test is written in pine script.




Data preparation

We will now retrieve our data once our strategy has been backtested. S&P 500 will provide us with the data. Using pandas, the code below scrapes the ticker labels of the S&P 500 index from Wikipedia and formats them into a csv file.

Brokerage Selection and Interaction

Alpaca API will be used for this project to place and execute trades. You can choose from a variety of brokerages when you write your algorithm/bot, but this brokerage offers the advantage of commission-free trades (having no fees), the ability to simulate trades without using real money (paper trading), and, most importantly, it is tailored specifically for developers and their trading bots.

Developing the bot

You can find the bot’s code (main.py) below. The main method is the first to be discussed.

The code checks every hour between when the stock market opens and when it closes for each of the tickers we scrapped (see b.check_trade).

Below is a more detailed description of the check_trade method.

We will execute a trade based on the value of the variable “result”. Below is the code.