Automate Any Logic | Create Your Own Rules for Trading

Shyam BV
Investor’s Handbook
6 min readJun 20, 2021

--

Introduction

This article focuses on how to automate the logic/conditions. It can be interpreted in different ways. I have written this article in the lens of trading.

Everyone wants to buy at a low price and sell at a high price in the stock market according to some conditions. And to do that, you need to waste a ton of time by watching the prices. Limit orders are not so flexible and block your money. In this article, I will discuss how to create your own 100+ rules for trading. This article is for the folks who have less time or more conditions in the market. As usual, I am going to split it for two folks.

  1. Non-technical — Read section 5.
  2. Technical coders/developers — Read all sections.
Photo by Sai Kiran Anagani on Unsplash

Problems with a limit order

Have you ever thought like this “if I had known that TSLA came down to $500, I would have bought it! But I was busy with other work.”

I often think about it. Most of us are not day traders and will not have time to look at stock prices hourly or daily. You might argue, that is where limit order helps. Below are the problems with a limit order.

  1. Limit order blocks your money. If you have placed a limit order, the money involved in that order is blocked for other trades.
  2. Limit often orders too basic. It does not involve percentages.
  3. Orders cannot be tagged with other stocks or indexes. For example: If NASDAQ < 2%, then buy TSLA. These cannot be done.
  4. I cannot use any technical indicators in my condition. For example: if MA50(TSLA) < 600 then buy 2 stocks.
  5. Condition expires after 90 days—no time frame before that.
  6. You have to go back and cancel the order if you wanted to change the condition.
  7. And the list goes on...

Solution

I thought about this scenario and came up with my way to create conditions. Solution is a bit technical, and all the coding is done in python if you want to make changes. However, you don't need to be technical to use it, and you can add new conditions and modify existing ones in no time. Below are steps

  1. Create a CSV or excel for all the conditions you wanted. Like the above screenshot.
  2. Parse the logic conditions
  3. Perform buy and sell using your brokerage API
  4. Create a schedule so it can run at frequent intervals.

Let us go one by one in detail.

1. Create a CSV or excel file

We might have 100+ conditions on different stocks. We can list every conditions in a file. The logic is a pseudo-code so that any low-level person can create this type of logic. You can either mention in percentage or on price.

We can also modify the code to read conditions like this If NASDAQ < 2%, then buy TSLA. However, I wanted to keep it simple and focus on simple if-else conditions.

2. Parse the logic conditions

Now, these logic conditions are just strings. Converting to helpful information is where the intelligence comes into the picture.

We will use the below package to parse it out.

pip install pyparsing

2.1 Quick intro about pyparsing

Pyparsing is an excellent package to parse the strings. Traditionally, regex or string parsing is used. A pyparsing module is an alternative approach to creating and executing simple grammar. The pyparsing module provides a library of classes that client code uses to construct the grammar directly in Python code.

Pyparsing checks the input string and looks for keywords such as if, then, and else. Then it will try to parse the string, and it will spit out like below.

Code for parsing initial ticker and overall string

Now we need to parse the remaining strings. The below code will parse the complete string.

The final output will be a parsed string which will be something like this.

Final parsing on the string

3. Repeat for all the conditions

Now we can loop through the CSV file and parse all the logic strings which we have created.

#Read the CSV file and the conditions inside functionconditions_df = pd.read_csv('conditions.csv')
The final output from parsing

4. Trading logic

We have parsed all the conditions, and now we need to evaluate the conditions to trade on it. Here, I will link another article that is linked. It will focus on the overall architecture.

You need two pieces of information for trading the logic which we have mentioned. When checking a condition, you need to get the price and percentage change. We will use finviz package to get the price and % change of the ticker that we parsed.

To evaluate a condition, we need to use the eval function, converting the string into python code and evaluating the code to provide us the result.

condition_price_str = "1 if "+ticker_price+' '+parsed_condition[2]+' '+parsed_condition[3]+" else 0"

The above code will evaluate the string and will provide us the result.

The above code will check the category of the condition and check the indicator of the condition. Then the code will buy the number of stocks or fractional shares mentioned. A similar process is followed for the sell signal as well.

Above will be the final results of our code. If the condition is true, it will buy the specified amount of stocks which is mentioned.

5. Use it daily

Anyone with technical or no technical skills can use this type of method. For non-technical users, get the complete code and run the below code. You needed a python setup. You also needed the CSV file with conditions.

python parsing_conditions.py

We can use the code daily by scheduling the complete code using airflow or in an AWS lambda function. In that way, you are free from day-to-day execution. Check out the below article regarding airflow.

We can have these conditions on a google spreadsheet so we can modify on any device. All you need to is update the google sheets and validate the conditions.

Final Thoughts

Amazing! We have implemented a code to trade on our conditions.

  1. We have converted a pseudo-code to buy and sell on the stocks.
  2. Extend the parsing logic according to our needs. The sky is the limit here.
  3. Any limit orders trading does not block you.
  4. We can also check for account balances and then trade accordingly.
  5. Buying, selling, shorting can be performed as part of the API with conditions.

References:

  1. https://towardsdatascience.com/seven-underutilized-data-science-packages-python-2021-81b2d85bcaef
  2. https://medium.com/code-sprout/automatic-trading-python-portfolio-buy-sell-stocks-using-ai-and-rules-fa6182646f3d

Portfolio Bytes Email

For the folks who want final results — Please subscribe here to get an email daily about the latest Reddit stock tickers and much more.

Get Code

For technical users and doers — Please subscribe to my newsletter to get the complete working code for my articles and other updates.

--

--