Algorithmic trading simplified

Munesh Lakhey
7 min readJul 1, 2020

--

In this post, I will build and evaluate a trading plan which is the key step in any trading strategy, particularly algorithmic trading. Further, having a sound trading strategy can improve the risk/return profile and avoid heavy losses.

Algorithmic trading is about generating trading signals based upon some preconceived ideas which are then rigorously tested on available past data. Trading plans are often executed automatically by computers, but manual execution is also an option.

Key steps in building and defining a strategy are:

  1. Data processing — removing duplicates, sorting by date, filling NaN values, and checking and reconciling errors.
  2. Computing key metrics -returns, wealth, draw-downs for each date.
  3. Comparing means, standard deviation, and Sharpe ratio of returns for active trading with simply buy and hold scenario. Similarly, cumulative return and maximum draw-downs are key factors in decision making.
  4. Finally, visualize the cumulative return and draw-downs to highlight the performance of each.

Part 1-Company data and return characteristics

For this post, I will be using data from ‘Nabil Bank’ a high-cap, commercial bank, traded in Nepal Share Market (NEPSE). Readers can use any data they see desirable to try the same or different strategies.

A. Load and checking the data

The above code will load the data in data-frame as seen here.

Right away we can see a few issues, % Change seem wrong and there are a lot of duplicates (see the code). These issues need to be fixed.

In this exercise, we will be working with Close price or LTP(Last traded price). Hence we’ll plot LTP to begin with.

Close price shows frequent sharp falls, however, NEPSE restricts daily price changes to 10%.

B. Removing duplicates, computing returns and adjusting for splits

Next, we will use simple functions to remove duplicates, compute returns, and to adjust for splits. We will also calculate cumulative return (wealth), the peak of wealth, draw-downs from daily returns. We will use these additional metrics to evaluate the performance of the trading strategy later.

Close price shows many steep drops indicating a sharp collapse of the stock price. We will find the range of percentage changes to explore this issue. NEPSE limits the daily trading range to +/- 10%. Price change below this range is due to adjustment after distribution of bonus and right share (stock splits) and not due to actual trading.

Data-frame after recalculating returns.

Data after recalculating % change and log-return on LTP. There are 8counts of LTP drops < 10% on single day.

Eight days in total % Changes are beyond the allowed range of 10% as suspected from the plot. We will ignore those days, and from the rest of the days, we can reconstruct split-adjusted price (cumulative return x first days price). On this adjusted data we will calculate cumulative return series, the peak of return on any given day, and drop-down from peaks for day/days that yield negative returns. These metrics are used to compare with active trading strategies.

Code for removing duplicates, calculating returns, adjusting for splits and computing additional metrics.

Finally, we have data in the desired form along with different useful metrics.

C. Assessing stock performance from data

Next, we will plot prices, and returns to understand them better. Though un-adjusted prices look flat after almost a decade, the adjusted price shows investment grows four times during the period.

While un-adjusted price seem to yield no positive return, price adjusted for return seem to grows about 4 times.

Mean, standard deviation, and Sharpe ratio of log-returns are 0.00058, 0.02, 0.0283. Mean is positive and close to 0, the standard deviation is approximately 2%. Hence about 2/3 of the daily returns vary from -2% to 2%.

Mean of logReturn is positive but close to 0 , standard deviation is about 2% or about 2/3 of the time returns stay withing range of -2%, to +2% (assuming logReturns are normally distributed). There are periods of high volatility where std can be as high as 6%.

Next, we will further explore the return distribution and see if it is approximately normally distributed as we will be often using properties of normal distribution while interpreting return characteristics. We can plot the histogram together with a normal curve having the same means and standard distribution.

Visualizing return distribution and comparing it with the normal distribution.

Return look symmetric and peaked. Noticeable difference from normal curve frequency of extreme returns, both high positive and high negative returns are much more common than predicted by normal distribution. (i.e. return is fat tailed)

We can employ the Jarque-Bera test for cheeking whether any sample is normally distributed. Test values (p_val for normality =0.0, skewness = 0.437, kurtosis = 9.40) suggest curve is not exactly normal, it’s positively skewed and peaked.

