Creating your first algorithm

Published : Feb 5, 2024

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:

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