Day Trading Algorithm

Abstract

This project focuses on the application of algorithmic techniques in the field of finance. In particular, it attempts to leverage several technical indicators to specifically target day trading of inverse ETFs. Over the course of this project, a day trading algorithm was created utilizing several technical indicators and Python financial libraries. Based on these indicators, buy or sell signals were generated and then tested against market conditions to determine whether the algorithm is profitable or not. The algorithm was able to achieve positive returns in 68% of tested transactions.

Introduction

Day trading refers to the fast-paced buying and selling of financial instruments within a single trading day. The goal of day trading is to make quick profits. However, the stakes are high and the risks are significant. Inverse ETFs are investment vehicles that are designed to perform in the opposite manner to a particular index. Essentially, if the index goes down, the inverse ETF goes up, and vice versa. This project explores the application of algorithmic techniques to mitigate risks and maximize profits in this volatile environment. Instead of using machine learning, the focus here is on using a blend of technical indicators to determine the efficacy of the trading algorithm. These are essentially data-driven insights about market trends—to create an algorithm that can smartly guide trading decisions. This algorithm was put to the test and showed promise, successfully turning a profit in 68% of the trades executed.

Tools and Libraries

Influx-DB

InfluxDB is a time-series database specifically designed to handle high write and query loads. I chose InfluxDB because of its beneficial for backtesting, allowing for quick data retrieval to assess the effectiveness of trading strategies.

Pandas

This Python library excels in data manipulation and analysis, and it was especially useful in managing time-series data of stock prices and indicators. The data structures offered by Pandas were ideal for cleaning and transforming the raw financial data into a format suitable for the project.

Pandas TA

This played an essential role in seamlessly integrating technical indicators into our data analysis workflow. The library streamlined the process of adding indicators to our historical price data, allowing us to focus on fine-tuning our trading strategy.

Alpaca

This API allowed for the execution of trades in a simulated environment, offering a risk-free way to test the algorithm in real-time market conditions. It was an invaluable tool for validating the trading algorithm's effectiveness in a setting mimicking live markets.

Quantopian

This platform was employed for backtesting our trading strategy, providing a sandbox environment to simulate trades over historical data. The backtesting helped to fine-tune the algorithm parameters and validated its effectiveness.

Numpy

It provided the essential mathematical operations needed to manipulate the financial data sets and was helpful in the process of preparing data for analysis.

Technical Indicators

Technical indicators are mathematical calculations based on price, volume, or open interest of a security that assist traders in interpreting current or predicting future price trends. In a field as volatile as day trading, where positions are opened and closed within the same trading day, having a set of reliable indicators is extremely important to determine optimal points of entry and exit. A total of 40 technical indicators spanning trend, momentum, and volume were used in this project to build a robust and versatile trading algorithm. The following are a couple of the basic ones that were used in the project. These indicators were not just chosen randomly but were meticulously backtested to ensure they contribute positively to the trading algorithm. Please feel free to reach out to me to get information on other technical indicators used.

SMA (Simple Moving Average)

The SMA is essentially the average stock price over a certain number of days. It's one of the oldest and simplest indicators to use. I chose this because it provides a smoothed-out line that offers a clearer visual of the price trend over a given period. SMA makes it easier to identify the overall direction, whether it's upwards, downwards, or sideways.

EMA (Exponential Moving Average)

EMA gives more weight to the most recent prices. This is vital for day trading where recent price actions are often more relevant for making quick decisions. The main reason for including EMA was its sensitivity to price changes, making it a good tool for identifying early signals for entry or exit points.

RSI (Relative Strength Index)

RSI is an oscillator that measures the speed and change of price movements, ranging from zero to 100. Generally, an RSI above 70 suggests that a stock is overbought, and below 30 indicates it is oversold. I included RSI to gauge the momentum and identify potential reversals in price direction. It's an effective way to avoid buying or selling into a temporary price extreme.

Bollinger Bands

Bollinger Bands consist of an SMA line with two standard deviation lines, one above and one below. The bands expand and contract based on market volatility. I chose this indicator because it gives a dynamic view of price volatility while also providing a sense of direction. When prices touch the upper band, it's generally considered overbought, and when they touch the lower band, it's seen as oversold.

