Logo

dev-resources.site

for different kinds of informations.

Algorithmic Trading: algorithms to beat the market

Published at
2/2/2020
Categories
investing
trading
python
strategies
Author
anrodriguez
Author
11 person written this
anrodriguez
open
Algorithmic Trading: algorithms to beat the market

During 2019, the stock market grew. A lot.

Take for example an ETF I like: FTEC (Fidelity MSCI Information Technology Index):

During 2019, FTECā€™s price grew from $49.35 to $72.48: a staggering almost 50% growth!

Thatā€™s almost double the growth of the standard-bearer S&P500 that grew ā€œonlyā€ around 30%.

Stocks like APPL (Apple Inc.) grew even more, over 90%!

Put neatly:

S&P 500: 30%
FTEC: 50%
V: 41%
AAPL: 90%
Enter fullscreen mode Exit fullscreen mode

Some stocksā€™ return during 2019Some stocksā€™ return during 2019

Itā€™s easy to check it out using finance.yahoo.com.

Compare that with 2016, itā€™s a completely different picture.

S&P 500: 12%
FTEC: 15%
V: 3.1%
AAPL: 10%
Enter fullscreen mode Exit fullscreen mode

Same stocks, but with data during 2015Same stocks, but with data during 2015

It is evident that 2019 was a very good year for the stock market and for the ā€œbuy and hold strategyā€.

I was thinking about this today and I decided to compare the performance of my algorithm between years 2019 and 2016.

I couldnā€™t beat the market with data from 2019, but my algorithm did quite well with data from 2016 (luck? skill?).

Running the same algorithm against data from 2016, my algorithm had an edge of about 10% on average over the market.

When I saw this, I could finally understand why my trading algorithm never beat the market. Itā€™s hard to beat the 2019 performance of the stock market.

People mostly refer to ā€œthe marketā€ as the return shown by the S&P 500 index ( Standard and Poorā€™s 500 Index).

As most of you know, the S&P 500 is

a market-capitalization-weighted index of the 500 largest U.S. publicly traded companies. The index is widely regarded as the best gauge of large-cap U.S. equities.

Basically, this means that S&P500 is a good indicator of how well the stock market is doing as a whole.

Some say that to make a profit with an automated trading algorithm you would basically need to come up with a way of ā€œpredicting the marketā€.

I would say that this is partially true but at the same time somewhat misleading.

Itā€™s true that in order to make a profit you need to know when to buy and when to sell. But itā€™s misleading to call this ā€œpredicting the marketā€ as if one were an oracle, or if one pretended to read the future with a magic crystal ball.

For example, some would argue that if the price of a stock increases steadily as a straight line, the only way to make money would be to ā€œbuy and holdā€.

This is partially true.

If the price of a stock increase steadily as a straight line, there are no moments where the price can be considered low relative to the mean since the price is always increasing.

To reap the maximum profit, the best strategy would be to buy at the beginning and sell at the end (whenever you wish to enter or exit the market) and be ā€œexposedā€ to the stock the longest possible time.

Margin trading

However, another useful strategy, in this case, would be to ā€œ buy on marginā€:

Buying on margin is the act of borrowing money to buy securities. The practice includes buying an asset where the buyer pays only a percentage of the assetā€™s value and borrows the rest from the bank or broker. The broker acts as a lender and the securities in the investorā€™s account act as collateral.

Margin is basically borrowing money from your broker using your securities as collateral.

In this example, using margin could multiply your winnings simply by buying more with money you initially donā€™t have. HOWEVER, it could also multiply the losses. It can be seen as an amplifier.

If you buy stocks on margin and sell them before the market closes, then you donā€™t pay any interest on the loan (at least this is true when using Alpaca).

Alpaca offers annual fees for margin loans as low as 3.75%. However, you only have to pay this interest if you borrow overnight.

For example, if you borrow $5,000 overnight, you end up paying a $0.52 surplus over the loan.

If your stock ends up making 10%, you pay 3.75% for the loan and pocket the rest 6.25%.

As a more meaningful example, if you would have bought $100 of an S&P ETF (like VOO or SPY) you would have made $12. If you use margin to buy 4 times this amount (and kept the loan a whole year), that is, $400, you would have made a profit of:

net_profit = profit - margin_interest
           = $12x4  - $400 x 3.75% 
           = $48    - $15 
           = $33
Enter fullscreen mode Exit fullscreen mode

This is a profit of 33% instead of 12%. Almost 3x better (33%/12%).

Historically, S&P500 has made, on average, 7% a year.

Again, bear in mind that the same way your winnings can be multiplied, itā€™s equally true for your losses.

That is, if your stock loses $1, you actually lose $2 due to margin PLUS the interest (assuming 2x margin). If you are using a 4x margin and the stock drops 25% you lose it all.

