Curtis White – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Wed, 27 Jul 2022 16:39:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg Curtis White – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 Multiplex For Greater Profit https://easylanguagemastery.com/building-strategies/multiplex-for-greater-profit/?utm_source=rss&utm_medium=rss&utm_campaign=multiplex-for-greater-profit https://easylanguagemastery.com/building-strategies/multiplex-for-greater-profit/#comments Tue, 19 Oct 2021 10:00:00 +0000 http://systemtradersuccess.com/?p=11883

Two problems that often result from system optimization are: 

(1) a reduction in the number of trades, a system that generates too few trades can both be more difficult to trade and a low number of trades does not inspire confidence; and...

(2) there is a selectivity or specialization risk that, by sheer bad luck, the specific chosen parameter values will under perform in the future even while the basic system continues to work across most other parameters.

It is thought that hedge funds often run classes of similar systems to avoid the risk of simply choosing a set of unlucky parameters but individual futures traders may not have the capital to deploy a class of similar systems for essentially a single trading concept.

We present the concept of signal multiplexing as a method to increase the number of trades which offers the possibility of greater confidence and profits– while also providing the added bonus of reducing the specialization risk of trading a single parameter set. To demonstrate the concept, we build a RSI swing trading system for the ES but instead of optimizing for a single specific optimum: we optimize across three signals any of which can get us into or out of a trade. We chain the signals using conditional “OR statements”.

inputs:
RsiLength1(1),
RsiLength2(2),
RsiLength3(3),
RsiBuyThreshold1(30),
RsiBuyThreshold2(30),
RsiBuyThreshold3(30),
RsiSellThreshold1(70),
RsiSellThreshold2(70),
RsiSellThreshold3(70);

Value1 = Rsi(Close,RsiLength1);
Value2 = Rsi(Close,RsiLength2);
Value3 = Rsi(Close,RsiLength3);

If value1 cross under RsiBuyThreshold1 or value2 cross under RsiBuyThreshold2 or value3 cross under RsiBuyThreshold3 Then buy next bar at market;

If value1 cross over RsiSellThreshold1 or value2 cross over RsiSellThreshold2 or value3 cross over RsiSellThreshold3 Then sell next bar at market;

For comparison purposes, we compare the RSI 2 using standard settings against our computer optimized RSI Multiplex system.

RSI 2

RSI 2 Multiplex

Total Net Profit

$89,600

$133,925

Winning %

72%

69%

Profit Factor

1.59

1.93

#Trades

393

515

Average Trade Profit

$227

$260

Largest Winning

$4,512

$6,375

Largest Losing

$7,425

$6,612

RSI-2 Standard - Click For Larger Image

RSI-2 Multiplex - Click For Larger Image

We generate significantly greater total net profit, greater profit factor, more trades, increased the largest winning trade, reduced the largest losing trade, and smoothed the equity curve. 

Out-of-Sample Results

We held out the last 30% of data out-of-sample, and we can compare how the systems did during the out-of-sample period.

RSI-2 Standard - Click For Larger Image

RSI-2 Multiplex - Click For Larger Image

Our multiplexed system did significantly better during the out-of-sample period.

As a final sanity check, we also optimized a single entry and exit and the net profits were only $98,475 while the profit factor was 1.58: our Multiplexed system outperformed.

While in this case, the results from signal multiplexing were superior in every way, it is worth pointing out that even if the results weren’t the best, a multiplexed system could still do better in reality because of the benefits of diversification. In this case, we optimized across three entries and exits which were chosen somewhat arbitrarily but one could certainly optimize across even more signals.

One last check is due to being a long biased system, it is possible that simply being long more could have enhanced the results but even when looking at the short only results: we've seen greater short profits confirming the potential value for multiplexing signals.

Note: Because we used genetic optimization, your results may differ slightly from ours.

--by Curtis White from Beyond Backtesting

]]>
https://easylanguagemastery.com/building-strategies/multiplex-for-greater-profit/feed/ 13
Discover Best Trading Rules with Perceptron Search https://easylanguagemastery.com/building-strategies/perceptron-search/?utm_source=rss&utm_medium=rss&utm_campaign=perceptron-search https://easylanguagemastery.com/building-strategies/perceptron-search/#comments Mon, 21 Jun 2021 10:00:01 +0000 http://systemtradersuccess.com/?p=12100

