Creating your first algorithm
Block type not supported
We are moments away from becoming algorithmic traders.
Ok, so we learnt how to install python and connect it to our choice of broker and confirm its connected. All we need to do now is create an algorithm which places trades for us.
So what actually is an algorithm?
Algorithm sounds like a really complex word but it simply means a set of step-by-step instructions to accomplish a task or solve a problem.
So, for example, we could say if the day of the week is a Friday, sell 5 shares of Apple stock. But, if it’s a Monday, buy 5 shares of Apple stock. And that would look something like this:
from ib_insync import IB, Stock
import datetime
# Create a new IB instance
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
aapl = Stock('AAPL', 'SMART', 'USD')
ib.qualifyContracts(aapl)
def buy_stock():
order = ib.marketOrder('BUY', 5) # Buy 5 shares
ib.placeOrder(aapl, order)
print("Bought 5 shares of AAPL")
def sell_stock():
order = ib.marketOrder('SELL', 5) # Sell 5 shares
ib.placeOrder(aapl, order)
print("Sold 5 shares of AAPL")
current_day = datetime.datetime.now().weekday()
# 0 is Monday, 4 is Friday
if current_day == 0:
buy_stock()
elif current_day == 4:
sell_stock()
ib.disconnect()
Boom! You are officially an algorithmic trader! Well, kinda..
Even though this is technically algorithmic trading, we know that the chances of this actually working are minimal. This is due to the efficient market hypothesis, which states that where markets are so efficient, if this algorithm worked, then so many people would implement it that they would push up the stock too high on the buy days, and push the stock down too much on the sell days, making it unprofitable.
With that being said, this does start us off with a good foundation. We are taking in some external data (the date), we then transform that data to the format we want (from Strings to integers), we added some logic to say if the data is 0 do this, else do that, we have some minor risk management in the form of a fixed buy and sell size, and finally we have the actual trading execution.
In the next blog will look at a slightly more realistic trading algorithm, be sure to subscribe here for that one!
Skip straight to s ummary
Connect to your broker
Define a method to buy and a method to sell a stock
Transform your data to work with it, in this case transforming dates to integers
Create an if else method to buy or sell based on the data you’ve just transformed
Execute trades based on those steps and you have an algorithm