Quantcast
Channel: System Trader Success
Viewing all 323 articles
Browse latest View live

Sharpe Ratio – the right answer to the wrong question?

$
0
0

Sharpe was the right answer

First, let’s start with what Sharpe does well. There are two things it does well:

  1. Cross-asset unified measure: we all know that the most important component in alpha generation is asset allocation. Now, the difficulty is to have a single measure of risk-adjusted measure of alpha. This is where Sharpe did the job. It could give a single number across many asset classes: be it fixed income, equities, commodities, etc.
  2. Uncertainty: the human brain is hard-wired to associate uncertainty with risk. It triggers the amygdala and activates the fight, flight or freeze reflex (see one of my posts about fear and greed). So, Sharpe is a good measure of uncertainty: it quantifies units of uncertainty-adjusted performance.

Now, Sharpe ratio, as part of the modern finance package, was invented the same year of the coronation of the Queen of England. It was good, almost revolutionary for its time, since Batista in Cuba was fighting El Che and Fidel. But, like the UN building designed by Brasilian Oscar Niemeyer, it did not age well, and here is why:

Sharpe is not a measure of risk, it is a measure of volatility-adjusted performance

It associated volatility with risk. Risk does not equate volatility and here are a few examples:

  1. Low vol may be extremely risky: LTCM had low vol. In fact, their strategy was to be short gamma. It worked until it did not. Fast forward to 2008, vol funds collapsed one after the other. Low vol does not equate risk.
  2. CTAs like Ed Seykota, Tom Basso, Bill Dunn, William Eckhardt, etc: they have supposedly hopelessly low Sharpe but have clocked >+25% year in year out.

Does it mean that the CTAs have risky strategies ? No, it means they have low semi-volatility-adjusted strategies. Semi-vol is just downside volatility.


The Sharpe Ratio is the right mathematical answer to the wrong question.
Click To Tweet


Risk means uncertainty, just learn to get comfortable with it

As much as I understand that uncertainty is not pleasant and may trigger some reptilian alarms in our brain, we must learn to live with it. It involves mindfulness meditation, strict formalisation of strategies, etc. Do not pray for an easy life, pray for the strength to endure a tough one.

Now, what is risk ?

Risk is not a paragraph at the end of a dissertation. Risk is a number. The only difficulty is to find the adequate formula that goes along. There are two types of strategies: mean reversion or trend following. Please read my posts on the subject.

Risk is not difficult to quantify. It is only difficult to identify. I have come up with the common sense ratio as it recaptures both mean reversion and trend following strategies.

CSR = tail ratio * gain to pain ratio

Please use the trading edge visualiser to find out your personality:

TradingEdgeVisualiser - Sharpe Ratio

Conclusion

Bottom line, we have associated risk with volatility. We have come up with a measure of volatility-adjusted performance and deem it a risk measure. CSR, on the other hand, is a unified risk measure that can be used across asset classes. It measures risk according to strategy type.

Get in touch to Download files, resources, and some materials to take the advantage.

— By Laurent Bernut of Alpha Secure Capital originally appeared at Better System Trader.

The post Sharpe Ratio – the right answer to the wrong question? appeared first on System Trader Success.


Seasonal Strategies Built The Right Way

$
0
0

Many commodities, and even some individual stocks or stock groups, have recurring fundamental factors that affect their prices. These forcescan be seen by analyzing a market by day of week, day of month, or day of year. This is called seasonal trading.

Almost everyone who did seasonal analysis back in the 1990’s made a big mistake. That is, you can’t use backtest results which include the period used to discover the seasonal patterns and expect good real-world results.

The problem with this type of seasonal study is the assumptions that needs to be made in the analysis. Say a market rises in price in the selected time frame in 21 of the 23 years from 1980 through 2002. Would a trader have known to make these seasonal trades based on the information that he or she had at the time when a trade would have been made?

For example in 1985, five years into the carefully selected period, would you know the market had appreciated during this particular time frame in just six of the 10 years from 1975 through 1984? Few traders would have taken the trade then, although in the original analysis 1985 may have been the most profitable year. Even assuming that the same trades would have been made, using a static seasonal relationship in a walk-forward simulation is a flawed approach. The proper way to study seasonality is a pure walk-forward dynamic seasonal.

It is necessary to use either all the previous years or a window of previous years to trade the current year and then to shift the window forward. It is also important to use the same rules for defining all seasonal periods and making all trading decisions across all markets.

Predictive Seasonal

One approach to seasonal analysis focuses on creating a predictive seasonal. For example, when looking at the 20th trading day of the year and trying to create a five-day price prediction, it would involve taking the difference between the 24th trading day of the year and the 20th. In this way, a seasonal based on how prices will move over the next n days is created. The key is that we only use data through the previous year to calculate the seasonal for this year and we walk it forward. Most seasonal references talk about performance during an in-sample period. This approach is not statistically valid. The only way to do a seasonal that can be used in trading is to develop a rolling window seasonal that holds up walking forward. Seasonality does evolve over time. You might ask why that would happen? Well, for example, corn, was strongly corollated with a seasonal based on the US market, but over time we had two seasonal signals overlaying each other, one from the US market and the other from Argentina, which is the other big corn producer.

Some seasonal calculation methods use raw prices and average the price for each seasonal period, for example daily, weekly or monthly. These types of seasonal calculations require individual contracts or calculations from cash prices. Using the price differences between days allows the calculation of seasonal tendencies from back-adjusted contracts.

We could use average returns for this type of predictive seasonal difference.

The problem is this type of simple classic seasonal can be distorted by a large move on one day. During the mid-1990’s, the solution came to me; use the percentage the market rises or falls to develop seasonal trades. However, you still have the problem of normalizing the seasonal so that it can be traded using the same relative numbers across all markets.

This concept became the seasonal indicator called the Ruggiero/Barna Seasonal Index that integrated both of these factors.

The Ruggiero/Barna Seasonal Index

The Ruggiero/Barna Seasonal Index was developed by myself and Michael Barna.

I would like to make one point about the RuggierolBarna Seasonal Index: It is calculated rolling forward. This means that all resulting trades are not based on hindsight. Past data are used only to calculate the sea-sonal index for tomorrow’s trading. This allows development of a more re- alistic historical backtest on a seasonal trading strategy.

The Ruggiero/Barna Seasonal Index is calculated as follows:

  • Develop your seasonal and update it as you walk forward in your data.
  • For each trading day of the year, record the next n-day returns and the percentage of time the market moved up or down.
  • Multiply this n-day return by the proper percentage.
  • Scale the numbers calculated in step 3 between -1.00 and 1.00 over the trading year. An output of 1.00 means the market will be the most bullish of the year over the next five days and an output of -1.00 is the most bearish.

The Ruggiero Barna Seasonal is so powerful it can be used as a system all by itself. Look at these results for coffee. Using an 8-year lookback to calculate a walk forward seasonal the Ruggiero/Barna Seasonal produced the following amazing results, no slippage, and commissions deducted since we wanted to look at the seasonal bias. First trade in 2002, 15 years ago.

Let’s look at the yearly breakdown for Coffee using the Ruggiero/Barna Seasonal Index.

Now let’s look at the equity curve for this system.

This approach works across many markets. Remember, this is a true walk-forward analysis!

The only way to develop seasonal-based strategies that can reliability help you trade is using walk-forward seasonality -- that is, identifying the seasonal bias using historical data only and rolling this forward to generate results. Even well-known seasonal companies make the mistake of showing results on in-sample data, and they charge a lot of money for their flawed approach.

The Ruggiero/Barna Seasonal let's you uncover seasonal patterns for any market, and has been traded for over 20 years. It has continued to hold up and produce amazing results over that time.

How To Do This In TradeStation or MultiCharts

In 1996, I released my first version of the Universal Seasonal for TradeStation. This was one of my most popular products. This product had open code but the engine of it was done in C DLL  This meant that when TradeStation changed the API, this product needed to be totally reworked. 

Now, 21 years later, I have redone this product and it  now in 100% easy language and will work in both TradeStation and Multi-charts. The key to the universal seasonal is that it uses a walk-forward methodology.

It's called Universal Seasonal.

Universal Seasonal has all you need to develop your own seasonal strategies and includes the Ruggiero/Barna seasonal index strategy, developed over 20 years ago based on walk forward analysis and still works today on a wide basket of markets. 

If you're interested in creating seasonality based trading systems, Universal Seasonal is a must-have. 

-- Murray Ruggiero

The post Seasonal Strategies Built The Right Way appeared first on System Trader Success.

The Tough Truth About Part Time Trading

$
0
0

Practically every week, I get an e-mail or two from an aspiring trader. “I want to make some extra money trading”, the story usually goes. Sometimes it is from young adults, already scrambling to get out of the rat race. Other times it is from a retired folk who suddenly realize that money is tight, and working at a fast food restaurant is a loathsome option.

For some reason, $50,000 per year after taxes seems to be the amount most frequently requested. I guess it makes sense – who wouldn’t have a more comfortable life with an extra $1,000 spending money each week in their pocket?

Most want this amount by part time trading. They have obviously seen all the trading “gurus” out there bragging about their alleged profits (spoiler alert: most gurus do not even trade, and the alleged profits are fairy dust!), and the people who e-mail me want just a little taste of that but do not want to be full time traders.

Let’s forget about the sheer audacity of the request – seriously, what kind of part time job pays someone with zero or little experience $50-75 per hour?

And let’s forget about the difficulty in making ANY money in trading – the statistics tell us more than 90% of people lose at trading – which is absolutely true.

Casting the sheer difficulty of the task aside (becoming a profitable trader is a whole book in itself!), let’s just look at the math. How can someone net $50,000 per year from part time trading?

First, how much capital would you need? Assuming a 30% tax rate, to net $50,000 per year, you’d need to make around $71,000 in a year. Not a trivial amount. If you only had a $10,000 account to start, you have to have over 700% annual return! WOW!!!

Unfortunately, it is even worse for most part time traders, who might only have $5,000 to start with. They would need over 1400% return per year, for every year they trade, since they are withdrawing all profits.

Of course, some gaudy returns are possible, but those returns are possible only with EXTREME risk – basically losing it all versus a slim chance at an extraordinary gain. I call it a “lottery ticket” approach, since it has about as much chance of occurring as winning the big prize in the lottery.

Obviously, as the amount of starting capital goes up, the annual return goes down. But even with $180,000 starting capital, you’d still need 40% annual return to meet the profit goal. Most professionals do not hit that kind of annual percentage return, and even if they do, it is hard to do multiple consecutive years.

Figure 1:  Annual Percentage Returns Required To Take Out $50K After Taxes

Figure 1:  Annual Percentage Returns Required To Take Out $50K After Taxes

So, what about an alternative: take some money out and slowly build the account? The good news is you’ll eventually be able to take out $50,000 after taxes, every year. The bad news is that even with 50% annual returns (VERY difficult), and taking out only 60% of net profits, it will take 26 years of this kind of performance to hit the $50,000 withdrawal level. In other words, not very palatable for most part timers.

Figure 2:  Year 26 is the first time this part timer can take out $50K!

Even for someone willing to forego current income to reach the $50,000 goal has it tough. Assuming 50% per year return, 30% tax rate, and reinvesting 100% of net profits (taking out 0%), it still takes 10 years before one can withdraw $50K per year without dropping the account balance.

Part Time Trading

Figure 3:  It Takes 10 Years With Reinvestment to Get to $50K Return Level

As daunting as even this scenario sounds, remember two things:

  •  This assumes 50% annual returns, each year, for 10 years! In other words, you will be in VERY rare air to reach this return level.
  • This ignores the inevitable drawdowns that will accompany such returns (assume 25-50% annual drawdowns, as a likely minimum).

Download

I have included a spreadsheet for you to tailor to your own situation. Just change the numbers highlighted in blue for your circumstances.

Conclusion:

You can definitely become a part time trader - that is not an issue. But make sure your goals and objectives are realistic before you start trading. For most people, the math simply does not work out. Unrealistic expected returns, small starting capital, and pie-in-the-sky income requirements make part time trading very difficult for most.

Remember, trading is a marathon, not a sprint. Keep your requirements for return and income small at first, and focus just on growing the account and trading well. If you do so, profits will eventually follow. 

Get in touch to Download files, resources, and some materials to take the advantage.

-- Kevin Davey of KJ Trading Systems

The post The Tough Truth About Part Time Trading appeared first on System Trader Success.

Using a Self-Similarity Metric with Intraday Data to Define Market Regimes

$
0
0

koch-snowflake-and-serpinski-triangle

The images above are the famous Sierpinski Triangle and the Koch Snowflake. These objects are “self-similar” and this means that examination at finer levels of resolution will reveal the same shape. Both are examples of “fractal” geometry, and are characteristic of many phenomena in the natural world such as mountains, crystals, and gases. Self-similar objects are associated with simplicity, redundancy and hence robustness. Self-dissimilar objects are associated with complexity and chaos. Several mathematicians (including Mandelbrot) have observed that markets are clearly non-gaussian or non-normal. Markets exhibit “fat-tails” and have a distribution that shares more in common with a Levy distribution than the normal distribution which is used frequently in quantitative finance. But the market does not have a constant distribution – at times the market behavior is fairly normal in character while at other times the market is wild and unpredictable. The question is how we can effectively determine which regime the market is in so that we can apply the appropriate trading strategies to mitigate risk.