Every system developer has a list of rules and indicators that they want to test out. The problem every developer faces is narrowing down that list of rules and indicators to the select few that are best worth focusing on. A quite similar and related problem that every developer has to deal with is having some inputs or indicators that they believe to be relevant and important but not knowing exactly in what way they are significant. I will show you how you can quickly find the best rules and indicators to focus on using an automated search approach which will work on most traditional retail trading platforms (such as Tradestation, Multicharts, Ninjatrader, Amibroker, etc.). But first I should point out that there are two basic approaches to developing systems.

The manual method also known as the hypothesis and test method (guess and check), quite similar to the scientific method, and the generative method also often thought of as the “data mining” approach. It seems that most professionals use the scientific method because the generative method lacks sufficient control over the process. The problem with the traditional method is that it can be really slow and self-limiting.

Computers today are tremendously powerful and fast, and yet the system developer using the traditional approach derives very little benefit from all that increased computing power and resources. Clearly, a developer who can’t utilize the advances in technology will be at a significant handicap.

Fortunately, it is not an either-or scenario because the optimizers found in retail trading platforms can be used for not just optimizing inputs but also for discovering the best trading inputs and rules to use. The key idea is to use the optimizer to find the most relevant rules or indicators. One of the first ideas that I had was to chain conditions together using operators such as “or” and “and”. This can be achieved by creating an array of rules with associated bit states which the optimizer can turn on and off.

Tradestation has the limitation that it can’t optimize Boolean fields. The solution is to simply convert everything to “0” and “1” numeric. Create a list of rules and allow the optimizer to turn them on or off.

Inputs:
BuyCondition0(0),
BuyCondition1(0),
BuyCondition2(0);

Arrays:
BuyConditions[5](0);
BuyConditions[0] = IFF(Close > Close[1],1,0);
BuyConditions[1] = IFF(High > High[1],1,0);
BuyConditions[2] = ....More rules and conditions follow

if BuyConditions[0] = BuyCondition0 or
   BuyConditions[1] = BuyCondition1 or

A rule must both be turned on and have its corresponding input set to true for it to trigger. This allows the optimizer to turn rules on and off. Each associated “buy condition” is optimized (0 to 1, step 1). The method works and is quite powerful in itself. But the problem is you might start to think maybe we should link the rules together using an AND statement instead. OR means any rule can be own whereas AND requires all the rules to be true.

Also, maybe some conditions should signal to the system not to take a trade; that they have negative input. The number of inputs multiplies and the method quickly become unworkable. Clearly, while this method is powerful, it has too many limitations. The solution is to change the Boolean “on/off” conditions to weights, as shown below:

BuyConditions[5](0);
BuyConditions[0] = IFF(Close > Close[1],1,0) * w0;
BuyConditions[1] = IFF(High > High[1],1,0) * w1;
BuyConditions[2] = ....More rules and conditions follow

if ( BuyConditions[0] +
     BuyConditions[1] + 
   ) > thresholdBuy

We sum the weights and a buy is only triggered when the combined weights are greater than our threshold value. This is known as a perceptron. The perceptron is the precursor to the much more advanced neural network (a question for mathematical folks, what’s the difference between this and a linear function approximator?).

For simple searches, you optimize the weights with values 0 or 1. However, you can create partial weighted functions where multiple inputs can contribute to the output by optimizing from 0 to 1 in fractional increments. By changing the step size, you can define the minimum contribution that each input needs to have for the perceptron to “fire”. For example, if your threshold is 1 and your minimum step is .5 then any indicator would need to contribute at least 50% to have an impact or else would be forced into the off state.

An additional reason why this model is more powerful is that you can optimize from -1 to 1 which enables indicators to have a negative or inhibitory effect. Perceptron search can quickly reveal which rules and indicators are most likely to be relevant and worthy of additional exploration. As for techniques for additional development, converting the trading signals into normalized continuous output functions could eliminate the need to even define the initial rules.

 — by Curtis White from blog Beyond Backtesting

]]>
https://easylanguagemastery.com/building-strategies/perceptron-search/feed/ 4
Simulation: Beyond Backtesting https://easylanguagemastery.com/building-strategies/simulation-beyond-backtesting/?utm_source=rss&utm_medium=rss&utm_campaign=simulation-beyond-backtesting https://easylanguagemastery.com/building-strategies/simulation-beyond-backtesting/#respond Mon, 12 Oct 2020 10:00:15 +0000 http://systemtradersuccess.com/?p=12628

One problem with traditional backtesting is that it relies on the presupposition that there are repeating predictive patterns in the market. In fact, most trading methodologies rely on this assumption. And yet we know the disclaimer that past performance is not indicative of future results.

