Coding Your Way to Wall Street
By: Marco Santos
Tags: Trading, Algorithms, Coding, Python, Stock Market

The Trading Algorithm

Let’s start by importing the libraries we will need:

A major difference with Quantopian’s IDE is how some functions are run. You are still able to call functions like normal but others need to be scheduled to run at specific times during the market.

Initialize Function

The Initialize function

Here we have the initialize() function. Within this function we will be using the algo.schedule_function() to schedule three functions:

trading()

exiting_trades()

record_vars()

The other arguments:

algo.date_rules.every_day()

algo.time_rules.market_close()

specify when the functions will run. The reason these functions are scheduled for these times is to fix any potential leverage issues. Leverage plays an important role in our algorithm which will be explained later on.

Trading Function

So now that we have an initialize() function that will run our algorithm, we can move on to the trading() function which will automatically trade the stocks we want.

But first we must explain how we are retrieving the stocks we want. In Quantopian, stocks are assigned unique id values. To access the stocks, we call upon the sid() function, type in the stock ticker, and a drop down menu will appear. See below to see which id number is assigned to TSLA.

TSLA and its sid #

For our trading function, we will be making a list of stocks that we would like to pick from. Those stocks are: TSLA, DIS, AAPL, and SPY. Each with their own sid #. There are ways to grab more stocks and filter out selected ones but that requires another function.

With our list of stocks, we will iterate through them with a ‘for’ loop. The steps taken in the ‘for’ loop are:

Fetching each stock’s closing price history. Calculating their 50 day and 200 day moving averages. Creating a True/False statement to determine crossing points. Calculating leverage allowance and setting it as another True/False statement. Creating conditional statements using open_lev , and bullish_cross or bearish_cross . Once all conditions are satisfied, we place an order for a stock using order_target_percent(stock, 0.25) to fill 25% of our portfolio with that stock. (We set the percentage as negative or positive to buy or short the stock).

The Trading function

Now each step requires specific Quantopian methods and functions. So please refer to the help page once again for a detailed explanation. Next, we’ll be explaining the conceptual reasoning behind the crossing signals and open leverage.

To determine if the 50 day MA crosses the 200 day MA in a bullish fashion, we set the 50 day MA to be less than the 200 day MA, both calculated from one day before. Then, we set the current 50 day MA to be greater than the current 200 day MA. By setting this as a conditional statement, we can capture the crossing point of the moving averages.

Now regarding open leverage, its importance is taken into account because leverage determines whether we are using our own money or borrowing money. The results from borrowing money can drastically alter our trading outcomes. The formula and schedule coded before allow us to make trades without exceeding our own leverage or cash limit.

Exiting Trades Function

Now the next function, exiting_trades() , is very similar to our trading function. The only difference is checking if we have any positions open in the first place and what kind of position that is (long or short).

The exiting trade function

As you can see, there is not much of difference between exiting_trades() and trading() . This exiting trades function repeats most of the calculations and conditions from before in order to close positions whenever the moving averages crosses against us.

Next, let’s finish the code up with a record_vars() function to keep track of a few variables that we believe are necessary.

Here we will record() our leverage and how many positions we have open. We want leverage to not drastically exceed 1. Open positions should not exceed 4 because we devoted only 25% of our portfolio for each stock we trade.

Running a Backtest

Finally, set the dates and starting capital to match the one below. We won’t be running a full backtest because it is not necessary. A full backtest will provide more information about the coded strategy but, as of now, it is not needed.

Set to 7 years of backtesting with a starting amount of $10,000

Click the button Build Algorithm, which will run the code, and then you will end up with a page like so:

Results of our coded strategy

Great! We have successfully backtested our first trading algorithm. We were successful in limiting the leverage to 1 (albeit with a little leeway, which is fine) and the trading positions never exceeded 4. Feel free to alter some of the code to see if it would significantly affect the results.