The essence of self-similarity and complexity is to compare the whole to its component parts. For example, let’s take a square that is divided into four separate squares of equal size. The area of the larger square is equivalent to the sum of the areas of each of its component squares. The same of course is true of a one-dimensional line which is equivalent to the sum of its parts. One of the methods of identifying self-similarity in the stock market is to look at the range or the difference between the highs and the lows. We would expect that in a perfectly self-similar market the longer range would be equivalent to the sum of the ranges measured over a smaller interval. The more chaotic the market is, the greater the difference will be between these two measures. Such market conditions would be characterized by a large ratio between the sum of smaller ranges versus the longer measure of range. Essentially this relationship is called fractal dimension and is a measure of complexity. There are many different ways to measure this including using the Hurst exponent, but the problem I have always found in my own humble research is that the suggested thresholds defined by specific absolute values do not seem to reflect the information consistent with theory. I have often found that relative measures tend to be more robust and consistent – much the same way that the magnitude of past returns has less predictive value than the relative rank of past returns. Relative measures tend to be more stationary than absolute values. To compute this measure of self-similarity I use the intraday range (high minus low) versus a longer range window. Here is how it is calculated:

  1. Find the high minus the low for each day going back 10 days.
  2. Take the sum of these values (sum of the pieces).
  3. Find the 10-day range by taking the 10-day maximum (including the highs) and subtracting out the 10-day minimum (whole range).
  4. Divide the sum of the pieces by the whole range – this is a basic measure of fractal dimension/complexity.
  5. Take the 60-day average of the 10-day series of the complexity values – this is the quarterly “chaos/stability” metric.
  6. Use either the 252-day normsdist of the z-score or the percentile ranking of the chaos/stability metric.
  7. Values above .5 indicate that the market is in a “chaos” regime and is much less predictable and non-stationary, values below .5 indicate that the market is stable and much more predictable.

When the market is “stable” it is easier to apply effective quantitative trading systems. When the market is in “chaos” mode, it is not necessarily volatile but rather it is too complex to use for standard measurement and calibration of basic linear prediction. Let’s look at how this measure performs over a long time period using the S&P500 as a test set. The high and low values are generally the same until about 1963 which is when we will begin this test. Here is how the market performed in both regimes over the last 50+ years:

ssm1 (1)

ssm2

 

The market performs quite poorly in “chaos” conditions and seems to make all of its long-term returns in the “stable” regime. Note however that the volatility is not materially different between both regimes – this means that we are capturing something different than just high and low volatility market conditions. Furthermore, the correlation between the chaos indicator signals and for example the basic trend signal of a 200-day moving average is -.116. This means that we are capturing something different than just the market trend as well. The indicator is meant to be used to define regimes rather than as a trading signal to go long or short, but clearly there are some interesting attributes worthy of further exploration and refinement.

  • By David Varadi of CSSA

Update by Jeff Swanson

Here is my attempt at creating this indicator in EasyLanguage. Please let me know of any corrections. The code was last updated on April 9, 2015.

CSSA Regime (TradeStation ELD)
CSSA Regime (Text file)

The post Using a Self-Similarity Metric with Intraday Data to Define Market Regimes appeared first on System Trader Success.

Can You Short The S&P Successfully?

$
0
0

A short signal for the S&P500? Believe it or not, some do exist. Although these can often be hard to find they can also contribute greatly to your success – so tons of traders search endlessly for a complimentary short system or two for their portfolios.

I want to talk about a simple short edge that I have recently been tweeting about for the past year or so as it has been an interesting signal as of late. It is nothing more than a short signal – not a complete system! The sample size is not great, but it is still noteworthy.

Sigma Score

The raw signal itself is just a +2 sigma move based on rolling 20 day (historical) volatility. A sigma score or “z score” is simply a way to express something in terms of standard deviation units. For example, a sigma of 1.5 signifies a value that would allow us to fit 1.5 standard deviations between the mean and the current value. Note: That mean is zero in this case due to standardization.

The trading idea being that the market has moved up too much too fast and some short-term pause or price retraction could be expected.

So how do we calculate sigma score? Below is simple python code using Build Alpha’s python environment for creating custom signals. (Another example: buildalpha.com/python)

Step 1. Calculate the natural log of one bar price changes
Step 2. Calculate the rolling average of the price changes
Step 3.  Calculate the rolling standard deviation of the price changes
Step 4. Calculate the Z score or sigma score which is defined as z = (value – average) / standard deviation.
Step 5.Create python list named Signal that contains 1 for true signal or 0 for false signal.

There is also an ELD with TradeStation code attached that contains a simple function for sigma_score(lookback) that will do the same calculation.

Performance

Below you can see the equity curve from 2002 to 2018 if one were to have sold short (1 contract) all +2 sigma score days and hold exactly for one trading day (entry and exit both executed next bar open). No stop or profit target included.

It is not an excellent edge by any means, but a short signal to persist while the market has gone straight up is always worth keeping tabs on. Below you can see the e-ratio for this event. (Learn more about eratio here: buildalpha.com/eratio).

You can see it peaks at 1 bar hold but maintains almost 0.30 units of volatility over normal (1.00) so longer hold times might not be out of the question for this edge – but that will be left for further research. A better idea might be to use this daily signal as a multi-timeframe filter for some intraday short systems as the peak is clearly at x = 1.

I am a quantitative trader with a high frequency,  market-making firm but also recently started developing the Build Alpha trading software which has the ability to create, stress test, and produce tradeable code for hundreds of systematic trading strategies. All of this can be achieved with NO programming.  However, I recently added a Python development environment to allow sophisticated users a bit more flexibility. I can be reached at David@buildalpha.com or on twitter @dburgh.

Downloads

Sigma Function, Strategy and Indicator ( TradeStation ELD )
Sigma Strategy WorkSpace ( TradeStation WorkSpace )

-- Dave Bergstrom from Build Alpha

The post Can You Short The S&P Successfully? appeared first on System Trader Success.

Are you losing when you should be winning? Here’s something you might be missing

$
0
0

Most people think about where to get into and out of positions. Nearly all traders know how important it is to follow their rules, and the majority of them always work toward being more disciplined. These are important pieces of a successful investment strategy, and most traders work on these things. But there’s one thing that is usually neglected, and it can turn winners into losers. When you trade, how much do you trade? How big are your positions?

This question of how much to trade–position sizing–is critical. Trade too small, and no matter what you do, you won’t make enough money to justify your time spent trading. Trade too big, and you risk losing everything.

I am in the process of creating the next module of my free trading course, and it will focus on this question of how to size positions appropriately. I created an example, a long time ago, of a simple positive expectancy system (the system wins 50% of the time and wins are 1.2X the size of losses. More details of the system are here) and then created a simulation where many traders would trade the system for 250. Starting with $100,000 and risking $2,000, here are the results of 50 random traders trading the system:

Fifty traders trading 250 trades of a positive expectancy system

Fifty traders trading 250 trades of a positive expectancy system

I’ve used this example before, and even put it in my first book. The point here, is that results can be a lot more variable than you’d think. None of these traders made mistakes, and there were no surprises–over 250 trades (a large sample) of this positive expectancy system, one unlucky trader lost money, and quite a few struggled. There are lessons here that should give us pause for thought, but let’s focus on something a little different. What happens if we risk different amounts on each trade?

1,000 traders, each trading 250 trades of the same positive expectancy system, risking X per trade

1,000 traders, each trading 250 trades of the same positive expectancy system, risking X per trade

A few points to notice: the more you risk (per trade), the more you make (on average), but there’s a huge red flag–at higher risk levels, the chance of something very bad happening becomes extreme. Remember, this was the same positive expectancy system (expectancy was +0.1) with the same set of trades for each column; the only thing that changed was how much we risked on each trade. At $8,000 risk per trade, 11% of the accounts went bankrupt–trading a winning system! At $25,000 risk, nearly half the accounts went bankrupt. These risk levels seem crazy(or, I hope they seem extreme to you), but many traders are working with risks like this, whether they know it or not.

A picture is worth a lot of words; here’s an illustration of the equity curves from the table above. Pay special attention to the number of traders who “crater” into the zero line–one bankrupt, they are out of the game and have to stop trading.

Equity curves for different traders risking X per trade.

Equity curves for different traders risking X per trade.

Most people are inclined to focus on the good things that could possibly happen, even if they are not likely–this is why lotteries and casinos exist. Use too much risk, focus only on the upside, dream of the big home runs, and you’re rolling the dice; your entire trading account becomes a lottery ticket. Focus on the risk first, manage that risk, and make sure that each of your trades is a correct, consistent bet size, and you’re on the path to being a professional trader and working toward consistency.

A few final thoughts: these examples focus on risking a specific dollar amount per trade. That’s ok, and it’s better than no plan at all, but risking a fixed percentage of your equity (fixed fractional risk) probably makes more sense; as your account grows, you will automatically risk larger dollar amounts and everything scales proportionally. The question of how much to risk does not have an easy answer. There are optimized approaches like the famous Kelly criterion and Ralph Vince’s optimal f, but these can be quite aggressive and may have unacceptable drawdowns for many investors.

A reasonable compromise is to choose a risk per trade of somewhere between 1% – 4% of your equity. Again, the right answer depends on your psychology, trading objectives, and characteristics of your trading method, but this is a good rule of thumb. Paying attention to this critical piece of your investment strategy can make the difference between failure and success.

by  from Adamhgrimes blog

The post Are you losing when you should be winning? Here’s something you might be missing appeared first on System Trader Success.

Case study: Can a simple Market Internals technique actually improve trading strategy results?

$
0
0

In my 10+ years’ full-time trading career, I have found very few tools and tactics that would get my attention so deeply as Market Internals.

In 2014, I spent about six months in a row with this unique traders tool, exploring its possibilities every single day, searching for new and creative implementation ideas for my own automated trading systems (ATSs). With a real obsession for this concept, I finally found almost 40 new ideas (mostly my own proprietary ideas) on how to squeeze the most out of this great tool, and slowly started implementing many of them into my own trading – with great success.

I truly believe that Market Internals can give a trader a small, unfair advantage – if thoroughly thought out and implemented well, especially in new, creative ways. Therefore, in this article I would like to give you a very brief introduction into the Market Internals world, together with an example of one of my private Market Internals filters – to show you, how dramatic the impact of Market Internals deployment can be – in a favorable way.

Introduction: What are Market Internals (MI)

We all know how hard it is to find a new, viable trading edge. We are also aware that the scope of our possibilities is quite narrow: It doesn’t really matter what trading indicators or other tools of technical analysis we use – most of the time they all use the same source of data anyway. This data is consist of Open, High, Low and Close values of the bars in our trading chart, and whatever trading indicator we use, we basically use only a slightly different interpretation of the same O-H-L-C values.

So, if we really want to go a step further and implement a broader view for our trading decisions (trading entry/exit conditions), we have to start investigating outside the O-H-L-C values. We can, for example, implement information like Volume or Open Interest to our trading entry/exit conditions, which is not a bad idea at all, and many of my ATSs use O-H-L-C values together with Volume effectively.

However, we can still go a step further.

We can do something that many traders have no idea they can even do: We can start making our trading (entry/exit) decisions based not only on the data coming from the underlying market but also on taking into consideration the market (its overall direction, quality, strength, and overall “mood” ) as a whole!

Just imagine:

Wouldn’t it be fantastic to know where the stock market as a whole is heading before we enter a position in our emini S&P strategy?

And that is exactly what Market Internals are about: The ability to read the market as a whole and effectively incorporate this much broader view into our trading decisions.

Market Internals: A quick introduction

So what exactly are Market Internals? Where do they come from?

It’s very simple: Market Internals are information about the overall stock market, provided by the stock exchanges (NYSE, AMEX), usually in the form of a standalone data feed.

And this data feed instantly provides us with real-time information about the overall stock market situation.

Using Market Internals we can immediately, in real-time, start receiving information like, for example:

  • How many stocks from the Dow Jones Index have just moved up and how many down?
  • Is the volume of all rising stocks from the Dow Jones Index higher or lower than the volume of all falling ones?

Or even:

  • How do ALL stocks move in the entire NYSE? Are most of them rising or falling?
  • How many stocks have a price that hasn’t changed?
  • What is the direction of the majority of the volume? Up or down?
  • Do the 30 stocks in the Dow Jones Index correspond with the rest of the market, or does the Dow Jones Index now live its own life?

As you can see, there is plenty of information that can be obtained through this standalone data feed about the stock market as a whole (and later on, to be used in our strategies).

All this information can be split into several different categories, and every category has its own meaning and preferred method of implementation. However, because the space for this article is very limited, and the subject of Market Internals could give more than a dozen articles like this, I am going to focus only on one Market Internals category, one of my most favorite, the MI pair UVOL-DVOL.

Market Internals: UVOL-DVOL

This category of MI simply consists of two separate data feeds provided from the exchange:

$UVOL monitors the total volume of all rising stocks on the exchange.

$DVOL monitors the total volume of all falling stocks on the exchange.

By using these data feeds (often called MI indicators), we can monitor the volume on one side or the other, so we can get a better idea where the volume is moving to, i.e. which side is stronger. This is, of course, a very powerful view on the market that can provide us lots of important information (if we know how to use it).

From a practical means, we usually add two different data symbols into our chart (data2 and data3) to start using UVOL-DVOL pair for our trading:

MIChart

Then we can start using these MI indicators as additional, or even leading filters (or as I usually call them – “Super Filters”) for our existing systems – with the goal to improve them significantly.

Let’s have a look at such a condition in practice. I am going to reveal one of my proprietary UVOL-DVOL MI conditions, which I use as a filter for many of my breakout index or stock strategies (MI can only be implemented on indexes or stocks of futures indexes).

UVOL-DVOL as a filter for significant improvement

To demonstrate the effect that Market Internals can have, I have decided to use the most simple condition that I could think of – a primitive breakout condition high=highest(h,N1). I haven’t done any optimization of the N1 parameter, nor have slippage and commission been included in the results shown below – the purpose of this article is not to present a functional breakout trading system but to demonstrate that Market Internals can be applied to even the most basic systems and get immediate, and very often dramatic improvements. For the N1 parameter, I have used the first number that came to my mind, number 20.

Here is the basic code that I will use to demonstrate the impact of the Market Internals “Super Filter”. The test will be completed on the EMD.D market, 15-minute time frame, from 3/22/2006 – 3/21/2016:

If high = highest(h,20) then buy this bar at close;
setstoploss(600);
setexitonclose;

Here are the results:

MI-TSReport-Before

And also the equity curve:

MI-TSChart-Before

Now let’s move on to the implementation of a very simple Market Internals condition that is based on the following rules:

  • Calculate the difference between UVOL and DVOL;
  • Calculate a 30-bar simple moving average of this difference;
  • If the UVOL-DVOL difference is above the moving average of the UVOL-DVOL difference AND high = highest(h,20), a Long position is opened;
  • The position is closed by the end of the day or when the 600 USD stop-loss is hit.

In a moment, I will show you the outcome of the application of this code to the original system. But first, I need to mention that I have used several small add-ons, like for example, taking into consideration the zero line of the UVOL-DVOL difference to cancel the “Super Filter” in certain situations – all of this is included in the code and the workspace that you can download at the end of this article. Yet the basic idea is exactly as I have described it – to work with the UVOL-DVOL difference and with the moving average of this difference.

Let’s take a look at the results after application of the Market Internals “Super Filter”. First, the performance report:

MI-TSReport-After

Now the equity:

MI-TSChart-After

And finally the comparison table showing the results before and after the application of the Market Internals “Super Filter”.

Metric Before MI After MI Improvement
Net Profit 79,440 76,000 -4.3%
Profit Factor 1.17 1.38 +17.9%
Avg. Trade 36.52 63.81 +74.7%
Max DD (C-to-C) 12,650 7,790 -36.8%
Net Profit / Max DD 6.28 9.76 +55.4%
Trades 2175 1191 -45.2%

I believe that the numbers speak for themselves – maximum drawdown has improved by almost 40% (36.8%), Average trade by +74.8%, and the Net Profit to Maximum DD ratio by +55.4%. All really great improvements, and I see similar improvements of Market Internals very often.

Conclusion

I have been using Market Internals for my own trading since 2014.

Here is what I have generally achieved by implementing them into my own trading strategies:

  • Reduce max. Drawdown
  • Improve Avg. Trade
  • Improve Net Profit / Max DD ratio
  • Smoother equity curve
  • Overall improvement of portfolio performance
  • Getting additional psychological confidence by knowing that I only trade in highly favorable market conditions.

I was really surprised that Market Internals are used by so few traders, yet when I present them the Market Internals possibilities, they usually get quite excited and implement it to their own trading systems with instant positive impact.

This is exactly the reason why I like them and I encourage all traders to investigate them further.

Please visit this link at Better System Trader to download the source code used in this article.

— by Tomas Nesnidal from blog, Better System Trader

The post Case study: Can a simple Market Internals technique actually improve trading strategy results? appeared first on System Trader Success.

Beginner’s Guide to Quantitative Trading

$
0
0

In this article I’m going to introduce you to some of the basic concepts which accompany an end-to-end quantitative trading system. This post will hopefully serve two audiences. The first will be individuals trying to obtain a job at a fund as a quantitative trader. The second will be individuals who wish to try and set up their own “retail” algorithmic trading business.

Quantitative trading is an extremely sophisticated area of quant finance. It can take a significant amount of time to gain the necessary knowledge to pass an interview or construct your own trading strategies. Not only that but it requires extensive programming expertise, at the very least in a language such as MATLAB, R or Python. However as the trading frequency of the strategy increases, the technological aspects become much more relevant. Thus being familiar with C/C++ will be of paramount importance.

 A quantitative trading system consists of four major components:

  • Strategy Identification – Finding a strategy, exploiting an edge and deciding on trading frequency
  • Strategy Backtesting – Obtaining data, analysing strategy performance and removing biases
  • Execution System – Linking to a brokerage, automating the trading and minimising transaction costs
  • Risk Management – Optimal capital allocation, “bet size”/Kelly criterion and trading psychology

We’ll begin by taking a look at how to identify a trading strategy.

Strategy Identification

All quantitative trading processes begin with an initial period of research. This research process encompasses finding a strategy, seeing whether the strategy fits into a portfolio of other strategies you may be running, obtaining any data necessary to test the strategy and trying to optimise the strategy for higher returns and/or lower risk. You will need to factor in your own capital requirements if running the strategy as a “retail” trader and how any transaction costs will affect the strategy.

Contrary to popular belief it is actually quite straightforward to find profitable strategies through various public sources. Academics regularly publish theoretical trading results (albeit mostly gross of transaction costs). Quantitative finance blogs will discuss strategies in detail. Trade journals will outline some of the strategies employed by funds.

You might question why individuals and firms are keen to discuss their profitable strategies, especially when they know that others “crowding the trade” may stop the strategy from working in the long term. The reason lies in the fact that they will not often discuss the exact parameters and tuning methods that they have carried out. These optimisations are the key to turning a relatively mediocre strategy into a highly profitable one. In fact, one of the best ways to create your own unique strategies is to find similar methods and then carry out your own optimisation procedure.

Here is a small list of places to begin looking for strategy ideas:

Many of the strategies you will look at will fall into the categories of mean-reversion and trend-following/momentum. A mean-reverting strategy is one that attempts to exploit the fact that a long-term mean on a “price series” (such as the spread between two correlated assets) exists and that short term deviations from this mean will eventually revert. A momentum strategy attempts to exploit both investor psychology and big fund structure by “hitching a ride” on a market trend, which can gather momentum in one direction, and follow the trend until it reverses.

Another hugely important aspect of quantitative trading is the frequency of the trading strategy.Low frequency trading (LFT) generally refers to any strategy which holds assets longer than a trading day. Correspondingly, high frequency trading (HFT) generally refers to a strategy which holds assets intraday. Ultra-high frequency trading (UHFT) refers to strategies that hold assets on the order of seconds and milliseconds. As a retail practitioner HFT and UHFT are certainly possible, but only with detailed knowledge of the trading “technology stack” and order book dynamics. We won’t discuss these aspects to any great extent in this introductory article.

Once a strategy, or set of strategies, has been identified it now needs to be tested for profitability on historical data. That is the domain of backtesting.

Strategy Backtesting

The goal of backtesting is to provide evidence that the strategy identified via the above process is profitable when applied to both historical and out-of-sample data. This sets the expectation of how the strategy will perform in the “real world”. However, backtesting is NOT a guarantee of success, for various reasons. It is perhaps the most subtle area of quantitative trading since it entails numerous biases, which must be carefully considered and eliminated as much as possible. We will discuss the common types of bias including look-ahead biassurvivorship bias andoptimisation bias (also known as “data-snooping” bias). Other areas of importance within backtesting include availability and cleanliness of historical data, factoring in realistic transaction costs and deciding upon a robust backtesting platform. We’ll discuss transaction costs further in the Execution Systems section below.

Once a strategy has been identified, it is necessary to obtain the historical data through which to carry out testing and, perhaps, refinement. There are a significant number of data vendors across all asset classes. Their costs generally scale with the quality, depth and timeliness of the data. The traditional starting point for beginning quant traders (at least at the retail level) is to use the free data set from Yahoo Finance. I won’t dwell on providers too much here, rather I would like to concentrate on the general issues when dealing with historical data sets.

The main concerns with historical data include accuracy/cleanliness, survivorship bias and adjustment for corporate actions such as dividends and stock splits:

  • Accuracy pertains to the overall quality of the data – whether it contains any errors. Errors can sometimes be easy to identify, such as with a spike filter, which will pick out incorrect “spikes” in time series data and correct for them. At other times they can be very difficult to spot. It is often necessary to have two or more providers and then check all of their data against each other.
  • Survivorship bias is often a “feature” of free or cheap datasets. A dataset with survivorship bias means that it does not contain assets which are no longer trading. In the case of equities this means delisted/bankrupt stocks. This bias means that any stock trading strategy tested on such a dataset will likely perform better than in the “real world” as the historical “winners” have already been preselected.
  • Corporate actions include “logistical” activities carried out by the company that usually cause a step-function change in the raw price, that should not be included in the calculation of returns of the price. Adjustments for dividends and stock splits are the common culprits. A process known as back adjustment is necessary to be carried out at each one of these actions. One must be very careful not to confuse a stock split with a true returns adjustment. Many a trader has been caught out by a corporate action!

In order to carry out a backtest procedure it is necessary to use a software platform. You have the choice between dedicated backtest software, such as Tradestation, a numerical platform such as Excel or MATLAB or a full custom implementation in a programming language such as Python or C++. I won’t dwell too much on Tradestation (or similar), Excel or MATLAB, as I believe in creating a full in-house technology stack (for reasons outlined below). One of the benefits of doing so is that the backtest software and execution system can be tightly integrated, even with extremely advanced statistical strategies. For HFT strategies in particular it is essential to use a custom implementation.

When backtesting a system one must be able to quantify how well it is performing. The “industry standard” metrics for quantitative strategies are the maximum drawdown and the Sharpe Ratio. The maximum drawdown characterises the largest peak-to-trough drop in the account equity curve over a particular time period (usually annual). This is most often quoted as a percentage. LFT strategies will tend to have larger drawdowns than HFT strategies, due to a number of statistical factors. A historical backtest will show the past maximum drawdown, which is a good guide for the future drawdown performance of the strategy. The second measurement is the Sharpe Ratio, which is heuristically defined as the average of the excess returns divided by the standard deviation of those excess returns. Here, excess returns refers to the return of the strategy above a pre-determined benchmark, such as the S&P500 or a 3-month Treasury Bill. Note that annualised return is not a measure usually utilised, as it does not take into account the volatility of the strategy (unlike the Sharpe Ratio).

Once a strategy has been backtested and is deemed to be free of biases (in as much as that is possible!), with a good Sharpe and minimised drawdowns, it is time to build an execution system.

Execution Systems

An execution system is the means by which the list of trades generated by the strategy are sent and executed by the broker. Despite the fact that the trade generation can be semi- or even fully-automated, the execution mechanism can be manual, semi-manual (i.e. “one click”) or fully automated. For LFT strategies, manual and semi-manual techniques are common. For HFT strategies it is necessary to create a fully automated execution mechanism, which will often be tightly coupled with the trade generator (due to the interdependence of strategy and technology).

The key considerations when creating an execution system are the interface to the brokerage, minimisation of transaction costs (including commission, slippage and the spread) and divergence of performance of the live system from backtested performance.

There are many ways to interface to a brokerage. They range from calling up your broker on the telephone right through to a fully-automated high-performance Application Programming Interface (API). Ideally you want to automate the execution of your trades as much as possible. This frees you up to concentrate on further research, as well as allow you to run multiple strategies or even strategies of higher frequency (in fact, HFT is essentially impossible without automated execution). The common backtesting software outlined above, such as MATLAB, Excel and Tradestation are good for lower frequency, simpler strategies. However it will be necessary to construct an in-house execution system written in a high performance language such as C++ in order to do any real HFT. As an anecdote, in the fund I used to be employed at, we had a 10 minute “trading loop” where we would download new market data every 10 minutes and then execute trades based on that information in the same time frame. This was using an optimised Python script. For anything approaching minute- or second-frequency data, I believe C/C++ would be more ideal.

In a larger fund it is often not the domain of the quant trader to optimise execution. However in smaller shops or HFT firms, the traders ARE the executors and so a much wider skillset is often desirable. Bear that in mind if you wish to be employed by a fund. Your programming skills will be as important, if not more so, than your statistics and econometrics talents!

Another major issue which falls under the banner of execution is that of transaction cost minimisation. There are generally three components to transaction costs: Commissions (or tax), which are the fees charged by the brokerage, the exchange and the SEC (or similar governmental regulatory body); slippage, which is the difference between what you intended your order to be filled at versus what it was actually filled at; spread, which is the difference between the bid/ask price of the security being traded. Note that the spread is NOT constant and is dependent upon the current liquidity (i.e. availability of buy/sell orders) in the market.

Transaction costs can make the difference between an extremely profitable strategy with a good Sharpe ratio and an extremely unprofitable strategy with a terrible Sharpe ratio. It can be a challenge to correctly predict transaction costs from a backtest. Depending upon the frequency of the strategy, you will need access to historical exchange data, which will include tick data for bid/ask prices. Entire teams of quants are dedicated to optimisation of execution in the larger funds, for these reasons. Consider the scenario where a fund needs to offload a substantial quantity of trades (of which the reasons to do so are many and varied!). By “dumping” so many shares onto the market, they will rapidly depress the price and may not obtain optimal execution. Hence algorithms which “drip feed” orders onto the market exist, although then the fund runs the risk of slippage. Further to that, other strategies “prey” on these necessities and can exploit the inefficiencies. This is the domain of fund structure arbitrage.

The final major issue for execution systems concerns divergence of strategy performance from backtested performance. This can happen for a number of reasons. We’ve already discussed look-ahead bias and optimisation bias in depth, when considering backtests. However, some strategies do not make it easy to test for these biases prior to deployment. This occurs in HFT most predominantly. There may be bugs in the execution system as well as the trading strategy itself that do not show up on a backtest but DO show up in live trading. The market may have been subject to a regime change subsequent to the deployment of your strategy. New regulatory environments, changing investor sentiment and macroeconomic phenomena can all lead to divergences in how the market behaves and thus the profitability of your strategy.

Risk Management

The final piece to the quantitative trading puzzle is the process of risk management. “Risk” includes all of the previous biases we have discussed. It includes technology risk, such as servers co-located at the exchange suddenly developing a hard disk malfunction. It includes brokerage risk, such as the broker becoming bankrupt (not as crazy as it sounds, given the recent scare with MF Global!). In short it covers nearly everything that could possibly interfere with the trading implementation, of which there are many sources. Whole books are devoted to risk management for quantitative strategies so I wont’t attempt to elucidate on all possible sources of risk here.

Risk management also encompasses what is known as optimal capital allocation, which is a branch of portfolio theory. This is the means by which capital is allocated to a set of different strategies and to the trades within those strategies. It is a complex area and relies on some non-trivial mathematics. The industry standard by which optimal capital allocation and leverage of the strategies are related is called the Kelly criterion. Since this is an introductory article, I won’t dwell on its calculation. The Kelly criterion makes some assumptions about the statistical nature of returns, which do not often hold true in financial markets, so traders are often conservative when it comes to the implementation.

Another key component of risk management is in dealing with one’s own psychological profile. There are many cognitive biases that can creep in to trading. Although this is admittedly less problematic with algorithmic trading if the strategy is left alone! A common bias is that of loss aversion where a losing position will not be closed out due to the pain of having to realise a loss. Similarly, profits can be taken too early because the fear of losing an already gained profit can be too great. Another common bias is known as recency bias. This manifests itself when traders put too much emphasis on recent events and not on the longer term. Then of course there are the classic pair of emotional biases – fear and greed. These can often lead to under- or over-leveraging, which can cause blow-up (i.e. the account equity heading to zero or worse!) or reduced profits.

Summary

As can be seen, quantitative trading is an extremely complex, albeit very interesting, area of quantitative finance. I have literally scratched the surface of the topic in this article and it is already getting rather long! Whole books and papers have been written about issues which I have only given a sentence or two towards. For that reason, before applying for quantitative fund trading jobs, it is necessary to carry out a significant amount of groundwork study. At the very least you will need an extensive background in statistics and econometrics, with a lot of experience in implementation, via a programming language such as MATLAB, Python or R. For more sophisticated strategies at the higher frequency end, your skill set is likely to include Linux kernel modification, C/C++, assembly programming and network latency optimisation.

If you are interested in trying to create your own algorithmic trading strategies, my first suggestion would be to get good at programming. My preference is to build as much of the data grabber, strategy backtester and execution system by yourself as possible. If your own capital is on the line, wouldn’t you sleep better at night knowing that you have fully tested your system and are aware of its pitfalls and particular issues? Outsourcing this to a vendor, while potentially saving time in the short term, could be extremely expensive in the long-term.

By–Mike from QuantStart where you can find everything you need to help you gain (and keep!) a lucrative job in quantitative finance.

The post Beginner’s Guide to Quantitative Trading appeared first on System Trader Success.


How to Trade the MACD: A High-level Analysis of the MACD Line Feature

$
0
0

Moving Average Convergence Divergence (MACD) is one of the most popular technical indicators used by traders.

It is a flexible indicator that can be used for determining the strength and direction of a trend. It has three distinct features and in this first post we are going to do a high-level analysis of one of those features, the MACD Line.

We will compare three of the most common MACD Line settings on the EUR/USD using daily bars over the past few years to determine whether or not there is a historical pattern that can be exploited.

What is the MACD Line?

The MACD Line was the first feature developed in the MACD indicator. It was developed around 1977 by Gerald Appel. The other two features are the MACD Signal Line, a smoothed average of the MACD Line, and the MACD Histogram, which is the difference between the Signal Line and the MACD Line.

MACD Indicator on EUR/USD 1-Day Bars

The MACD Line is composed of a fast and slow moving average. The value of the MACD Line is the difference between the two moving averages. The default settings for the two moving averages are typically 12-period (fast) and 26-period (slow) exponential moving averages and are generally calculated off of the close price of an asset. Using the MACD Line is the exact same as using a moving average cross. If you subtract the price of a fast-period moving average from the price of a slow-period moving average, you will get the value of the MACD Line. Gerald Appel also commonly uses default periods of 19- and 39-period EMAs while Tom Aspray, who added the histogram feature and studied the MACD in the 1980s commonly uses 10- and 20-period EMAs.

Gerald Appel claims, “As a general rule of thumb, the market climate is most unfavorable when the MACD is falling and below zero.” We’ll take the latter part of his rule of thumb to form our hypothesis; it is unfavorable to go long when the MACD Line is below 0 and it is unfavorable to go short when the MACD Line is above 0.

Using TRAIDE we can test exactly how favorable and unfavorable the market is when the MACD Line is above and below zero; We will try to find values of the MACD Line that lead to bullish and bearish moves the following day by looking at every trading day between August 1st, 2012 and March 24, 2015.

MACD Line (12, 26-Period EMAs) Analysis

TRAIDE automatically generates a histogram of the empirical data to display the distribution of the MACD Line values over our date range. The histogram will show how many of the next days’ bars closed up and how many closed down for every MACD Line value over our date range.

To create the histogram, we will first select the asset we want to analyze, the timeframe and date range. We then select the MACD Line feature under the MACD indicator group in the middle column of TRAIDE’s Strategy Creation page. We can ignore the “Signal Moving Average Type” and “Signal Period” in the indicator settings because we are not using the MACD Signal feature.

Selecting the MACD in TRAIDE

Let’s click analyze and look at the distribution.

MACD Line EUR/USD Distribution

  • y-axis: The number of trades, or trading days, between 08/01/2012 and 03/24/2015.
  • x-axis:The values of the MACD Line, ranging from -0.026 to 0.018.
  • Dividing lines on x-axis: This is the width of a “bin”. There are 10 bins and the edges of the bins are labeled. For example, -0.022 to -0.018 is one bin.
  • Red bars: The height of red bars represents the number of trading days where the following day was bearish, or the close was lower than the open, in any particular bin.
  • Green bars: The height of green bars represents the number trading days where the following day was bullish, or the close was higher than the open. in any particular bin.
  • Shading of the bars: We won’t be using the shading, but this is the strength of signal for that bin. Darker green means that the algorithms found strong signals to go long and darker red bars means that TRAIDE’s algorithms found strong signals for going short.

Using our distribution, let’s test our hypothesis.

The first step is to remove the ambiguous information. The red and green bars in bin -0.002 (-20 pips) to 0.002 (20 pips) straddle the zero line; we don’t know whether the next day closed up or down since we cannot distinguish between the trades that occurred right around zero.

The next step is to click all of the green bars above 0.002 and all of the red bars below -0.002 and see what the accuracy is in our statistics table for each case. When we select the green bars, we are going long for all positive values of the MACD Line above 0.002 and going short for all negative values below -0.002. We want to see if just this simple rule will lead to over 50% of our trades being correct.

Selecting Positive and Negative MACD Line Values

What we find is that when the MACD Line is positive, the price on the next day tends to close higher than the previous bar’s close and when the MACD Line is negative, the price on the following day tends to close below the current day’s close. There were 640 trades in our sample.

It turns out that our hypothesis is true. There is a historical pattern; when the MACD Line is negative (less than -0.002), the next day is bearish 52% of the time and presents an unfavorable condition to go long. When the MACD Line is positive (greater than 0.002), the next day is bullish 54% of the time, presenting an unfavorable condition for going short.

Let’s dive in a little bit deeper and see if we can refine our MACD Line values. From the distribution, it looks like the tail ends of the histograms don’t present a clear historical pattern while the histogram bars on either side of the -0.002 to 0.002 bin appear to have a clear pattern.

Finding the Best Values for Long or Short (MACD Line (12, 26))

On the days where the MACD Line is greater than 0.002, but less than 0.006, the next day was bullish 58% of the time with 183 total trades. In other words, when the 12-period EMA is between 20 and 60 pips above the 26-period EMA the next day closed up 58% of the time. On the days where the MACD Line was less than -0.002 but greater than -0.006, the next day was bearish 52% of the time. We went from a sample size of 640 trades to 380.

Selecting The Best Positive and Negative MACD Line Values

You can use this information to not go long when the MACD Line is between 0.002 and 0.006 or if you are going long, check to see if the MACD Line is within that range. The same goes for going short but with the negative MACD Line values. You could also use this information for the basis of a strategy. Waiting for the MACD Line, with 12- and 26-period EMAs, to be between 0.002 and 0.006 would be a good first filter for going long. I would recommend adding a couple other indicators that you like using. Let’s take a look at the other commonly used settings.

MACD Line (19, 39-Period EMAs) Analysis

Changing the defaults to use 19- and 39-period EMAs in TRAIDE:

Selecting MACD Line Settings 19 and 39-period EMAs

Once I hit analyze, the distribution will load on the Dashboard:

MACD Line Distribution 19 and 39-period EMAs

The two longer EMAs have caused a slight skew left. Let’s apply the same logic that we did in with the 12- and 26-period EMAs to do our analysis. Let’s remove the ambiguous data where the bin could be positive or negative. This takes out the bin -0.0021 to 0.0021. Then let’s select all the green bars to the right of 0.0021 and all the red bars to the left of -0.0021.

MACD Line Distributions Long/Short 19 and 39-period EMAs

Again what we find is that our hypothesis holds to be true; when the MACD Line is positive (above 0.0021), the following day had a 53% chance of closing higher than the previous day’s close. When the MACD Line is negative, the EUR/USD had a 52% chance of closing lower than the previous day’s close.

Looking at the histogram, there appears to be a very similar pattern to our 12- and 26-period settings so let’s take a look and see if we can refine the MACD Line values.

Finding the Best Values for Long or Short (MACD Line (19, 39))

If we click just the bars on either side of the -0.0021 to 0.0021 bin, we can see that 53% of the time, the following day closed lower than the previous day’s close when the MACD Line was negative (below -0.0021) while 54% of the time the next day’s close was higher than the previous day’s close when the MACD Line is positive (above 0.0021).

MACD Line Distributions the Best Long/Short 19 and 39-period EMAs

We found similar results, but the 12- and 26-period EMAs found a stronger pattern for going long, while the 19- and 39-period EMAs led to a slightly strong pattern for going short. Now let’s take a look at our final MACD Line settings; the 10 and 20-period EMAs.

MACD Line (10, 20-Period EMAs) Analysis

We find something very similar when we use 10 and 20-period EMAs. 54% of the time, when the MACD Line is positive (above 0.0017) the following day closed above the previous day’s close. 52% of the time, when the MACD Line is negative (below -0.0017) the following day closed below the previous day’s close. Our sample size is 630.

MACD Line Distributions 10 and 20-period EMAs

Applying the same process as the other two MACD Line parameters, we will see if the values that are just positive and just negative lead to a stronger historical pattern.

Finding the Best Values for Long or Short (MACD Line (10, 20))

MACD Line Distributions the Best 10 and 20-period EMAs

It appears so! Once again, selecting the bin to go short where the MACD Line is less than -0.0017 but greater than -0.0051 gave us 177 days where the following day closed lower than the previous day’s close 57% of the time. Selecting the bin to go long, where the MACD Line is greater than 0.0017 but less than 0.0051 gave us 194 days where the following day closed high than the previous day’s close. 54% of the time.

Summary

The MACD Line, using commonly used settings, is a reliable feature of the MACD indicator for determining whether or not it is favorable to go long or short on the EUR/USD using 1-day bars. I would suggest combining this feature with other indicators, using the MACD Line as a filter, or using it to confirm your trading decision. If you are applying this to other currency pairs or timeframes, make sure you study the MACD Line over those charts. Difference pairs and timeframes are going to behave in their own way.

A table of our results with the percent correct with each of the indicator settings:

Ema1

We can also conclude that the different period settings that we tested do not have a significant impact on whether or not the MACD Line can be used to determine whether or not the market is favorable or unfavorable for going long or short. What did have a significant impact was removing the tail ends of our histograms. Instead, when the MACD Line was just positive or just negative, our accuracy went of significantly for both long and short.

For all three indicator settings, it was better when we refined our parameters by selecting the bins where the MACD Line was just positive or just negative:

A table of our results with the percent correct with each of the indicator settings:

ema 2

It appears that the shorter EMAs, 10 and 20-period, returned the highest accuracy.

This high-level analysis on the empirical data of the EUR/USD using 1-day bars provides a good starting point for incorporating the MACD into your trading. The MACD Line is a reliable feature of the MACD indicator where we can find clear historical patterns.

You can generate these histograms in TRAIDE for any major currency on 1-hour, 4-hour, 6-hour, or 1-day bars since January 1st, 2012.

— by Justin Cahoon from Inovancetech Blog.

The post How to Trade the MACD: A High-level Analysis of the MACD Line Feature appeared first on System Trader Success.

Statistical Analysis For Exits

$
0
0

As system designers, we hit the problem that whilst it seems relatively straightforward to develop entries and then test them against arbitrary exits, the reverse is a lot trickier. I have found out that doing some very simple statistical analysis can help in exit rule development. Over the years it has appeared to me that some markets seem far choppier than others in their intraday price action and I use that observation here to do one of those analyses. What I am looking at in this piece is the tendency of markets to finish the day within a certain percentage of the high or low for the day.

To ‘close at the close’ The time of day can be a very useful building block in system development. This applies to the time of entry of trades, of exits, the inputs of many indicators used, and also using individually tailored trading sessions. In developing rules for algorithmic trading, the timing of exits are frequently neglected or ignored. Commonly systems enter on some type of signal and then exit during the last few bars leading into the close, or some subsequent close. This tendency of both systems and discretionary traders, both big and small, to ‘close at the close’ is one of the factors leading to a spike in trading volumes that is seen across most products at the end of the trading session, or the end of the old pit trading session.

Liquidity Profile For large fund managers and CTAs, the key factor to take into consideration on timing of entries and exits is liquidity and this will trump the improvements in performance that can be gained by timing trades optimally. All the clever execution algorithms in the world will only help so much and these players tend to bunch their trading at the open or close as the ‘liquidity tax’ of slippage would be too high to trade much at other times. This is because most contracts generally have a ‘U’-shaped liquidity profile during the day where trade liquidity (volumes) peak at the open and at the close. Indices and rates are usually quite a symmetric clean U shape whereas some products such as metals and energies have persistent volume bulges, but even then most have a significant volume spike at the close.

Click to enlarge

Click to enlarge

For most retail traders though, trading has relatively few contracts at a time, liquidity should be much less an issue. For systems designers, the tendency in the design of trading rules doesn’t seem to take any particular consideration as to whether closing a trade during these final minutes is optimal.

Compulsory and Optional Trading Rules Personally, I think of trading rules in terms of being either compulsory or optional. Compulsory rules are any forms of stop loss, which should be executed immediately as they occur, no matter what the timing is. Optional rules would be almost any other types such as profit targets or length of trade exit rules, and potentially most types of entry rules where there is a greater degree of freedom to design when the rules should execute. For these rules, adding a timing element can markedly improve performance.

How to Use This in Rule Design This has obvious implications in systems design. For those products that most likely to close at the extreme of the day, the closing bars of whichever day would appear to be the optimal time to exit those trades, assuming the trade is in the correct direction (such as trend following methodologies). However, for those contracts less likely to close at the extreme of the day, then optimizing time of day for exits through the usual rigorous testing processes would seem a much better way to develop those optional rules.

Methodology: I took a variety of products and assumed entry at the close of the first 10-minute bar of the trading session and exit on the 2nd to last 10-minute bar of the trading session. Using this method gives actual trading levels rather than exchange closes which have ruined many good trading system designer’s day. I did not choose a fixed number of bars, as this of course varies according to product, although many are almost open 24 hours a day which would theoretically be 144 10-minute bars. The likelihood of the exit price being within 10% of the high or low of the entire trading session was measured. Setting multiple series of random data as a check, unsurprisingly the results tend to approximate to 20% and because of the number of data points, generally very close indeed to this number. The data was run from 2007 to 2016, generating roughly 2,300 data points for each product. It doesn’t really matter whether each product has moved significantly up or down over the period covered by the test, as this is simply a test of closing at the extreme of the day, either high or low.

Results For me there were a couple of interesting facts that came from the results:

Results_Table
* Within product types. Gasoline is more likely to close at an extreme than WTI crude and Natural Gas even more likely than Gasoline. This fact ties directly to my own experience where I have always found it easier to develop day trading trend type systems that close at the close for Natural Gas and Gasoline than is true for WTI Crude. The eMini Russell 2000 is more likely than the eMini S&P to finish at an extreme and whilst the Russell is obviously highly correlated to the S&P, it appears to exhibit less ‘chop’ in its daily movements.

Group1
* The other interesting takeaway is the correlation between the results of different product groups, so the energies and stock indices and rates were all significantly more likely to close near the extreme for the day. All things being equal, we could conclude that these contracts would lend themselves more to day trading trend system than any other products.

Group2 The metals and most of the currencies were significantly less likely to close at the extreme for the day and this has some important implications for systems developers:
* These are the products that would be the most difficult to develop day trading trend systems exiting at the close for.
* The corollary of this difficulty is that for systems that do close at the close, these are probably the most fruitful contracts to explore for day trading counter-trend systems.
* For exits in general, these are the contracts where greater attention effort should be invested in time-of-the-day exits as exiting at the close may well not be the best way to go. A statistical bias for a single contract can be interesting but a lot more weight can be attached when we see a similar bias across multiple difference but related contracts such as the equity indices or the metals. As with any very simple statistical analysis such as that above, we are not going to get hard and fast rules, just a much better road map of where and how to direct research in our system development.

The post Statistical Analysis For Exits appeared first on System Trader Success.

9 Mistakes Quants Make that Cause Backtests to Lie

$
0
0

"I’ve never seen a bad backtest” -- Dimitris Melas, head of research at MSCI.

A backtest is a simulation of a trading strategy used to evaluate how effective the strategy might have been if it were traded historically. Backtestesting is used by hedge funds and other researchers to test strategies before real capital is applied. Backtests are valuable because they enable quants to quickly test and reject trading strategy ideas.

All too often strategies look great in simulation but fail to live up to their promise in live trading. There are a number of reasons for these failures, some of which are beyond the control of a quant developer. But other failures are caused by common, insidious mistakes.

An over optimistic backtest can cause a lot of pain. I’d like to help you avoid that pain by sharing 9 of the most common pitfalls in trading strategy development and testing that can result in overly optimistic backtests:

1. In-sample backtesting

Many strategies require refinement, or model training of some sort. As one example, a regression-based model that seeks to predict future prices might use recent data to build the model. It is perfectly fine to build a model in that manner, but it is not OK to test the model over that same time period. Such models are doomed to succeed.

Don’t trust them.

Solution: Best practices are to build procedures to prevent testing over the same data you train over. As a simple example you might use data from 2007 to train your model, but test over 2008-forward.

By the way, even though it could be called “out-of-sample” testing it is not a good practice to train over later data, say 2014, then test over earlier data, say 2008-2013. This may permit various forms of lookahead bias.

2. Using survivor-biased data

Suppose I told you I have created a fantastic new blood pressure medicine, and that I had tested it using the following protocol:

a. Randomly select 500 subjects
b. Administer my drug to them every day for 5 years
c. Measure their blood pressure each day

At the beginning of the study the average blood pressure of the participants was 160/110, at the end of the study the average BP was 120/80 (significantly lower and better).

Those look like great results, no? What if I told you that 58 of the subjects died during the study? Maybe it was the ones with the high blood pressure that died! This is clearly not an accurate study because it focused on the statistics of survivors at the end of the study.

This same sort of bias is present in backtests that use later lists of stocks (perhaps members of the S&P 500) as the basis for historical evaluations over earlier periods. A common example is to use the current S&P 500 as the universe of stocks for testing a strategy.

Why is this bad? See the two figures below for illustrative examples.

Figure: The green lines show historical performance of stocks that were members of the S&P 500 in 2012. Note that all of these stocks came out of the 2008/2009 downturn very nicely.

Figure: What really happened: If, instead we use the members of the S&P 500 starting in 2008, we find that more than 10% of the listed companies failed.

In our work at Lucena Research, we see an annual 3% to 5% performance “improvement” with strategies using survivor-biased data.

Solution: Find datasets that include historical members of indices, then use those lists to sample from for your strategies.

3. Observing the close & other forms of lookahead bias

In this failure mode, the quant assumes he can observe market closing prices in order to compute an indicator, and then also trade at the close. As an example, one might use closing price/volume to calculate a technical factor used in the strategy, then trade based on that information.

This is a specific example of lookahead bias in which the strategy is allowed to peek a little bit into the future. In my work I have seen time and again that even a slight lookahead bias can provide fantastic (and false) returns.

Other examples of lookahead bias have to do with incorrect registration of data such as earnings reports or news. Assuming for instance that one can trade on the same day earnings are announced even though earnings are usually announced after the close.

Solution: Don’t trade until the open of the next day after information becomes available.

4. Ignoring market impact

The very act of trading affects price. Historical pricing data does not include your trades and is therefore not an accurate representation of the price you would get if you were trading.

Consider the chart below that describes the performance of a real strategy I helped develop. Consider the region A, the first part of the upwardly sloping orange line. This region was the performance of our backtest. The strategy had a Sharpe Ratio over 7.0! Based on the information we had up until that time (the end of A), it looked great so we started trading it.

When we began live trading we saw the real performance illustrated with the green “live” line in region B– essentially flat. The strategy was not working, so we halted trading it after a few weeks. After we stopped trading it, the strategy started performing well again in paper trading (Region C, Arg!).

How can this be? We thought perhaps that the error was in our predictive model, so we backtested again over the “live” area and the backtest showed that same flat area. The only difference between the nice 7.0 Sharpe Ratio sections and the flat section was that we were engaged in the market in the flat region.

What was going on? The answer, very simply, is that by participating in the market we were changing the prices to our disadvantage. We were not modeling market impact in our market simulation. Once we added that feature more accurately, our backtest appropriately showed a flat, no-return result for region A. If we had had that in the first place we probably would never have traded the strategy.

Solution: Be sure to anticipate that price will move against you at every trade. For trades that are a small part of overall volume, a rule of thumb is about 5 bps for S&P 500 stocks and up to 50 bps for more thinly traded stocks. It depends of course on how much of the market your strategy is seeking to trade.

5. Buy $10M of a $1M company

Naïve backtesters will allow a strategy to buy or sell as much of an asset as it likes. This may provide a misleadingly optimistic backtest because large allocations to small companies are allowed.

There often is real alpha in thinly traded stocks, and data mining approaches are likely to find it. Consider for a moment why it seems there is alpha there. The reason is that the big hedge funds aren’t playing there because they can’t execute their strategy with illiquid assets. There are perhaps scraps of alpha to be collected by the little guy, but check to be sure you’re not assuming you can buy $10M of a $1M company.

Solution: Have your backtester limit the strategy’s trading to a percentage of the daily dollar volume of the equity. Another alternative is to filter potential assets to a minimum daily dollar volume.

6. Overfit the model

An overfit model is one that models in-sample data very well. It predicts the data so well that it is likely modeling noise rather than the underlying principle or relationship in the data that you are hoping it will discover.

Here’s a more formal definition of overfitting: As the degrees of freedom of the model increase, overfitting occurs when in-sample prediction error decreases and out-of-sample prediction error increases.

What do we mean by “degrees of freedom?” Degrees of freedom can take many forms, depending on the type of model being created: Number of factors used, number of parameters in a parameterized model and so on.

Solution: Don’t repeatedly “tweak” and “refine” your model using in-sample data. And always compare in-sample error versus out-of-sample error.

7. Trust complex models

Complex models are often overfit models. Simple approaches that arise from a basic idea that makes intuitive sense lead to the best models. A strategy built from a handful of factors combined with simple rules is more likely to be robust and less sensitive to overfitting than a complex model with lots of factors.

Solution: Limit the number of factors considered by a model, use simple logic in combining them.

8. Trusting stateful strategy luck

A stateful strategy is one whose holdings over time depend on which day in history it was started. As an example, if the strategy rapidly accrues assets, it may be quickly fully invested and therefore miss later buying opportunities. If the strategy had started one day later, it’s holdings might be completely different.

Sometimes such strategies’ success vary widely if they are started on a different day. I’ve seen, for instance, a difference in 50% return for the same strategy started on two days in the same week.

Solution: If your strategy is stateful, be sure to test it starting on many difference days. Evaluate the variance of the results across those days. If is large you should be concerned.

9. Data mining fallacy

Even if you avoid all of the pitfalls listed above, if you generate and test enough strategies you’ll eventually find one that works very well in a backtest. However, the quality of the strategy cannot be distinguished from a lucky random stock picker.

How can this pitfall be avoided? It can’t be avoided. However, you can and should forward test before committing significant capital.

Solution: Forward test (paper trade) a strategy before committing capital.

Summary

It is best to view backtesting as a method for rejecting strategies, than as a method for validating strategies. One thing is for sure: If it doesn’t work in a backtest, it won’t work in real life. The converse is not true: Just because it works in a backtest does not mean you can expect it to work in live trading.

However, if you avoid the pitfalls listed above, your backtests stand a better chance of more accurately representing real life performance.

-- Tucker Balch from Augmented Trader

The post 9 Mistakes Quants Make that Cause Backtests to Lie appeared first on System Trader Success.

World’s Simplest Trading System

$
0
0

Here’s the system: At the end of every month,
* if the index is above its 10-month simple moving average: the portfolio is 100% in the market
* if the index is below its 10-month simple moving average: the portfolio is 100% in cash

 And that’s it. So, if we take the FTSE 100 Index as an example, if at the end of a month the FTSE 100 is above its 10-month simple moving average then either,
* the portfolio moves into the market by buying, say FTSE 100 ETFs, (these will be the easiest instrument for most investors, but equally futures, CFDs or spread bets could be used), or
* nothing needs to be done if the portfolio is ready in the market. Conversely, if at the end of a month the FTSE 100 is below its 10-month simple moving average then the portfolio sells the ETFs and moves 100% to cash; if it is already in cash then nothing is done. [NB. OK, it’s possible that this isn’t absolutely the simplest trading system imaginable, but apart from buy and hold it is unlikely there are many systems much simpler than this one!] The following chart illustrates such a portfolio for the FTSE 100 Index since 1995. The diamond markers indicate the decisions made at the end of each month whether to be in the market (green diamond) or in cash (red diamond).

SMA-10M-Trading-System Roughly, one can see that the system kept the portfolio in the market in uptrends and out of the market (in cash) when the market fell. This trading system is well-known in the US, what we will look at here is:
1. If the trading system can be profitably applied to the FTSE 100 Index.
2. Whether 10 months is the optimum parameter for the moving average (or would a 5-month, or 15-month, moving average produce superior results)?

Terminology: we will use SMATS(10) to refer to the 10-month simple moving average trading system. And SMATS(5) for the trading system using the 5-month simple moving average etc. Below we will analyse the trading system for 14 different parameters of the simple moving average, i.e. from SMATS(4) to SMATS(16).

Performance Analysis First, let’s look at the overall profitability of SMATS.

Proftiability The following chart plots the values of the SMATS portfolios for the 14 different simple moving averages (i.e. 4-month to 16-month). As a benchmark the FTSE 100 is added (i.e. this is the value of a buy and hold FTSE 100 portfolio). All values were re-based to start at 100.

SMA-Trading-Systems-4M-16M-1995-2016 Some observations:
1. By the end of the 20-year period all the SMATS portfolios had out-performed the FTSE 100 – except SMATS(5).
2. By the end of the period, SMATS(10) had the highest value; although it can be seen that it wasn’t consistently the most profitable throughout the whole period.
3. For the first six years (up to August 2001) all SMATS under-performed the FTSE 100. This was caused by the market volatility in 1998 and 2001, which caused the portfolios to be whipsawed in and out of the market. The following chart summarizes the final portfolio values in 2016 after running the trading system from 1995.

SMA-trading-system-values-2016 By 2016 the STATS(10) portfolio had the highest value of all portfolios at 269; the FTSE 100 buy and hold portfolio a value of 1999.

Risk We’ve looked at profitability, let’s now consider the risk incurred by each portfolio. We’ll use volatility as a (fairly standard) proxy for risk. The following chart shows the volatility of the portfolios over the 20-year period.

SMA-trading-system-volatility-1995-2016 Not surprisingly the FTSE 100 had the highest volatility. The volatility of the SMATS portfolios was less due to the fact they were in cash for part of the time; broadly their volatility increased as the moving average month parameter increased. The Sharpe Ratio combines returns with volatility to provide a comparative measure of profitability per unit of risk incurred. The ratio’s purpose is to answer questions of the form: is the profitability of a strategy justified by the risk incurred, compared to another strategy? The following chart plots the Sharpe Ratio for the 14 portfolios. (The benchmark for the Sharpe Ratio calculation was the FTSE 100 Index.) SMA-trading-system-Sharpe-Ratio SMATS(10) had the highest (i.e. the best) Sharpe Ratio, although close behind were SMATS(14) and SMATS(15).

Max Drawdown Maximum Drawdown decribes the maximum loss a portfolio suffered from a previous high value. For example, in this test SMATS(10) had a max drawdown value of 22.8%. This means that over the 20-year test period the portfolio was at most 22.8% under water (from a previous high). Frankly, max drawdown has more significance for strategies that employ leveraged products (e.g. futures), as drawdowns incur

realised losses as margins have to be paid. By contrast in the case of unleveraged equities or ETFs, drawdowns incur unrealised losses. Having said that, unrealised losses can still be uncomfortable and can have a major adverse psychological impact on the investor or trader. The following chart shows the max drawdown values for the 14 SMATS portfolios and the FTSE 100 Index. SMA-trading-system-Max-Drawdown Here the SMATS(10) portfolio only had a middling relative score. The best portfolios (i.e. those with the lowest max drawdowns) were: SMATS(7), SMATS(14), SMATS(15), and SMATS(16).

Trade Frequency The following chart shows the average number of trades for the year for each portfolio. For example, over the 20-year test period SMATS(10) portfolio traded 36 times, which is an average of 1.7 times a year.

SMA-trading-system-Average-Trades-yr As would be expected the number of trades decreases as the length of the moving average month parameter increases. In other words, systems get whipsawed less with longer moving averages. The profitability figures above did not include transaction costs, but with the systems averaging under 2 trades per year the transaction costs would not be significant.

Summary Of Analysis The following table summarises the above analysis. The values are colour-coded with green being the best value through to red being the worst for each respective analysis.

SMA-trading-system-analysis-FTSE-100-1995-2016

 Conclusion

  1. This simple moving average trading system did work for the FTSE 100 (i.e. it out-performed the FTSE 100 Index) over the 20-year period.
  2. The best performing portfolio was indeed SMATS(10), i.e. the trading using the 10-month simple moving average. It had the highest absolute profitability and also the highest Sharpe Ratio. After SMATS(10), the best portfolio was the SMATS(14), followed by SMATS(15). — By 

Almanacist from Stock Market Almanac

The post World’s Simplest Trading System appeared first on System Trader Success.

Understanding the Relationship Between Stocks & Bonds

$
0
0

Intermarket Analysis is the comparison of potentially related markets. For example:

  • S&P500 and 30 Year Treasury Bonds
  • 30 Year Treasury Bonds and Gold
  • S&P500 and Japanese Yen
  • Shanghai Composite Index and Aussie Dollar, etc.

The problem with using TradeStation for any Intermarket Analysis is the dreaded “You may not mix symbols with different delays in the same window” error code. That’s exactly what you’ll get if you try to add 30 Year Treasury Bond Futures (symbol US) to an Emini chart (symbol ES). The problem arises because the data comes from two different exchanges – CBOT for Bonds and CME for the Emini. TradeStation says:

Tradestation limitation TradeStation does not allow you to plot two symbols in the same chart window when the amount of delay for the data is different. For example, one is delayed and one is real-time, or both are delayed but the exchanges providing the symbols’ data delay by different amounts of time. Otherwise, during the market session, you would see last prices on the current bar that are asynchronous (i.e. not simultaneous).
There are various ways around the problem – most of them quite complex and involving exchanging data between charts. However, I have found an easier solution. Read on for some tricks of the trade and useful equities vs. bonds indicators.

Using ETFs for Intermarket Analysis

equities_vs_bonds

The solution to the problem is to find market symbols from the same exchange. With the explosion in the number of Exchange Traded Funds (ETFs) it is usually possible to find ones that track the underlying markets you are interested in.

For the Emini the obvious choice is the SPDR (symbol SPY) ETF traded on the AMEX exchange. For the Bond market the best choice is the iShares Lehman 20+ Year Treasury Bond ETF (symbol TLT), also traded on the AMEX exchange.

In the left panel of the chart above, daily data for the SPY and TLT symbols have been plotted quite happily on the same chart. However, in the right panel you get the dreaded “mix symbols” error code when plotting the ES and US symbols.

Are the Emini and Bond Markets Correlated?

The answer is sometimes yes and sometimes no. Correlation between the two markets can go as high as +60% (correlated) or a low as -60% (negatively correlated). You can add the in-built TradeStation correlation indicator on a chart of SPY and TLT to see this for yourself.

There are 2 opposing factors that drive the Bond and Stock markets at different times:

  • Interest rates might be falling and causing Bond prices to rise. The stock market might view the lower interest rates as encouraging for the economy and respond with higher stock prices. Alternatively, rising interest rates will cause Bond prices to fall and the stock market might view the tightening as negative for the economy and stock prices. In these cases correlation between the two markets is positive as they are moving in sync.
  • Stocks and Bonds are also alternative investment vehicles. If the stock market is rising strongly it might encourage Bond investors to cash out and put their money in the stock market and thereby cause Bond prices to fall. Alternatively, if there is a stock market panic investors might rush for the safety of Bonds and push Bond prices up. In these cases the two markets are negatively correlated as they are moving in opposite directions.

Measuring Differences Between the Emini and Bond Markets

SpreadELD

With SPY and TLT plotted on the same chart we can compare price movements. A popular oscillator is shown in the screen grab above. In this case a ratio of SPY and TLT is calculated and this value is compared to a moving average of the ratio.

I prefer to use another measure of relative price movement. The screen grab below shows TradeStation EasyLanguage code for my Bond Oscillator. Instead of using the ratio of SPY and TLT prices it calculates the difference in percentage movement. This indicator is more like a momentum indicator.

BondELD

The two indicators are compared below. The Bond Oscillator (momentum type) is shown above and the Spread Oscillator (moving average type) is shown below. As you can see, the Bond Oscillator generates more defined turning points and is easier to trade.

OscillatorsCompared

The chart below shows the Bond Oscillator added to a 3 year chart of daily SPY prices. Spikes (up and down) in the oscillator show periods when the SPY is over or under-valued against Bonds. These periods can persist for some time – more so on the upside than the downside. To illustrate this a PaintBar has been added to highlight periods when the Bond Oscillator is above +5 (shown as white bars) and below -5 (shown as red bars).

BondOscillator

Rather than use extreme readings on the Bond Oscillator to enter trades, it is safer to wait until the Oscillator crosses the zero line after an extreme reading. This prevents entering the trades too early.

Another trick I have found using this indicator is to wait for an extreme Oscillator reading and then look for a large daily move in the opposite direction in the Bond market. For example, Bonds are in a down trend, the Bond Oscillator goes above +5 and then Bonds have a one-day large up move. This pattern is signaling that professionals are taking profits at stock market highs and reaching for the safety of Bonds, hence driving Bond prices higher.

TradeStation EasyLanguage code for the PaintBar is shown in the screen grab below.

PaintbarELD

Bond Market Turning Points and the Emini

The last series of Bond Intermarket indicators are designed to highlight market turning points. I have found that there is a tendency for the Emini to lag the Bond market by approximately 20 days. To illustrate this point check out the chart below.

20DayDelay

The SPY (Emini equivalent) is shown in the top of the chart and below it is TLT (Bond market equivalent) with closing prices shifted by 20 days. The red vertical lines show how turning points in the two markets (one delayed by 20 days) often line up. The neat thing about this analysis is that the Bond market turning points are known well in advance.

As an aside, this 20 day delay is also the reason I use 20 days as the look back period in the previous two indicators, Spread Oscillator and Bond Oscillator.

The chart below shows the state of the current Bond market (mid April 2007). A vertical line has been added showing where prices were 20 days ago. As you can see, since then the Bond market has declined steeply. If the 20 day relationship holds we may well see another turning point in the stock market. Only time will tell.

VerticalLine

If you’re interested in following turning points in the Bond market you can use the indicator below to plot these vertical lines. The indicator allows multiple vertical lines of different frequencies to be plotted. Just vary the inputs NumLines (number of vertical lines) and Period (20 days, etc.). Make sure there’s enough back history in the chart to plot the lines though – if you ask for two 200 day lines and only have 300 days of history on the chart, the indicator won’t work!

VerticalELD

I hope this article on Intermarket Analysis and equities versus bonds was helpful to you. Download the indicator code used in this analysis from the link below.

Downloads

Bond Indicators (TradeStation ELD)

— Barry Taylor of Emini Watch

“I’m not a trading Guru and I haven’t discovered the Holy Grail. I’m just a regular guy who makes a living day trading Emini futures full-time. This website shows what works for me and is a record of how my trading methodology is evolving.” Read more at Emini Watch.

The post Understanding the Relationship Between Stocks & Bonds appeared first on System Trader Success.

The Power Of One, Two, Three!

$
0
0

An example of combining different classes of assets improves returns and reduces risk

Many people begin their trading endeavor by trading a single system. This is a great stepping stone to becoming a successful trader, but you can’t rely on a single system. Why? Trading systems naturally ebb and flow much like the market. Sometimes they are hot, other times they lose money for months while on a few occasions, they crash completely.

The goal is to build a portfolio of trading systems. By trading several different strategies you can experience profound impact on the trading performance.

My three intermarket systems have been very popular, with the two index systems being the most popular. Most of the customers who own the S&P Intermarket System also own the Nasdaq Intermarket System, and that's great. The problem is many of them are not trading my bond system which costs them performance and increases risk.

Let’s take a closer look at combining several strategies resulting in missing out on the uncorrelated returns of the bond system. It's called, U.S. Bond Intermarket System​.

Most traders have not seen studies of testing multiple systems because it’s not easy to combine results in TradeStation. It can be done with Portfolio Maestro but that's not easy to use and the money management options you have are limited. Because of these reasons, we will use TradersStudio-for-TradeStation.

TradersStudio-for-TradeStation uses TradeStation data and is currently offline so it can give you orders for tomorrow on daily systems you can manually enter. It can also do intra-day backtesting and if you use longer bars (90 minutes) you can update data, generate orders, and kludge intra-day trading. A true real-time version will be available later this spring. TradersStudio for TradeStation uses an EasyLanguage-friendly language and also has a migrations tool to move your EasyLanguage over without having to reprogram your strategies. I think this software will provide a real benefit to TradeStation users by providing true portfolio level backtesting. But I digress…

The Holiday Issues

In reading this article you may discover issues about TradeStation that are disconcerting. For example, how TradeStation handles holidays. If a day ends 1:00 pm EST or earlier it seems that TradeStation just throws that data way at least in the stock indexes. This creates problems since when you export the data, even back to TradeStation as third-party data, these holiday-shorten days will not be included, and really they should be because that price action should affect indicators and moving average skipping them is wrong.

This holiday problem is ​an issue on why results between TradeStation and TradersStudio-for-TradeStation do not match. Another one is if a market order to buy and sell short occur on the same bar in a system TradeStation handles it poorly. TradeStation generates both orders, it gives a reverse first and then a new signal in the original direction. TradersStudio will either reverse on these type of orders or stay in the original direction, which gives you the same results as TradeStation without the bogus trade.

Now that we have introduced the tool and the issues, let’s look at trading two different sets of systems. First we'll look at the S&P Intermarket System alone. Then we'll add the Nasdaq Intermarket System thus, trading both strategies together. Finally, we'll add the U.S. Bond Intermarket  System to trade all three.

S&P Intermarket System

We will start by Trading a 1 contract with the S&P Intermarket System from 4/11/2007 to 3/14/2018. We will also use $37.50 slippage and commission round trip. Let’s look at the S&P Intermarket System by itself in TradersStudio-for-TradeStation (see note above on trade differences).

Nasdaq Intermarket System

Let’s now look at the Nasdaq Intermarket System. This system has different results in TradersStudio because both 4th of July holiday in 2009 and Good Friday 2013 create issues since major trades were affected around those periods.

S&P & Nasdaq Intermarket System

Now let’s look at what happens if we trade a one lot of each.

We make the money on both systems, which is good. However, we also take on the drawdown of both systems. Trading them together does nothing extra for us.

S&P & Nasdaq Intermarket System

Let’s now look at my U.S. Bond Intermarket System again from 4/11/2007 to 3/13/2018 with $37.50 deducted for slippage and commission.

Trade All Three

Now let’s see what happens when we combine the three. I think you'll see some "magic".

If we trade just the two index systems our maximum drawdown is $29,172. Trading all three our drawdown is $24,185. This is a reduction of 18% while increasing profit to 67%. It's clear that combining non-correlated strategies is one of the important keys to long-term success as a trader.

Dynamic ATR Allocation

Let’s now look at using a Dynamic ATR allocation that uses the so-called Dynamic Margin. We make a calculation of the 40-day true range (in dollars) and then we multiply it by ​7 and call that Dynamic Margin. We size positions based upon this value. For example, let's say the average 40-day true range for bonds was $1,000. We would call it Dynamic Margin $7,000. If we say we will trade at 40% of dynamic margin we would trade 1 contract for each $17,500 in the account. Let’s use this logic and start trading by 1/1/2010, and see what happens starting with a 50,000 account and a 30% dynamic margin.

We will see that our $50K becomes over 1.8 million dollars, but dollars are not how professional trades look at things. Let’s take a quick look at some other measures. Our compound annual growth rate is over 57%, maximum drawdown around 33%, the Sharpe ratio is over 1.8, and MAR is 1.73. We also have 74% winning months by combining these

Conclusion

In closing, we can see that combining certain strategies can work wonders for the performance of a trading portfolio. Adding a position sizing method is the next step. There is no holy grail when it comes to trading but, building portfolios and applying a position sizing method to that portfolio get pretty close. 

You can learn more about the U.S. Bond System by clicking the button below.

Downloads

Download the performance reports (excel format) used in this article.

The post The Power Of One, Two, Three! appeared first on System Trader Success.

The Journey

$
0
0

“The journey, Not the destination matters...” ― T.S. Eliot

You might be wondering what the Nobel Prize winning poet, T.S. Eliot has to do with trading. No, he did not leave a secret trading manual in his attic for his grandchildren to stumble upon. And I’m guessing he did not even trade – he was too busy creating immortal prose.

Yet, his quote, “The journey, Not the destination matters...” has profound implications for us as traders. Let me explain…

What if I told you of a Soybean Oil strategy that earned nearly $40,000 in single contract profits in five years? That is $8,000 profit per contract each year. Would you want to trade it?

Right now, margin on Soybean Oil is $660, so you might determine you could trade 1 contract of this strategy with $2,500. So, in five years, your $2,500 would turn into $42,500, which is a compounded annual growth rate of over 76%. Per year!

At first blush, who would not want that?  

The problem is that it's where most traders stop their analysis. They see the start point, and they see the end point five years later, with bags of cash awaiting them. They jump for joy at their performance, and rush to trade the strategy live.

Of course, our friend T.S. Eliot would disagree. He would argue that the journey during those five years, not just the end point, is what really matters.

So what does that journey look like? Here it is:

The end profit is there, sure enough. But look at what we had to endure to get there! A maximum drawdown of $9,000, numerous quick and steep equity collapses, extended flat periods – UGH!

The final profit says this is a nice strategy, but the path to get there is brutal. In other words, the journey is really important. Unfortunately, too many traders ignore that.

Psychologically, this strategy would be practically impossible to trade. Pretend you are trading this strategy, and just imagine yourself at the following point on the equity curve:

What would you be thinking? Most people probably would have quit even before this point, but how much confidence would you have right now? Realistically, you’d have zero confidence that this strategy would ever turn around. Yet, from that point on, that is exactly what the strategy did – its performance took off from that point.

Hopefully, this simple example makes it clear that the path of an equity curve is critical. You can’t enjoy the riches at the end if you cannot stomach the road to get there.

So, how can you take this into account with your own trading? Here are a few simple tips:

  1. When reviewing a Performance Report, make sure you look at more than just the Net Profit. Make sure you look at the max drawdown and any drawdown curves – could you handle the drawdowns? My rule of thumb is that I can mentally handle about half the maximum drawdown that I think I can handle. So, if I think I can handle a $10,000 drawdown, and the system has an $8,000 maximum drawdown, chances are I won’t be able to endure it. In that case, I probably should not trade such a strategy.
  2. You can employ my free Monte Carlo simulator for Excel (see below) to determine the drawdown, profit/drawdown and other statistics for any strategy. This is a simple, but powerful way to see if the risk adjusted return is appropriate for you. I throw away many great profit strategies because the drawdowns are just too severe, and the risk adjusted return is just too low.
  3. Take the equity curve, print it on a piece of paper, then get another piece of paper and cover it up. Slowly reveal the developing equity curve, moving left to right, and imagine yourself at each point along the curve. Try to experience what you would feel at each point. This is hard to do, especially when you know the positive end result, but if you do it correctly, it can be very enlightening.

To wrap up, always remember that the end result of a trading strategy is usually not the most important part. The path matters – a lot.

-- By Kevin Davey of KJ Trading Systems

The post The Journey appeared first on System Trader Success.


A Better Regime Filter To Boost Returns

$
0
0

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

The post A Better Regime Filter To Boost Returns appeared first on System Trader Success.

Three Trading “Truths” Quantified

$
0
0

I want to discuss three trading “truths” that I often hear but when I finally got into testing ideas found them to be myths. These discoveries were instrumental in turning my trading around.

For those that know my story, it was not all roses and rainbows – what trading story is?!? I actually “learned” about a lot of traders from online sources, chat rooms, webinars, and eventually found the right circles to roam in after a LOT of trial and error. I was then lucky enough to land a job with a high frequency trading firm. I was quickly made to realize that much of what I thought trading “was” was most certainly false.

In an attempt to show me the light, a few of the quick trading axioms they wanted to disprove to me were simple “well known” trading ideas that have been around for years but were in fact large falsehoods. I quickly realized beyond this list of three examples that there must have been many, many more “trading truths” that were causing harm to my account and doing my trading aspirations a disservice.

I then realized the value in testing everything and quantifying my entire approach. It wasn’t until this point in my journey did I get out of the “rat race” of trading… the ups and downs, the barely consistent, always doing slightly better but not really getting anywhere trading most of the traders I meet today are going through.

I cannot stress the importance of testing everything and quantifying your edge. Investigate these trading axioms. Otherwise you will be stuck in randomness until your account walks to 0. For more on my journey check out this podcast I did, chatwithtraders.com/103. Below you will find my three favorite trading “truths” quantified.

Trading “Truth” #1 - Bearish Engulfing Candle

This one is great because many are familiar with Japanese candle stick patterns and the name implies such a negative move in price that one cannot help but to shift their bias to the downside. These candlestick patterns are often traders' first introduction to technical analysis.

The pattern is defined as a bearish candle that “engulfs” the range of the previous day. I also like to look for a negative close and preferably a close below the previous session’s low. Here are a few pictures of bearish engulfing candles.

The truth is that this pattern has been one of the most bullish (not bearish) 1-day signals for the SP500 over the past 15+ years. Did you know that the day following a bearish engulfing candle actually closes higher than 61.72% of the time in the SP500 futures and 65.33% of the time in SPY ETF? The day following a bullish engulfing candle only closes higher than 54.05% of the time in the SP500 futures and 51.70% of the time in SPY. You tell me why they’re named how they are!


Trading Truth #2 – Above a moving average is bullish and below is bearish

Most of the time this is true but it depends on the moving average, moving average length, and the market. I recently came across a few blogs that mentioned using a short term moving average as a sign to exit long market exposure and wait for sunnier days. In reality, this sounds great; however, analyzing the data this can be an extremely misleading “truth”.

Below is a chart plotting the equity curve if you would buy every close when the SP500 is BELOW the 8-period simple moving average (8SMA) and sell the next bar (repeating until above 8SMA). The second chart is if you were to buy every close when the SP500 is ABOVE the 8SMA and exit the next bar (repeating until below 8SMA). Yes, being below this moving average is actually better for long returns.

trading truths

Of course this is not true for all markets and moving averages, as mentioned. I pointed this out in another post on SeeItMarket where I dissected popular stocks and different moving average lengths here: https://www.seeitmarket.com/testing-moving-averages-popular-stocks-etfs-16809.

The point is that these trading truths like “above a moving average is bullish” and “below a moving average is bearish” need to be quantified and tested. It is important to stop thinking trading truths can be generalized to every market, timeframe, indicator value, etc. and just verify them yourself and you’ll be much better off!

Trading Truth #3 – Overnight Exposure is Risky

Sure earnings announcements and large unexpected news announcements typically happen after market close. Does this mean we should avoid trading overnight, if possible? So many want to day trade and be flat on the close that they miss a lot of gains from the overnight session (sometimes all of them).

Below you will see 30 top stocks where I breakdown their returns in the day session compared to the overnight session. The blue line signifies if you bought the open and sold the close the same day (day session), and the orange line signifies buying the close and selling on the next day’s open (simulating overnight exposure). As expected, there are no generalities in trading truths. Some stocks exhibit that most, if not all, returns come from the overnight.

In conclusion

Not all trading truths are “truths”. There are many that still have value! The edge is not in these truths but in determining the difference between a truth and a “truth”. Most do not take the effort to investigate these trading axioms found in trading books, blog sites, chat rooms, etc. If I have one goal then it is to make traders realize the value in testing everything – it is something I wish I would have started earlier. It is a super power to quickly test these ideas and trade/act accordingly!

I think many traders shy away from digging into the data because it requires effort and they think it will be a hard and arduous journey before they find some gold. But now I think it is increasingly easier than many may think.

That’s why Build Alpha’s main goal was (and still is) to make this type of testing easier for those with no programming skills or those tired of crunching endlessly in excel. The game is changing and things like this can be easily tested now. Today, trading just comes down to those who will put in the work and who won’t: this should greatly increase your odds for success if you’re part of the former group.

--By David Bergstrom from blog Buildalpha

The post Three Trading “Truths” Quantified appeared first on System Trader Success.

Five Stock Market Timing Indicators Put To The Test

$
0
0

Humans have been trying to clock in the stock market with fancy indicators since the beginning of time. But do they work? In this article I test five different market timing indicators. They are:

  • Coppock Curve
  • Zweig Breadth Thrust
  • Arms Index (TRIN)
  • McClellan Oscillator
  • No. Of New 52-Week Lows

These market indicators are all available with my historical database from Norgate Data.

1) Coppock Curve Indicator

The first indicator we will test is the Coppock Curve.

The Coppock Curve first appeared in a Barron’s article in 1962 and was invented by economist Edwin Coppock.

The indicator takes a weighted moving average of the rate-of-change and is designed to spot long term trend changes in market indexes.

According to Investopedia, you should buy when the Coppock Curve moves above zero and sell when the indicator moves below zero.

Five Stock Market Timing Indicators Put To The Test

Coppock Curve indicator plotted in Amibroker with SPY.

Coppock Curve Strategy

  • Buy the S&P 500 SPY ETF when the Coppock Curve moves above zero.
  • Sell when the Coppock Curve moves below zero.

Testing this strategy between 1/1994 – 1/2017 resulted in an annualized return of 9.90% with a maximum drawdown of -19%. There were four trades in total and each one was a winner.

This compares to a buy and hold return between 1/1994 – 1/2017 of 9.09% with a max drawdown of -55%.

For an indicator that was developed in 1962 this is not such a bad result. The performance is better than buy and hold on a risk-adjusted basis.

Below you can see the equity curve taken from Amibroker with a $25,000 starting capital:

2) Zweig Breadth Thrust

Developed by Marty Zweig, the Breadth Thrust indicator takes the number of advancing issues in an index divided by the total number of issues (advancing and declining). A 10-period exponential moving average is then laid on top.

According to most sources, you should buy when the indicator moves from a level of under 40% to a level above 61.5% within a 10-day period.

This is noted as a rare sentiment shift and usually comes at the beginning of a new bull market.

Zweig Breadth Thrust in Amibroker with SPY.

Zweig Breadth Thrust Strategy

  • Buy SPY when Zweig Breadth Thrust moves from below 40% to above 61.5% within a 10-day period.
  • Sell after 20 days.

I tested this strategy between 1/1994 and 1/2017 and got an annualized return of 1.48% with a maximum drawdown of -14% and a win rate of 65% across 26 trades.

Below you can see the equity curve as taken from Amibroker:

3) Arms Index (TRIN)

The Arms Index was developed by Richard W. Arms in 1967 and is also referred to as the TRIN. This is another market breadth indicator. It’s calculated by dividing the advance-decline ratio by the advance-decline-volume ratio.

There are a number of interpretations on how to use TRIN and some suggest it is most useful for day traders.