And yet backtesting largely assumes that the future will be similar to the past. Yet, we can imagine the possibility for non-repeating but predictable profit opportunities. Even without getting into those possibilities, we can imagine that if we can model the dynamics of the market accurately, we can predict new outcomes that cannot be extrapolated from the past.

The way this is accomplished is by simulation. Simulation offers the powerful promise of allowing us to make use of historical market data under varying conditions of future similarity. Simulation, massive simulation is also poised to impact every aspect of our lives.

Imagine for a moment that you are a world class MMA fighter or boxer, and you’re competing against a similar top-ranked fighter. What should your strategy be? In the past, you might have studied your opponent and intuited a strategy. Perhaps, if you were more sophisticated you might have even used crude statistics such as counting to figure out the risk and probability of a given working move. But today, it is surely possible to feed your moves into a computer with precise timing and force calculations. Next, it is possible to infer the same regarding your opponent by using previous fight videos. In addition, by using the fighter's height, weight, and other statistics it is possible to model how well he could perform, including moves that were not recorded. Once all the data is put into the computer then you can run thousands or hundreds of thousands of fight simulations. The best performing simulations will yield the best strategies. The strategies that are discovered may be non-intuitive and completely innovative. These can be used with human cognition and consideration as the basis for your game plan.

Now, imagine how this would work for a trader. It is not just running thousands of simulations on past data. But you must infer how future traders will react to changing market conditions. This is the difficult part because you need to know how the combination of variables will impact their behavior.

Even if that level of simulation is beyond the average developer's capability or can only provide rough approximations due to the difficulty in modeling, it is still possible to start thinking more along the lines of simulation to explore creative opportunity and risk management.

Some ideas on how you might do this:

  • Use random and partially randomized entries, and exits to try to find more universal or robust settings for your strategies.
  • Create synthetic market data where you change the amount of volatility, trend, and mean reversion to see how it might impact your strategies.
  • Create models of how traders might act in certain scenarios and look for situations that might offer predictive advantage.
  • Use Monte Carlo analysis with randomized entries to come up with pessimistic capital requirements.
  • Try to find optimal strategies for given market conditions.
  • Build self-learning strategies with limited capacity for memory and try to find the optimal rules for trading.

–by Curtis White from blog, Beyondbacktesting

]]>
https://easylanguagemastery.com/building-strategies/simulation-beyond-backtesting/feed/ 0
3 Techniques to Avoid Consecutive Losing Trades https://easylanguagemastery.com/building-strategies/3-techniques-to-avoid-consecutive-losing-trades/?utm_source=rss&utm_medium=rss&utm_campaign=3-techniques-to-avoid-consecutive-losing-trades https://easylanguagemastery.com/building-strategies/3-techniques-to-avoid-consecutive-losing-trades/#respond Mon, 02 Mar 2020 11:00:00 +0000 http://easylanguagemastery.com/?p=21629

In my experience trading futures, I have found that most damaging losses are caused by taking consecutive losing trades, i.e. runs of losing trades or correlated loses. In this post, I share 2 simple methods and 1 advanced method to avoid consecutive losses which can be applied to your trading systems and discretionary trading.

The first method is based on time, and the concept is simple– you require a minimum time (min bars after loss) after a losing trade or trades before a new trade can be placed. The logic is that if you have a method that is normally consistent and you wait long enough after a loss that whatever was driving the market when you took the loss or your psychology has more likely played out.

The second technique is that after you have a losing trade or trades on either long or short side then you only allow your system (or yourself) to take trades that are opposite to the previous loss.

The third technique is based on a previous work of mine where I explained a method to score your winning and losing trades to learn from them. In that process, you need to acquire data on some statistically relevant number of trades. However, this new technique does not require training because it is only concerned with your most recent loss. In this approach, you need to develop a market similarity score and you record that statistic at the entry of a losing trade. Next, you wait for the similarity score to either change meaningfully before your next trade (must change by a statistically relevant or minimum amount to reset it) or to change meaningfully from your last losing trade.

While any of these technique in isolation could be used to improve your system performance, it makes sense to think about situations where they could be combined. Notice, I refer to loss or losses– the reason is that if your system normally shows a higher probability to win after a losing trade then you may want to reserve these techniques for only situations after you have 2 or more losses.

-- By Curtis White from blog beyondbacktesting

]]>
https://easylanguagemastery.com/building-strategies/3-techniques-to-avoid-consecutive-losing-trades/feed/ 0
Reasonable capital required for day trading futures? https://easylanguagemastery.com/trading-live/reasonable-capital-required-for-day-trading-futures/?utm_source=rss&utm_medium=rss&utm_campaign=reasonable-capital-required-for-day-trading-futures https://easylanguagemastery.com/trading-live/reasonable-capital-required-for-day-trading-futures/#respond Mon, 10 Feb 2020 11:00:00 +0000 http://easylanguagemastery.com/?p=21492

A good rule of thumb is that a reasonable risk per day for a day trader is from 2% to 5%. A moderate level of risk is around 3% of your capital. The new CME e-micros makes it possible to get started with trivial amounts of risk (from $500 to $1,000 or even less). However, the e-micros are only a small part of the futures landscape.

For day traders, the energy complex can provide good volatility– that would be products like CL (Crude Oil), HO (Heating Oil), and Natural Gas (NG). They can compliment the equity day trading e-minis like the ES (S&P 500), NQ (Nasdaq 100), and the RTY (Russel 2000).

Now, most traders know that the CME sets the margin requirements and many brokers offer very low day trading margins as low as $500 per contract. However, here I am concerned with calculating up the reasonable minimum account size for day trading to maximize the probability of success– not the absolute minimum.

I have found that for e-mini day trading that trying to trade with less than $600 risk per day can be restrictive and makes it more difficult. If we take $600 at 3% account risk then that yields $20,000 as your minimum reasonable starting capital. Of course, it can be difficult to utilize a given risk without exceeding it. As such, we might want a risk limit that is above what we anticipate and to provide for changing market conditions. Given that, a 1k daily loss limit at 3% yields $33,000 while a $1,200 risk limit at 3% would yield an account size of $40,000.

What about a more quantitative method that can also look at the individual contracts? In the method below, I calculated the notional value for the most popular day trading contracts. Next, I took the required capital to trade each contract at no more than 4x leverage. A leverage of 3x to 4x is often considered sufficient to enable meaningful returns while still allowing for adversity. However, that method does not take into account the volatility differences among contracts. As such, I developed a volatility adjusted method which is computed by taking a smoothed moving average of the Average True Range (200 SMA of the 14 ATR) and converting that into a real dollar amount (multiply by tick value), and finally calculating the capital that would be required to keep that at no more then 5% of our account. The logic is basically if we want to capture large intraday moves then it is a given that there is some associated level of precision which also, due to the fixed multiplier in futures, defines the type of capital we should be trading with.

While calculated independently, the results from the 4x leverage rule-of-thumb and the 5% ATR are mostly in agreement, and more or less support my original guesstimates.

Contract

National Value

4x Leverage Capital

5% Smoothed ATR

ES

$158,600

$39,650

$34,000

NQ

$170,420

$42,605

$46,800

RTY

$82,000

$20,500

$24,000

YM

$140,825

$35,206

$30,700

CL

$59,610

$14,903

$32,200

NG

$22,960

$5,740

$16,400

GC

$74,050

$18,513

$17,600

Avg

$101,209

$25,302

$28,814

In summary, the often recommended 25k capital requirement for day traders seems reasonable. In lieu of strong evidence to the contrary, the day trader who wants to maximize their probability of success while risking the minimum should start with somewhere in between 25k and 40k of risk capital.

--By Curtis White from blog Beyondbacktesting

]]>
https://easylanguagemastery.com/trading-live/reasonable-capital-required-for-day-trading-futures/feed/ 0
Better RSI Entries https://easylanguagemastery.com/indicators/better-rsi-entries/?utm_source=rss&utm_medium=rss&utm_campaign=better-rsi-entries https://easylanguagemastery.com/indicators/better-rsi-entries/#respond Mon, 13 Jan 2020 11:00:00 +0000 http://easylanguagemastery.com/?p=21375

Mean reversion systems, such as those based on RSI, suffer significant performance degradation when stop losses are applied for risk control. In previous posts, I shared how one could create more powerful RSI systems by using adaptive periodicity and multi-state regime classifiers.

The key idea for better RSI entries is that there may be a unique optimal RSI threshold for any given bar size. As to why this might be relevant, it might be capturing some component of the speed of the move, or the type of results might depend on the volatility regime.

We do not need to be concerned with the exact influence the bar size might have. For example, we might reason that a large fast move might be a better buy. On the other hand, it might also be that a large move implies greater risk of future big moves, and that we should be even more selective. The good news is that we do not need to know the precise way that the adjustment should be made. We merely need to know that there is an influence and the optimizer will do the rest.

For this sample long only S&P 500 E-mini system, I classify each trigger bar into 1 of 4 classes based on the bar’s range. For each class, I optimize a specific threshold adjustment factor which will be added to the threshold level (cross under 30) that is used for buys. The adjustment can be positive or negative. For the exit, I use standard overbought level (cross over 70) and 5 bar time-based exit.