MACD (Moving Average Convergence Divergence)

MACD is essentially the difference between a 26-day EMA and a 12-day EMA, with a 9-day EMA of the MACD itself used as a signal line. MACD helps in spotting changes in the strength, direction, momentum, and duration of a trend. I included MACD because it offers two key signals: crossovers and divergences, which are great for confirming trend reversals and continuations.

On-balance volume (OBV)

OBV is a momentum indicator that uses volume flow to predict changes in stock price. The theory is that when volume increases sharply without a significant change in the stock's price, the price will eventually jump upward, and vice versa. I utilized OBV to confirm the strength of a trend; it's a way to add an additional layer of validation before making a trade.

Weighting Matrix

A pivotal part of this project was the weighting matrix - a matrix that assigns weights to all the technical indicators to indicate the role they play in contributing to a decision. This is important because most of the times, technical indicators do not agree with each other. It’s not uncommon to have some indicators signalling a great time to buy while others signalling a sell decision.

The weighting matrix acts like a decision-making panel where each indicator gets a vote but not all votes are equal. Some indicators are given more importance (higher weight) based on their reliability and relevance to the project’s specific trading strategy for inverse ETFs. For example, a momentum heavy trading algorithm will favor momentum based technical indicators whereas a volume one would assign higher weightage to volume indicators. The weightings are essentially numerical values assigned to each indicator, allowing them to contribute proportionally to the final trading signal.

For example, if the Simple Moving Average (SMA) has been particularly reliable in test runs, it might be weighted at 0.3, while a less consistent indicator like On-balance Volume (OBV) might get a 0.1 weighting. When generating a signal, these weights are applied to each indicator's value to produce a composite score, dictating whether to buy, sell, or hold.

Trading Algorithm

The trading algorithm was essentially the all encompassing final product of this project. The algorithm uses the weighted indicators to make its buy or sell decisions. It's a set of specific rules and is similar in nature to a flowchart. First, it takes real-time or historical price and volume data and calculates the indicators. Then, these indicators are run through the weighting matrix, producing a composite or 'final' score. Based on this score and pre-defined thresholds, the algorithm decides whether it's a good time to buy, sell, or simply do nothing. Changing the thresholds and the weightages have a big impact on how the model functions. The model was run several times on historical data to tune in the optimal weights and thresholds.

Key Outcomes and Performance Metrics

  1. Success Rate: This metric underscores the efficacy of the model in actually providing positive returns on investments. The trading algorithm was successful in 68% of the transactions.

  2. Risk-to-Reward Ratio: The Risk-to-Reward Ratio was calculated using the formula (Take Profit Level−Entry Level​) / (Entry Level−Stop Loss Level). The ratio for this algorithm was approximately 1:1.27 which means that for every dollar risked, the expected return is $1.27.

  3. Sharpe Ratio: The Sharpe Ratio is a measure that helps understand the return of an investment compared to its risk. It's calculated as (Average Return−Risk-Free Rate) / Standard Deviation of Returns. For this algorithm, the Sharpe Ratio was 1.8, indicating that the returns are reasonably good when adjusted for the risk taken.

  4. Drawdown: Drawdown measures the largest single drop from peak to bottom in the value of a portfolio. This gives an idea about the volatility and risk associated with the trading strategy. The algorithm recorded a maximum drawdown of 12% which gives an idea about the strategy’s downside risk.

Conclusion

The landscape of day trading is continuously evolving and so is this algorithm. With a focus on inverse ETFs, the project leveraged multiple technical indicators to generate buy or sell signals. While the algorithm showed promise with a 68% rate of positive transactions, it's essential to note that the performance metrics are just the tip of the iceberg. Future iterations will include the addition of more indicators and potentially refining the weighting matrix for a more reliable trading signal. Metrics like Trade Volume and False Positives will also be added to give a more complete understanding of the risks and returns involved.

For those interested in diving deeper into the thought process behind the indicator choices or the matrix implementation, feel free to reach out to me. I’d love to hear any insights or prior experiences you have in the field of day-trading.

Next
Next

Sound Recognition