Part 2-Rolling mean based trading

Trading strategies.

Trading in contrast to buy and hold strategy assumes that outcomes of holding are less desirable/predictable. And in trading, explicit signals makes it much easier to book profit and limit losses. With good strategies, it might be possible to buy stocks at some opportune time, hold it till there is a clear signal to sell. The objective is to get better returns and avoid big losses leading to favorable reward to risk ratio (Sharpe ratio).

Strategies could be any idea/pattern (it can be simple or can combine the number of observations). We need to test those ideas on available past data (also called back-testing). Those with the best Sharpe ratio and low draw-downs can be then tried in real markets.

Crossover

Cross over strategies either use price cross overs with some moving average or it employs two moving averages to signal the change in trend. In the example below, we will use 2 rolling averages spanning 20 and 60 days. As short term or 20-day rolling average crosses from below, it signals a bullish trend and vice versa. Hence buying and selling are timed according to these crossover patterns.

We can plot trend-lines to illustrate price trends and spot opportunities to make profits as the curves each other.

As short mean climbs up and crosses over, it signals a bullish trend and vice versa. Buy right after short mean crosses from below and selling right after short mean crosses from above could be a profitable strategy.

We need to mark the days when the crossing over takes place and use 1 to indicate curves are crossing each other. On occasion when short mean crosses from below we will mark these spots as buy signals and when the opposite happens (short mean crosses from above) we shall mark the particular day as a sell signal. We will use a series of data-frames and transformations to build and evaluate this idea.

The first step is to generate buy and sell signals. As shown below when short mean crosses from below it generate a buy-signal and vice versa.

Using buy and sell signals stocks are bought and sold on corresponding days at adjusted price and returns calculated using price differences (or ratios).

Part 3 -Evaluation and decision making

At this point risk (std of return), return ( mean of return), Sharpe ratio (mead/std), draw-downs (drop from recent peak wealth) are calculated for both strategies for head to head comparison. For a fair comparison, we will use the same window of the time period for both strategies and recalculate returns and wealth for buy and hold strategies keeping with dates in the trading strategy.

Code for computing means, standard deviation, wealth draw-downs and comparing them.

We can see the results below. Trading outperforms buy and hold strategy in all metrics. In about 8 years buy and hold strategy grows the investment by about 4 times and cross-over strategy grows investment by approximately 5 times.

Cumulative return (wealth) of buy and hold and active trading.

A maximum draw-down is much more favorable for active trading. While the maximum loss of value from any peak is 42% for buy and hold investing, rolling mean base trading loses a maximum of 11% value at the worst. Often sell signal is generated early during the bearish moves, active trading avoids huge fall in value. Hence during any event of distress selling our loss is limited.

Worst possible fall in value at any time from recent peak for both strategies.

To compare returns in the same scale annualized mean, and the standard deviation is used. Annual return for buy and hold is about 18% and for trading 21.5%, similarly, standard deviations are 30.7% and 25.3%. Even after adjusting for the trading cost (1% per trade, 1.5 trades/year, implied trading cost 1.5% per year) return with active trading is superior. As both return and risk profile is better for trading Sharpe ratio is much favorable for trading (0.849 for trading vs 0.581 for passive investing). Frequency wins (positive returns) and losses are again better for active trading (2 vs 0.92).

Comparing reward (mean of return), risks (standard deviation), wealth (cumulative return) and maximum draw-downs. For fair comparison, use yearly metrics (Yr -indicates yearly values).

Caveats and conclusion

Though back-testing of trading strategy shows robust results favoring trading. There are few caveats in trading. For example, it may not always be possible to get in and get out in price/time as stipulated by the trading model. A trading model may not fully capture the full range of return distribution and the model may fail to make correct predictions in the future.

In summary, we cleaned the data, recomputed returns, defined the trading signals, and calculated all relevant metrics for both strategies. The trading plan outperforms passive investing. The best part of trading is we can enjoy superior returns and avoid significant losses at any period.

Explore more topics on AI and Finance: https://medium.com/@mnshonco

--

--

Munesh Lakhey

AI Freelancer, Interested in AI for Finance & Health Care