Trading Bots & Marxism
Python can extend the power of your brain exponentially through mass data analysis, but getting started with coding can be just as chaotic as entering any community within normal life. There are different versions of the language, different modules to achieve the same thing, different habits for testing and debugging code, different software programs you can use as a coding interface, etc. In everyday culture, there are rituals that give structure to the chaotic environment that we live in. We say “Hi” to our neighbours, we go to school to get a diploma, we comb our hair in the morning. These activities can be considered rituals that give structure to the interaction with our social environment. The activities have a positive effect by facilitating confidence and a sense of belonging among those who practice the ritual. However, they can also be very painful. Men who have undergone a traditional circumcision during manhood, have a high complication rate and, of course, pain. How senseless as this might seem to an outsider, the symbolic meaning of belonging to a group and achieving in-group status dominates the fear and pain of these individuals during the painful act. In this post, I will propose a similar ritualistic process for your coding career. Don’t worry, the one I suggest will not harm your precious sensitive overcivilized flesh, but it will involve a big friendly green snake that will hurt your bank account if you mishandle it…
Using Python to build a trading bot entails writing code that uses historical financial data to create useful predictions about future stock prices. If you want to achieve an effective algorithmic trading application you have to bring many different skills to the table: 1) create your strategy, 2) understand the necessary tools, 3) store and retrieve data in a reliable way, 4) tweak the subunits of a complex system and 5) know how to debug if something goes wrong. These are all necessary skills that you will use in the future if you continue with coding.
Emotionally, the testing of your trading strategy (also called backtrading or paper trading) is not such a big deal, but real trading is different. There are time delays of your order with price changes in the between time, there are orders that are deleted because a time limit has exceeded, there are sudden value changes due to news reports. Coding a trading bot will probably have a similar mental effect as losing some foreskin. You get scared to lose money and worried about the possible consequences it will have on your real financial situation.
Unfortunately, I can’t promise you that this won’t happen when you start with making a trading bot. But you have to be courageous. If you complete the project correctly and you’ve made a live trading bot, you have officially made one of your coding projects a very extremely almost non-existent tiny, but real part of the economy… We can say to ourselves and others at the end of the journey that we can make something useful with our code...
To make it easier for you to get started, here is an adjusted workflow from the book Machine Trading by Ernest Chan. You don’t per se have to use a graphical user interface, but it does make it easy to turn switches on and off or adjust variables during the fine-tuning process.
How much time does it cost to complete the project?
The time for coding of the trading bot itself is of course dependent on your level. Here is a raw estimate based on my one year experience of coding:
- Basic level: variables, loops, functions, loops — 4 weeks full time.
- Intermediate level: object-oriented programming, inheritance, decorators — 2–4 weekends.
- Advanced level: professional coder — a couple of hours (?).
Which Broker Server should I use?
There are many servers you can use in the U.S. to trade with Python, but if you are living outside the united state, there are fewer options (Robinhood, Alpaca for instance don’t allow non-US residents). I live in the Netherlands so it took me a long time to find a broker with a suitable API. Here is a list of websites where you can open a brokers account from outside the U.S. I found none in that list that allows you to communicate with a python API. I am using one that is not in the list called DeGiro which has its own python API along with clear documentation on the basic commands you’ll be using 99% of the time in the bot. I'm happy with it, their Python API is very easy to work with so I recommend using that one if you live outside the U.S.
Which feedback mechanism should I use?
If you want to get feedback out of your trading bot you have two options for running your code 24x7:
- Use a cloud service like Google cloud platform, Amazon Webservices or Heroku.
- Let an old laptop run 24x7 to do the trading.
You can send yourself a feedback signal through:
- Sending yourself an e-mail or SMS notification (with e.g. Twillio) for every specific number of transaction or for a specific time interval or something like that.
- Visualize the data with Matlplotlib, Seaborn, Plotly, Dash or another package on a cloud server so you’ll be able to check the performance of your bot from anywhere with your phone.
The cloud service of the Heroku platform is the easiest one to use. If you choose that one I would recommend carefully following this tutorial from Charming Data to prevent yourself from making mistakes in the setup. Don’t forget to adjust the WEB-CONCURRENCY option to 1 as described in this post so you won’t have your buy and sell orders being performed in double.
Dash is probably the easiest way to make a graphical user interface. It's rising in popularity and the documentation is very good. This is a medium post on how to get started with Dash, but you can also find a lot of good tutorials on YouTube. The advantage of using Dash is that it doesn’t take that much effort to create a graph that gives you updates every x minutes/hours/days with the live update callback. This tutorial and this StackOverflow post show you how to implement this live update into your application. Don’t forget to adjust the callback function as described in my GitHub repository if you use this tutorial! If you want to know more about running a scheduler in the background that coordinates the trading frequency then you can read more about that in this post.
How much money and stock to experiment with?
Depending on your daredevil level you can use whatever parameters you want in this equation so this is a difficult one to advise you in. You need to think of at least the following parameters:
- The frequency of trading attempts of your bot.
- The maximum number of stocks you will buy per specific time interval (e.g. 10 stocks/24 hours).
- The maximum number of stocks you want to have in your possession.
- The maximum price for a stock. Keep in mind that the lower the maximum price your willing to pay for a stock, the longer you will have to keep it to achieve a break-even price if the stock price is rising. Or if you choose for a low maximum price you will have to buy a higher number of stocks.
- The minimum price of a stock to make a profit in regard to the transaction costs (between 1–3 euros) of your online trading account provider.
- The maximum number of days you want to keep on trying to buy a stock after you have placed the order.
How to store your data within the workflow?
You can use JSON files, pickle files, csv files, SQL databases, or other options to store your data. They all have their advantages and drawbacks. This is an informative post on StackOverflow.
Should I use machine learning?
There are some very cool machine learning tutorials online:
- Computer science LSTM (long-short term memory) machine learning stock prediction
However, this video gives convincing reasons that the contributory value to price prediction is limited. It gives the answer to the question of whether ML can really help in trading. In short:
- Finding patterns in the past with machine learning doesn’t say anything about future prices.
- If you train your machine learning algorithm to more data or more different data sources it will be prone to overfitting (seeing patterns that are not there).
- If you do decide to try it, having fun while learning new things should be your main objective.
While analyzing patterns with machine learning seems to be not beneficial, at least not to the individual trader, there have been many publications that shed light on the predictive power of sentiment analysis. The most convincing one I came across was the one by Bollen et al. published in 2011. The graph beneath comes from this open-source article. In red, you see the calm sentiment analysis score during the election of President Obama and thanksgiving. In blue, you see the average positivity in opinion.
When you correlate the calm sentiment with stock prices 3 days later you get the graph beneath. The calm score is shown in red at the bottom. The stock price of the American Dow Jones is shown in blue in the middle. The graph at the top shows the areas of congruency between stock price and sentiment accentuated in grey.
Sentiment analysis might be a viable way of predicting the stock market at that time, but I can’t tell you if it still is and whether it is applicable to the stock and sentiment in your country and language.
In my path of becoming code literate, I was reluctant to get into algorithmic trading. I had been mostly confronted with the dark sides of capitalism, so I wasn’t interested. That was until I began to see the results of what I could do with Python in some small projects. After these small successes, I needed more challenging and bigger projects, but also a more serious project, a project I could use to get more experience in coding solutions for real-life problems. I reconsidered a trading bot as a good option, but the question ran through my mind: what about all the destructive effects of capitalism I see around me? A year ago I got interested in Marxism. I discovered his genius analysis of the negative effects of capitalism on socio-economics and how his understanding could explain the awkward situation we’re in today. In his theory, technology was the capitalist's way to increase the production of the worker. Capitalists would first try other things like increasing the number of working hours, decreasing the time of lunch breaks, decreasing wages relative to inflation to increase the production of workers (the so-called surplus or “Mehrwert” in German), etc. These are changes in the work process that all create an excess of production that the capitalist can then use in his quest to create more wealth and some of these changes might sound very familiar to you. If there were new technological inventions the capitalist would let them be deployed to let the worker create even more surplus. The capitalist would quietly push the benefits of technology towards an increase in the production of his/her workers. New technology was just another mean for the capitalist to increase production without having the worker see any of the gains in wealth. As Marx wrote, the worker would be humiliated by this transition:
“all means for the development of production transform themselves into means of domination over, and exploitation of, the producers; they mutilate the labourer into a fragment of a man, degrade him to the level of an appendage of a machine,[…] they transform his life-time into working-time, and drag his wife and child beneath the wheels of the Juggernaut of capital.”
Marx also saw the immense destructive potential of new technologies to our biological environment. He was far ahead of his time when in 1867 he described the destruction of the earth as an eminent result of the rising technological advances:
“Capitalist production develops the technique and the combination of the process of social production only by exhausting at the same time the two sources from which all wealth springs: the earth and the worker.”
However, reading Juval Harrari’s Homo Sapiens caused me to reconsider all the criticism I had on capitalism. He accepts that capitalism has a destructive side by making the gap between different social groups worse than ever by the introduction of wealth inequalities. But he also argues that there is something else about capitalism that made it the dominant economic system in the world today. It is not the goodness of capitalism that caused countries to change their economic policies but the capability of the capitalistic system to process large amounts of information in an unregulated and efficient fashion on a wide scale:
“Money is the most universal and most efficient system of mutual trust ever devised.”
After some deep contemplation for months, I had to agree. The universe is evolving towards increasingly more efficient information processing systems, and capitalism is just one step on the road as Yuval Harrari further explains in his follow up of Homo Sapiens: Homo Deus.
TRADING BOT: GOOD OR BAD?
Coming back to our trading bot we stand for a dilemma. Marx was right in that workers creating a surplus that flows to the already wealthy capitalist is a system that makes the rich richer and the poor poorer. But maybe he was wrong in appointing the place of technology in his diagram of how things work together in the economy. In his view, technology was a tool for the wealthy to achieve more power. On the other hand, today we can increasingly see how technological means made available to us for free can be used to improve our lives. We can educate ourselves as never before, get the most recent medical information to improve our health and we can send money to our relatives over the world. Maybe the positive things can overwhelm the negative, but it all depends on how we use it. The same is true for our bot. We can use it to invest in airline corporations that will get government investments to stay alive during corona, we can let our bot invest in oil companies as a way of achieving a secure income, we can invest in companies that manufacture clothes in poor countries. But we can also do it differently. We can invest in animal-suffering-free company processes such as the production of vegan products, in health-tech companies that use the latest robot technologies and artificial intelligence to help debilitated patients move their arm or legs again, or support development in the African continent by investing in a company that sells off the grid electricity through solar panels in Kenya. So next to being an initiation rite, a trading bot can influence the market in the right instead of the wrong direction. Just like with everything in life, we can do bad and good things with it. Its effect will be dependent on the intend we have when we build it.
In conclusion, creating a trading bot is a positive thing for your software engineering skills and can function as a second “hello world” ritual. I have argued that while performing algorithmic trading as a supporter of Marxism involves an emersion into the inner workings of capitalism, it could also be considered a noble activity if you build your algorithms with the right intentions. And yes, I have undergone the ritual, I have created my trading bot. It's running, but I’m primarily spanking it (debugging) in the hope it will perform better. When the returns become higher than the amount of money I painfully lost during the testing phase I will write a post about it. But it will probably take some time before I can show you how going through all the painful stumbling points can lead to something nice in the long run… If you want to stay up to date on how I try to realize this American, or maybe even better, Marxistic dream, follow me.