First, we examine how the long only base RSI(14) system does. While the trade quality surprised me, the poor sample size and low overall profits were not impressive.

RSI(14) Cross Under 30/Over 70, 5 Bar Exit

The results get worse once we add a 15 point stop loss. There is still promise in the in-sample results. The recent bearish regime is likely having a large impact on the OOS. Also, there are too few trades.

RSI(14) Cross Under 30/Over 70, 5 Bar Exit, 15 Point Stop

Next, I optimize the RSI(14) with a single optimal buy threshold. The results are not very good. But, is there a hint of promise?

RSI(14) Cross Under Optimized / Over 70, 5 Bar Time Exit

While there is really no need too, I apply the stop loss to the above optimized system. The profit factor for the in-sample portion improved but the out-of-sample results are still not even profitable. However, the recent market regime changes would tend to make for poor out-of-sample results for most of these types of systems.

RSI(14) Cross Under Optimized / Over 70, 5 Bar Time Exit, 15 Point Stop

With baselines established, we test how bar range threshold classifier performs. We optimize the buy threshold based on the trigger bar. There are significant improvements in the total net profit and consistent out-of-sample results. The higher number of trades appears to have helped over the recent bearish regime, at least thus far.

RSI(14) Cross Under Class(Optimal)/Over 70, 5 Bar Time Exit

With better RSI entries, the system maintains profitability and similar net profit even with a 15-point stop loss applied. It starts to look like something that might be worth trading with an average winning trade of twice the average losing trade. This win ratio is still a concern which can likely be improved with better exits. In addition, this system might be a worthy of consideration for trading with options spreads.

RSI(14) Cross Under Class(Optimal)/Over 70, 5 Bar Exit, 15 Point Stop

Addendum, after reviewing the results, I went back to look at why the max losses were so large and that is the result of a happy coding accident of the stop not being applied on the first bar. All other examples have the stop applied in the same way. With the stop applied to the first bar, the results are not quite as good. The net profit is around $10,000 less but the largest loss is reduced by about half.

Enjoyed this article? Would you like the opportunity to both support this site, and receive the open source Easylanguage for this system and a bundle of other similar systems? If so please send me an email which will help me gauge the interest level and can be used to inform you when it becomes available. The cost for the strategy bundle would be reasonable, from $150 up to perhaps $600, depending on what systems are packaged.

-- By Curtis White from beyondbacktesting

]]>
https://easylanguagemastery.com/indicators/better-rsi-entries/feed/ 0
A Visual Quantitative Analysis of RSI using Tradestation and Excel https://easylanguagemastery.com/building-strategies/a-visual-quantitative-analysis-of-rsi-using-tradestation-and-excel/?utm_source=rss&utm_medium=rss&utm_campaign=a-visual-quantitative-analysis-of-rsi-using-tradestation-and-excel https://easylanguagemastery.com/building-strategies/a-visual-quantitative-analysis-of-rsi-using-tradestation-and-excel/#comments Mon, 21 Oct 2019 10:00:33 +0000 http://systemtradersuccess.com/?p=11078

The traditional way to treat the RSI is to treat low RSI levels as good buying opportunities while treating high RSI levels as selling opportunities. However, we seek to gain fresh insight into the nature of RSI, with an eye toward discovering possible momentum return, by exploring the RSI using a visual quantitative approach.

Exporting And Visualizing The Data

We are interested in the next day returns of the RSI(2) for the E-mini S&P 500 (ES) futures contract. We will be using Tradestation and Excel for this analysis. For computing next day returns, we export the RSI(2) level and the close to close returns. We can export CSV data from Tradestation using the toolbox. However, I often find it convenient to print the data directly to the output window using Easylanguage, and then simply copy and paste it into Excel.

variables:
firstBar(1);
value1 = Rsi(Close,2)[1];
value2 = Close-Close[1];
if firstBar = 1 then begin
print("Date", ",", "RSI 2",",", "Close Close Change");
firstbar = 0;
end;
print(datetojulian(date), ",", value1,",", value2);

Now with the data properly in Excel, a scatter plot can be generated.

The Y-Axis shows the next day returns for the given RSI value, as represented by the X-axis. We can see that when RSI values are low that the market tends to be more volatile but beyond that it is difficult to read much more from this chart thus I introduce the concept of the cumulative return scatter plot.

A cumulative return scatter plot shows the total return for given RSI ranges. We can generate a cumulative return scatter plot by breaking the RSI down into a series of distinct classes or buckets and performing a rolling sum for those buckets. This can be performed in Excel. But, due to the number of rows,  I found it more productive to generate a strategy optimization report and export that into Excel.

//RSI Class Generator
inputs:
RsiLevel(20);
variables:
RsiEntryLevel(0);
If Rsi(Close,2) >= RsiLevel-20 and Rsi(Close,2) < RsiLevel then 
buy this bar at close; 
If marketposition > 0 then
sell this bar at close;

Optimizing the RsiLevel from 20 to 100 in steps of 20 will yield the report we need to create the cumulative return scatter plot.

This chart reveals that the ES has primarily been a mean reverting market over a couple days. Momentum or trending returns might only manifest over longer holding period, however. With a slight modification to the previous code, we can test the RSI returns over various holding periods.

inputs:
RsiLevel(20), DaysHold(0);
variables:
RsiEntryLevel(0);

If Rsi(Close,2) >= RsiLevel-20 and Rsi(Close,2) < RsiLevel then 
buy this bar at close; 
If marketposition > 0 and barssinceentry > dayshold then 
sell this bar at close;

We optimize both inputs to generate a new strategy report which can be used for visualizing the RSI returns over a range of holding periods. We look at returns from selling the next day up to 5 days out (where days refers to the value for our DaysHold variable– the actual number of days will be 6 or 7 depending on whether you want to count the overnight as the first day). Exporting to Excel, we can generate various heatmap displays.

The first heatmap shows the returns sorted by RSI class and number of days held. The second heatmap is sorted by net profit. The heatmaps reveal that buying weakness, at least as measured by RSI(2), even when holding up to 5 days out tends to be better than buying strength. However, it is also clear that some profits are being generated from modestly to moderately overbought conditions.

For maximal clarity, we can create a 3d bubble chart which will allows us to extend our cumulative returns scatter plot concept with the 3rd dimension.  The custom 3d bubble chart below provides exceptional clarity into both how various holding periods affect specific RSI classes and how returns from different classes compare to one another on a relative basis. The size and color of the bubbles convey the magnitude of the gain or loss for each class while the X-axis shows the class with the Y-axis represents the holding period.

Summary

Our custom 3d bubble chart reveals quite a bit. First, it reveals that RSI levels under 20 are the most optimal. Yet, even when trading the RSI in a mean reversion nature, additional profits may be gained by trading more aggressively. Specifically, it looks like RSI class 40 (values 20-40) shows strong returns when holding for up to 1-5 days out with 2 days appearing to be the optimal. The additional profits, however, won’t be cumulative because some trades will result in the RSI dipping even lower after entry. 

As for momentum returns, we do see that there does appear to be, an albeit weaker, momentum driven return for RSI values from 60 to 80 when holding from 1 to 3 days out. On the other hand, extremely overbought conditions exhibit a strong reversionary nature. The returns from buying such extremely overbought conditions are very negative even when allowing for holding periods of up to 5 days out.

Note all reference to days references the value of the variable, you would add 1 or 2 to get the actual number of days out depending on whether you want to count the overnight as the first day or not. Tradestation counts the entry bar as the first day. Adding code to sell at the open would enable seeing the overnight returns.

–by Curtis White from blog beyondbacktesting

]]>
https://easylanguagemastery.com/building-strategies/a-visual-quantitative-analysis-of-rsi-using-tradestation-and-excel/feed/ 2
Finding The Optimal Period https://easylanguagemastery.com/building-strategies/finding-optimal-period/?utm_source=rss&utm_medium=rss&utm_campaign=finding-optimal-period https://easylanguagemastery.com/building-strategies/finding-optimal-period/#comments Mon, 05 Aug 2019 10:00:30 +0000 http://systemtradersuccess.com/?p=11465

Today’s topic is on finding the optimal periodicity for the RSI indicator and the techniques should apply to other sorts of indicators as well. The good news is that it won’t require any rocket science. John Ehlers has written a lot about this topic, and his articles spurred my interest in it, which frankly I had never considered. I might should note now that I have not reviewed the actual methodology that Ehlers used in any depth but my impression was that the methods were very advanced. However, I realized I could tackle this problem using just basic statistics.

Before we start analyzing specific solutions, I want to take a moment to describe what we are actually attempting to do. The question that we are trying to answer is how do we find the optimal length to use when calculating an indicator. A poor length value may result in the RSI spending too much time in either the overbought or oversold states, or failing to reach the proper levels.

Obviously, the optimal lookback will change as market conditions change and therefore our methods should be adaptive and responsive to the market. The goal is to find a metric to rank how well behaved the RSI is. A well behaved RSI is one that spends about an equal amount of time in overbought and oversold levels. During a trending market, if the RSI gets stuck into overbought conditions then that would be an example of a poorly behaved RSI. The solution thus is simply to measure the amount of time that the RSI spends in overbought and oversold conditions.

My original inspiration came from the idea of a histogram. We simply add 1 for every bar that the RSI is above our threshold and subtract 1 for every bar that the RSI is below our threshold. The absolute value of the resulting summation is our error metric, which we seek to minimize. Key Concept: Sum the amount of time that the RSI spends above 50 and below 50, and take the difference. The absolute value of the difference is our error metric, which we seek to minimize.

Next, we will simply compute our error metric for every RSI length in our search space, and select the RSI with the minimum error. In this example, I searched from RSI(2) to RSI(14). There is one more consideration which is determining our lookback. Too short of a lookback will lack statistical relevance while too long of a lookback will defeat the benefits of adaptation. Some manual trial and error were used before I settled on a lookback of 90 days.

Test We conducted the test using the S&P 500 Emini and have selected the long only RSI(2) with standard 30/70 overbought/sold thresholds as our baseline. The results are below:

RSI(2) Simple vs RSI(2..14) 50/50

@ES Daily 1/1/2004 - 1/29/2017

RSI(2) Simple

RSI (2..14) 50/50

Net Profit

$86,075.00

$82,812.50

Max DD:

$16,937.50

$17,887.50

Profit Factor:

1.84

1.98

Avg Profit Per Trade

$304.15

$363.21

Number  of Trades

283

228

Win %

74.91

75

While the results are not too different, we do see our profit factor and average profit per trade has improved. The net profit is slightly reduced and the drawdown is slightly higher but essentially similar.

Tightening The Threshold We can get better results by making our threshold more restrictive. Instead of using the median line, we can use the amount of time that our indicator spends in actual overbought and oversold levels. This makes some sense as the overbought/sold conditions are what’s really important. We use the same technique but now we try to balance the amount of time we spend below 30 and above 70. We see significantly better results. The results improve even more when we try to balance the extreme overbought/oversold conditions using 20/80 as our thresholds: notice that we do not change our actual buy/sell conditions.

RSI(2..14) 30/70 vs RSI(2..14) 20/80


@ES Daily 1/1/2004 - 1/29/2017

RSI (2..14) 30/70

RSI (2..14) 20/80

Net Profit

$73,387.00

$83,375.00

Max DD:

$16,937.50

$16,937.50

Profit Factor:

2.53

2.54

Avg Profit Per Trade

$824.59

$850.77

Number  of Trades

89

98

Win %

74.16

77.55

Final Analysis & Summary Both the 30/70 and 20/80 optimization thresholds show significant improvement in the profit per trade over the baseline, fewer trades, and higher profit factor. This suggests that our RSI optimizations are improving trade quality significantly and suggests that our indicators are better synchronized to the more dominant cyclical structure of the market.

While the net profits are not quite as strong, the strong increase in average profit per trade is especially appealing. It appears that we can find significant cyclical structure in the markets using simple statistical techniques. However, we did have to use some trial and error in determining the lookback to calculate our statistics over, and that may be one area for improvement.

––Curtis White from Beyond Back Testing

]]>
https://easylanguagemastery.com/building-strategies/finding-optimal-period/feed/ 5
A Better Regime Filter To Boost Returns https://easylanguagemastery.com/building-strategies/multi-state-classifiers/?utm_source=rss&utm_medium=rss&utm_campaign=multi-state-classifiers https://easylanguagemastery.com/building-strategies/multi-state-classifiers/#comments Mon, 03 Jun 2019 10:00:15 +0000 http://systemtradersuccess.com/?p=10218

One technique for optimizing systems is to create a regime filter. A most common example is a binary classifier that classifies the market into either bull or bear markets based on closing above or below the 200 day moving average. But, there are problems with binary classifiers and we will demonstrate why a multi-state classifier is often a more powerful approach. In fact, the multi-state classifier combined with optimizer is actually a basic but powerful form of machine learning.

There are some obvious problems with binary classification. First, assuming that the market only has 2 regimes is somewhat an arbitrary decision. Second, it is a rather crude tool. For example, we might find it reasonable to classify various variables into multiple classes such as bearish, bullish, and neutral. The multi-state classifier is a powerful technique that allows for such classifications and more. In the moving averaging example, we might take the difference between the close and the moving average and let that specify our trading style. This allows our system to trade adaptively to the current market conditions. And the possibilities are really extensive for application.

One benefit of multi-state classifiers over a linear regression approach is that it is easy to encode non-linear logic. For example, imagine the hypothetical scenario where we want to trade conservatively when the market is very bearish, aggressive when bearish, aggressive when bullish, and conservatively again when the market is very bullish. The idea in this case is that very bullish or bearish markets are higher risk. This is an example of a nonlinear matrix.

Market Conditions

Trading Selectivity

Very Bullish

Conservative

Bullish

Agressive

Bearish

Agressive

Very Bearish

Conservative

In other words, we’re trying to find a predictor that can positively influence or inform our trading decisions. We can create as many classes or states as we desire, i.e. we can have multiple optimal values for our indicator. However, one word of caution, if we create too many classes then we run the risk of overfitting. We can guard against the possibility of overfitting in a few ways. We can limit the number of classes that we create, and we can enforce a minimum number of trades per class; like we would with an individual system. Finally, we can use “force logic” such that the optimizer is not able to optimize each class individually but rather is only able to optimize some delta. We don’t consider such advanced possibilities any further in this example.

The Example

For this example, we will look at a long only version of Connor’s RSI(2) system applied against the ES futures contract, and will seek to classify the optimal buy and sell thresholds based on the longer term RSI. We observe that the intermediate RSI tends to stay in the overbought or oversold during extended periods of strength or weakness. We want to make it easier to buy and sell during strong periods, and we want to make it more difficult to buy and sell during weak periods. In other words, we want to become more selective when the market is persistently weak which makes sense because the risk is higher.

In this example, we’ll use an RSI(14) for our longer term RSI. We observe the RSI(14) tends to stay between 15 to 70.

However, to be sure that we capture the lower and upper extents then we’ll define our classes as: -infinity to 30, 30 to 50, and 50 to infinity. If the intermediate RSI is in the lower region then that indicates a more bearish market that should dictate more trade selectivity; on the other hand if the market is strong then we need to be more aggressive to capture the dips. We could use the optimizer to find the optimal values for these classes. However, in this example, we simply force the logic we desire and optimize by hand.

The All-Important Code

Before we get to the results, it might be illustrative to see the most pertinent EasyLanguage code. We can actually make the class assignment code rather short and elegant as long as we pay attention to the ordering of the statements:

BuyThresholdV = 30;
BuyThresholdV = IFF( RsiClassifier >= -10, 10, BuyThresholdV);
BuyThresholdV = IFF( RsiClassifier >= 30, 20, BuyThresholdV);
BuyThresholdV = IFF( RsiClassifier >= 50, 30, BuyThresholdV);

SellThresholdV = 70;
SellThresholdV = IFF( RsiClassifier >= -10, 60, SellThresholdV);
SellThresholdV = IFF( RsiClassifier >= 30, 70, SellThresholdV);
SellThresholdV = IFF( RsiClassifier >= 50, 80, SellThresholdV);
BuyCondition = RsiSignal < BuyThresholdV; SellCondition = RsiSignal > SellThresholdV;

Finally, we compare the simple RSI(2) strategy to our hand optimized multi-state classifier.

RSI(2) Simple vs RSI(2) Multi-State

RSI(2) Simple

RSI(2) Multi-State

Net Profit

$86,075.00

$95,487.50

Max DD:

($16,937.50)

($16,937.50)

Profit Factor:

1.84

2.02

Avg Profit Per Trade:

$304.15

$404.61

Number of Trades:

283

236

Win Percentage:

74.91

74.58

Simple

Multi-State

Summary

We introduced the concept of multi-state (or multi-class) classification by using the RSI(2) strategy as an example. We quantitatively improved the results of the RSI(2) system using only hand optimization and forced logic. Our multi-state classifier improved the net-profit and significantly improved the average profit per trade. The winning percentage was basically unchanged.

Unfortunately, we were not able to significantly reduce the drawdown with this method. This suggest that our profits may be deriving more from trading more aggressively in bull markets than avoiding the losses in bear markets. However, the fact our total trades is lower and our profits higher suggest the quality of trades overall we took were higher. That would suggest on average we did better but both systems took a single or a few big hits sometime over the entire history.

One suggestion as to why this may be the case is that the RSI itself tends to make large movements on a bar-by-bar basis which limits the degree to which we can use its value to inform our decision. Fortunately, one is not limited to using RSI, and there are many more types of market conditions that one can classify that may yield even better performance.

–by Curtis White from blog Beyond Backtesting

]]>
https://easylanguagemastery.com/building-strategies/multi-state-classifiers/feed/ 9