According to this article, you should go long when the 10-day moving average of TRIN moves below 0.8 and sell when it moves above 1.2.

Arms Index (TRIN) example in Amibroker with SPY

Arms Index (TRIN) Strategy

I tested buying SPY according to the above definition between 1/1994 – 1/2017 and recorded an annualized return of 3.52% with a maximum drawdown of -22% and a win rate of 65% from 20 trades.

Following is the equity curve taken from Amibroker. You can see that this is a rare signal in recent times so the settings may need to be altered:

4) McClellan Oscillator

The McClellan Oscillator is another market breadth indicator. This one is based on the smoothed difference between the number of advancing and declining securities on the NYSE or some other market index.

Ratio Adjusted Net Advances (RANA) = (Advances – Declines) / (Advances + Declines)

McClellan Oscillator = 19-day EMA of RANA –  39-day EMA of RANA

Looking online, I found it difficult to find any consistent definition on how this oscillator should be used.

According to one article, you should be bullish when the McClellan Oscillator moves above zero and bearish when it moves below zero.

I tested this on the SPY ETF and the results were poor. I also tried a number of other variations which also showed net losses. The best result came from a strategy taken from Futures Mag.

McClellan Oscillator in Amibroker with SPY.

McClellan Oscillator Strategy

  • Buy SPY when the McClellan Oscillator moves to between -70 and -100, then turns up.
  • Sell SPY when the McClellan Oscillator moves to between 70 and 100, then turns down.

In other words, we are looking for the indicator to move down into an oversold range before turning back upwards.

This strategy generated an annual return of 9.61% with a maximum drawdown of –24% and a win rate of 76% over 45 trades between 1/1994 and 1/2017.

This compares to a buy and hold return between 1/1994 – 1/2017 of 9.09% with a max drawdown of -55%.

This indicator has some interesting characteristics and it is always nice to see a win rate above 70%. You can see the equity curve below:

5) Number Of New 52-Week Lows

The final stock market indicator we will look at today is the number of stocks making new 52-week lows in comparison to the index itself.

This is a classic indicator that can be used to measure strength in the prevailing trend and is also useful when looking for divergence.

You can see that in the chart below the number of stocks hitting new 52-week lows hit a peak of over 400 (out of 500) in 2008.

New 52-week low divergence example in Amibroker with SPY.

New 52-Week Lows Divergence Strategy

  • Buy SPY when it closes at a new 20-day low but the number of stocks making new 52-week lows goes down.
  • Sell five days later.

This strategy is based on divergence. The index has hit a new low but the stocks that make up the index have not made new 52-week lows. This suggest the downward trend is weakening and an upturn could be on the cards.

This strategy produced an annualized return of 3.74% between 1/1994 and 1/2017 with a maximum drawdown of -14% and a win rate of 62% over 100 trades.

Below you will find the equity curve produced in Amibroker:

Conclusions

There are countless numbers of different indicators on the market but few are able to generate profits superior to buy and hold. We have looked at five indicators here and the results are mixed.

The Coppock Curve Indicator, McClellan Oscillator, and Number of New 52-Week Lows Divergence strategy look fairly interesting and they might be useful for day traders or as market timing filters.

For example, traders could use these indicators to only take trades when certain conditions line up. These strategies might also be enhanced with extra leverage or adapted for futures.

As usual, the data proves there is no easy money available in the stock market despite what is claimed by the inventors and promoters of simple market indicators.

--by Joe Marwood from blog Jbmarwood.com

The post Five Stock Market Timing Indicators Put To The Test appeared first on System Trader Success.

A Strategy For Each Day of the Week [Seriously?]

$
0
0

A different strategy for each day of the week? Sounds crazy, but is it?

I have written about “Turnaround Tuesday” before.

This simple strategy is actually at new highs since this was published over 10 months ago!

But what about other markets? Is it possible to just trade one market per day of the week (from open to next day’s open) on a specific day of the week and still do well? If you would have followed this simple “portfolio” below for the past 15+ years then yes... you would have. You wouldn’t even have to sit in front of the screens like the rest of us degenerates.

Strategy 1: Short Crude Oil on Mondays

Simple strategy dating back to 2003. Short Oil on Monday’s open and cover on Tuesday’s open. Results based on a 1 lot.

A Strategy For Each Day of the Week [Seriously?]

Strategy 2: Turn Around Tuesday

If Monday was a down day (Monday’s close less than or equal to Monday’s open) then buy Tuesday’s open and sell on Wednesday’s open. Results based on 1 lot.

Strategy 3: Long Gold on Friday's. Weekend Risk.

Maybe in lieu or anticipation of bad weekend news releases, buying Gold on Friday’s open and holding over the weekend to exit on Monday’s open has produced the following based on 1 lot.

Not a bad portfolio equity curve, right?! One of the hidden ‘holy grails’ in trading is combining systems together to smooth the equity growth of the account. No single super star out of any of these three strategies but combined their curve starts to look rather nice.

Sure these might not be alpha generators on their own but they may be combined with some other price patterns, filters, or targets and stops to become full strategies. They can certainly act as intermarket or multi-time frame filters for more complicated strategies.

For example, if you have a 60-minute mean reverting system that buys oil dips then maybe it should be turned OFF on Mondays! At the very least it is worth a look and this is all made very simple with Build Alpha – just point, click, test.

For example, did you know S&P500 has performed much better on even days than odd days? (April 6 is an even day).

Anyway, I just wanted to show some simple things that can be tested in Build Alpha and how sometimes the most simple ideas turn out to work the longest. Maybe because people think they’re too simple and that they can’t work? I don’t know.

Either way I have put some python code (and TradeStation code) in the private Build Alpha users’ forum to specify day of the week as I know a lot of you are trying to learn python so I figured I’d help out a bit. But day of week is all point and click options pre-built into Build Alpha’s signal library for those of you who could care less about learning to code. Happy Friday!

--by David Bergstrom from blog Buildalpha.com

The post A Strategy For Each Day of the Week [Seriously?] appeared first on System Trader Success.

Market Seasonality Study

$
0
0

With April  over I thought it would be a good idea to review our Market Seasonality Study. 

If you will recall, back on November 2nd of last year, we opened a seasonality trade in anticipation for a traditional strong period of the stock index markets. That is, the months of November, December, January, February, March and April. So what did the market do during those months?

Below is the image of the price chart were we entered back in November and where we re-exited at the open of May 3rd when price fell below our simple moving average.

Another winning trade.

We are now entering a traditionally weak season for the stock index market. This is a well known seasonality period. In this article I would like to take a closer look at the seasonality bias which so many investors and traders talk about. 

Seasonality Bias

First, I would like to test the popular trading idea of buying the S&P in November and selling in May. I will test this on the cash market going back to 1983. The number of shares to buy will be adjusted based upon a fixed amount of risk. In this case, $5,000 is risked per trade based upon the volatility of the market. As this is a simple market study no slippage or commissions were taken into account. The EasyLanguage code looks like this:

CurrentMonth = Month( Date );
 
If ( CurrentMonth = BuyMonth ) And ( MP = 0 ) Then Buy("Buy Month") iShares contracts next bar at market;
 
If ( CurrentMonth = SellMonth ) Then Sell("Sell Month") iShares contracts next bar at market;

Testing Environment

I decided to test the strategy on the S&P cash index going back to 1960. The following assumptions were made:

* Starting account size of  $100,000.
* Dates tested are from 1960 through May 2017.
* The number of shares traded will be based on volatility estimation and risking no more than $5,000 per trade.
* Volatility is estimated with a two times 20-week ATR calculation. This is done to normalize the amount of risk per trade.
* The P&L is not accumulated to the starting equity.
* There are no deductions for commissions and slippage.
* No stops were used.

From here we can plug into the input values the buy month (November) and sell month (May). Doing this we generate the following equity graph:  

It sure looks like these months have a long bias as those are some nice results. What would the equity curve look like if we reverse the BuyMonth and SellMonth? That is, let's buy in May and sell in November. Below is the equity curve for this inverted system.

The early years of 1960 to about 1970 the equity curve went lower and lower. Then it started climbing reaching an equity peak of 1987. During this period, the strategy was producing positive results. That equity peak occurred during 1987 should be familiar. That was the year we had the massive one day market crash on October 19th known as Black Monday. That's when Dow Jones Industrial Average dropped 22% in one day!

 Since that event the behavior of market participants has been altered. This is not unlike the radical market changes which occurred after the 2000 market peek where much of the trending characteristics of the major markets were replaced by mean reversion tendencies. So far the basic seasonality study looks interesting. However, keep in mind that we do not have any stops in place. 

Nor do we have any entry filter that would prevent us from opening a trade during a bear market. If the market is falling strongly when our BuyMonth rolls around we may not wish to purchase right away.

Likewise, we have no exit filter to prevent us from exiting when the market may be on a strong rise during the month of May. It's conceivable that the market may be experiencing a strong bull run when our usual SellMonth of May rolls around.

Simple Moving Average Filter

In order to avoid buying and selling at the wrong times I'm going to introduce a 30-period simple moving average (SMA) to act as a short-term trend filter. This filter will be used to prevent us from immediately buying into a falling market or selling into a rising market. For example, if our SellMonth of May rolls around and the market happens to be rising (trading above the 30-period SMA), we do not sell just yet. We wait until unit price closes below the short-term SMA. The same idea is applied to the buying side, but reversed. We will not go long until price closed above the short-term SMA. Within EasyLanguage we can create a buy/sell confirmation flag called BuyFlag and SellFlag which will indicate when the proper go-long or sell conditions appear based upon our short-term trend filter.

if ( MinorTrendLen > 0 ) Then BuyFlag = Close > Average( Close,  MinorTrendLen )
Else BuyFlag = true;
If ( MinorTrendLen > 0 ) Then SellFlag = Close < Average( Close, MinorTrendLen )
Else SellFlag = true;

The MinorTrendLen variable is actually an input value which holds the look-back period to be used in the SMA calculation. You will notice there is an additional check to see if the look-back period is zero. This is done so we can enable or disable this SMA filter. If you enter zero for the look-back period, the code will always set our BuyFlag and SellFlag to true. This effectively disables our short-term market filter. This is a handy way to enable and disable filters from the system inputs. Below is the performance of both our Baseline system and the system with our SMA filter:

We increased the net profit, profit factor, average profit per trade, annual rate of return, and the expectancy score. The max intraday drawdown fell as well. Overall it looks like the SMA filter adds value.

MACD Filter

A standard MACD filter is a well known indicator that may help with timing. I'm going to add a MACD calculation, using the default settings, and only open a new trade when the MACD line is above zero. Likewise, I'm only going to sell when the MACD line is below zero.  Within EasyLanguage we can create a MACD filter  by creating two Boolean flags called MACDBull and MACDBear which will indicate when the proper major market trend is in our favor.

If ( MACD_Filter ) Then
Begin
MyMACD = MACD( Close, FastLength, SlowLength );
MACDAvg = XAverage( MyMACD, MACDLength );
MACDDiff = MyMACD - MACDAvg;
If ( MyMACD crosses over 0 ) Then
Begin
MACDBull = True;
MACDBear = False;
End
Else If ( MyMACD crosses under 0 ) Then
Begin
MACDBull = False;
MACDBear = True;
End;
End
Else Begin
MACDBull = True;
MACDBear = True;
End;

Below are the results with the MACD filter:

Utilizing the MACD filter and comparing it to our baseline system, we reduced every so slightly many of the performance metrics. Overall, it does not appear to be better than our SMA filter.

RSI Filter

For our final filter I will try the RSI indicator with its default loopback period of 14. Again, like the MACD calculation, I want price moving in our direction so I want the RSI calculation to be above zero when opening a position and below zero when closing a position.

If ( RSI_Filter ) Then
Begin
   RSIBull = RSI(Close, 14 ) > 50;
   RSIBear = RSI(Close, 14 ) < 50;
End
Else Begin
   RSIBull = true;
   RSIBear = true;
End;

The RSI filter performed better than the MACD filter. Comparing it to the Baseline, we see it's very similar. With the RSI filter the net profit, profit factor and RINA Index are all slightly lower.

In the end it does appear applying a SMA filter or an RSI filter can improve the baseline results. Both filters are rather simple to implement and were tested for this article with their default values. Of course, you could take this simple study much further.

Apply SMA Filter on Weak Seasonality Period?

After performing the different filter tests and choosing the simple moving average filter, I started wondering what it would look like if we applied to the weak seasonality period. Below are the before-and-after equity curves.

Without the simple moving average filter

With the simple moving average filter

It appears the simple moving average filter helps a lot. While we can still see the weak seasonality period equity curve is not nearly as attractive as the strong seasonality period, it did improve to somewhat decent. 


Conclusion

It certainly appears there is a significant seasonal edge to the S&P market. The very trading rules we used above for the S&P cash market could be applied to the SPY and DIA ETF markets. I've tested those ETFs and they produce very similar results. The S&P futures market also produces similar results. It even appears to work well on some stocks.

Keep in mind this market study did not utilize any market stops. How can this study be used? With a little work an automated trading system could be built from this study. Another use would be to apply this study as a filter for trading other systems.

This seasonality filter could be applied to both automated trading systems or even discretionary trading. It may not be much help for intraday trading, but it may be worth testing. Anyway, just being aware of these major market cycles can be helpful in understanding what's going on with today's markets and where they may be going in the near future.

Hope you found this study helpful. This seasonality filter (30-period SMA) is what's used on our State of U.S. Markets webpage.

Downloads

The post Market Seasonality Study appeared first on System Trader Success.

Viewing all 323 articles
Browse latest View live