Although this is not common, not long ago we all know it happened. And it might happen again. Granted it was not all during a single trading session (but it might be in the future!).

50-drop.png

I am not a financial advisor. So take this as a warning and do it at your own risk.

Mean reversion

Although there are countless strategies, many revolve against the concept of mean reversion:

Mean reversion is a theory used in finance that suggests that asset prices and historical returns eventually will revert to the long-run mean or average level of the entire dataset.

There are also many ā€˜indicatorsā€™ that promise to tell you when to buy or sell, or what the market trend is.

A very basic indicator is made by calculating the ā€œstandard deviationā€ of the random price fluctuations or volatility of the stock.

The indicator named ā€œBollinger bandsĀ®ā€ uses the standard deviation.

The standard deviation is easily calculated with, for example, Pandas:

Pandas is a fast, powerful, flexible and easy to use open-source data analysis and manipulation tool, built on top of the Python programming language.

Weā€™ll be using Pandas in future articles. Iā€™ll share some simple code to get started with algorithmic trading.

I donā€™t think any indicator or strategy is a silver bullet (ā€œNobody has cracked it. Period.ā€).

Itā€™s pretty obvious because if these strategies or indicators were magical and openly disclosed, then most algorithmic traders would already be rich or making a ton of money.

Also, if these strategies or indicators were so good, itā€™s hard to think they would be openly available on the internet.

A good trading platform

If you are looking for a very good Algorithmic Trading platform, where code is a first-class citizen, I would certainly recommend Alpaca.

They are truly a platform dedicated mostly to algorithmic trading. You can also buy/sell stocks on their online platform. They offer margin. Also, they have neat integrations, for example with TradingView.

Alpaca also offers a very nice paper trading account. The paper account trading lets you trade as if you had a live account, but with ā€œfakeā€ or ā€œpaperā€ money. You can test your algorithms posting buy/sell orders, etc. and have a peek on how your algorithm would do in a real-world scenario.

But I find more useful doing very simple custom baked ā€œbacktestingā€ scripts. Backtesting is testing your algorithm using historical data.

But remember the mantra:

Past Performance Is No Guarantee of Future Results.

A backtesting script

I recently did a basic backtesting script using Alpaca, downloading data for free from Polygon.io and coded it in Python. In fact, over time Iā€™ve done a couple. It isnā€™t hard.

My custom backtesting script basically loops over the data and simulates the decision making on when to buy or sell. It also keeps track of the transactions (buy and sell prices). In the end, I like to know how much money the algorithm would have made or lost.

Hereā€™s my next article where I share some code to download historical minute data using Alpaca and do a simple backtest for the ā€œBuy and Holdā€ strategy.

In the third part of this series, weā€™ll build on our code and work on a scalping script, that even gives good results with 2016 data.

I might also later write about some other strategies Iā€™ve tried, and provide code snippets that some might find useful. Stay tuned.

See you next time!

strategies Article's
27 articles in total
Favicon
How I Boosted My Blog Traffic Using Free SEO Strategies Even Big Companies Swear By
Favicon
Data Center Resilience with Comprehensive Disaster Recovery Strategies
Favicon
The Most Popular Database Caching Strategies Explained
Favicon
Top Ways MSPs Can Strengthen Their Data Protection Game in 2024
Favicon
Marketing Strategies
Favicon
Mastering Data Security: A Comprehensive Look at NAS Backup Strategies
Favicon
Strategic Web Development: Turning Ideas into Seamless Online Experiences
Favicon
Mastering Locator Strategies in Appium
Favicon
Top Creative Real Estate Investment Strategies
Favicon
Unlocking Free Traffic: Strategies to Boost Visitors to Your Website
Favicon
Unlocking Free Traffic: Strategies to Boost Visitors to Your Website
Favicon
8 tips to embrace API documentation with both arms instead of one
Favicon
Take your brand to the next level with our advanced digital marketing strategies!
Favicon
Fault Tolerance in Distributed Systems: Strategies and Case Studies
Favicon
Mastering Problem-Solving: A 5-Step Approach for Coding Success
Favicon
Six Tips and Strategies for Handling the mess left behind
Favicon
7 Effective Affiliate Marketing Strategies to Boost Your Online Revenue
Favicon
How do you stay motivated when there's no company bonus?
Favicon
6(Rā€™) Strategies for Cloud Migration - All IN ONE
Favicon
Construction marketing strategies
Favicon
Cost reduction techniques: Lesson for travel app development
Favicon
Not For Profit Forum With Matthew Brannelly
Favicon
Strategies for building a successful Community
Favicon
Algorithmic Trading: algorithms to beat the market
Favicon
Algo Trading: algorithms to beat the market
Favicon
When and how do you make time to learn?
Favicon
5 Strategies That Will Really Grow Your Instagram Audience

Featured ones: