Thursday, January 25, 2018

BackTest on Displaced Moving Average (DMA): Simple is Good!

Displaced Moving Average, is perhaps one of the most simple technical indexes that I have ever tested, but it is one of the most stable technical indexes that I have ever seen among different Futures Contracts.

I tested it against all the contracts listed in China Futures Market, and it turned out that most of them suit pretty well. In daily basis, DMA is strong enough to capture big trends in price movements.

Let's look at the definition and formula of it:

Components:
  • MA(t,12) = Simple Moving Average for close price in 12 days
  • MA(t,26) = Simple Moving Average for close price in 26 days
  • DMA(t) = MA(t,12) - MA(t,26)
  • AMA(t,9) = Simple Moving Average for DMA in 9 days

Strategy:
  • Long on the spot that DMA surpasses AMA
    • (DMA(t) > AMA(t) and DMA(t-1) <= AMA(t-1))
  • Short on the spot that DMA surpassed by AMA
    • (DMA(t) < AMA(t) and DMA(t-1) >= AMA(t-1))

Even though, the results of DMA is vulnerable to different Futures Contract, but the truth is, when we combine them together, then the outcome is beautiful.

* Click this link to check out the performance of each individual Futures Contract:
https://drive.google.com/open?id=19DnrN0YQlJkcelnBzm4M6YAoE345p-4F

Profits & Loss of the entire Market:


The Sharpe of it, is 1.33, which is already very good as daily trend capturing strategies are not that stable, and this Sharpe suggests the stability of the entire strategy.

Note that cash, accounts, and trading volumes have not been adjusted for different kinds of Futures Contracts, and we assume that the maximum holding positions for all of them are 3 volume, and therefore the profit or loss from each individual contracts may be different.

But generally speaking, the results are stable even for the fact that individual risk has not been eliminated, as we can simply deduct the most profitable and least profitable contracts as follow:


We can observe that even though the absolute value of profits have been changed, the shape of it is stable. This partly suggest that our belief that DMA is stable in different contracts is reasonable.

Considering the fact that how simple DMA is, many of us assume that such index is no longer effective, and it is debatable whether the market is efficient and technical analysis is useless.

So, it can be possible the entire performance is out of luck. Therefore, be careful when investing with technical analysis.

* Source Code and Raw Data are not applicable.

Wednesday, January 24, 2018

On Sharpe Ratio: The Higher, The Better?

Sharpe Ratio is perhaps one of the most famous and powerful ways to evaluate the performance of a portfolio.

$Sharpe\ Ratio = \frac{Risk\ Premium}{SD\ of\ excess\ return}$

In most cases, Sharpe Ratio is used as a quick way to reflect the reward to volatility of a portfolio:

The higher Sharpe Ratio is, the more risk premium we assume that is coming from a given "volatility".

For example, some big trading companies may categorize funds with Sharpe more than 2 as spectacular, more than 1.5 as excellent, more than 1.25 as good, more than 1 as average, less than 1 as inferior...

HOWEVER, given different time horizons of a portfolio, while others remain constant, Sharpe can be completely different, and evaluation based merely on Sharpe can be misleading.

To understand this, let's first dive into the components of Sharpe Ratio:

I. Risk Premium

To begin with, assume we have all the data of monthly return of Baidu. We fear that there may be some scandals tomorrow and influence its cash flow in the future, and in the meanwhile we also hope a new version of auto-mobile car invented in the next month.

To bear this kind of risk, a risk-averse investor (we assume all the investors are risk-averse) would then expect a higher return in the future.

But how to estimate excess return? The most widely-used way is to use the arithmetic average return minus risk-free rate as the estimation of risk premium.

$\widehat{E(r)}=\frac{1}{n}\sum_{i=1}^{n} r_i$

Under the assumption of normal return distribution, the above estimation is unbiased.

Expected Return minus Risk-free Rate, and we can get our unbiased estimation of Risk Premium.

II. Volatility: Standard Deviation of Excess Return

A generally accepted valuation of expected volatility is standard deviation $\sigma $.

Some claim that we care only about the downward risk. However, Bodie argued that as long as the probability distribution is more or less symmetric about the mean, $\sigma $ is a reasonable measure of risk.

$\widehat{E(\sigma ^2)}=\frac{1}{n-1}\sum_{i=1}^{n} (r_i-\bar{r})^2$

Under normal assumption, such estimation of standard deviation is unbiased as the degrees of freedom bias is eliminated.

III. Time Horizons: a variable greatly easy to be ignored

Now, we already have the estimations of Risk Premium as well as Estimated Volatility, and simply divide them, we can derive Sharpe Ratio.

What seems to be the problem?

Given monthly average excess return r, and monthly standard deviation $\sigma$, assume that returns among each month is i.i.d., and annually estimated excess return is $12r$, while annually estimated standard deviation is $\sqrt{12}\sigma$

Therefore, now the annual Sharpe Ratio is $\sqrt{12}\frac{r}{\sigma}$, while the monthly Sharpe Ratio is $\frac{r}{\sigma}$.

This indicates that a same portfolio can be measured with drastically different Sharpe Ratio!

For example, if the previous annual Sharpe Ratio is 1.50, labeled as excellent previously, would soon become 0.43, which is inferior in a monthly basis.

However, in practice, we merely mention that "My Sharpe is 2 in an annual basis", but "The Sharpe of my strategy is 2".

We simply ignore one factor that may change the entire story.


Monday, January 22, 2018

BackTest on MACD, KDJ, and RSI

MACD, KDJ, and RSI are three powerful technical indices. These indices are widely used to reflect trend, especially reversal trend.

Simply speaking, when one of these indices is triggered, then:

  • An upward trend may reverse to a downward trend, OR,
  • A downward trend may reverse to an upward trend


The performance of those indices are more or less affected by the extraneous parameters (like the x in "highest price in x days"), but here we assume all of these parameters set to be generally accepted parameters.

To specify, here we assume that:

MACD:

Estimation Formula:
  • EMAS(t) = Exponential Moving Average of Price in Short Term (daily close price in 12 days)
  • EMAL(t) = Exponential Moving Average of Price in Long Term (daily close price 26 days)
  • DIF(t) = EMAS(t) - EMAL(t)
  • DEA(t) = Exponential Moving Average of DIF (in 9 days)
  • MACD(t) = [DIF(t) - DEA(t)] * 2
Strategy:
  • Long when MACD is negative and increasing
  • Short when MACD is positive and decreasing

KDJ:

Estimation Formula:
  • Low(t,9) = Lowest price in 9 days (date t-9 to t)
  • High(t,9) = Highest price in 9 days (date t-9 to t)
  • RSV(t) = (Close(t) - Low(t,9)) / (High(t,9) - Low(t,9))
  • K(t) = RSV(t)/3 + 2*K(t-1)/3
  • D(t) = K(t)/3 + 2*D(t-1)/3
  • J(t) = 3*K(t) - 2*D(t)

Strategy:
  • Long when J is <= 25 and increasing
  • Short when J is >= 75 and decreasing

RSI:

Estimation Formula:

  • MEANUP(t,12) = Mean of positive returns in the last 12 days
  • MEANDOWN(t,12) = Absolute value of the Mean of negative returns in the last 12 days
  • RS(t) = MEANUP(t,12)/MEANDOWN(t,12)
  • RSI(t) = 100 - 100 / [ 1+ RS(t) ]

Strategy:
  • Long when RSI is <= 40 and increasing
  • Short when RSI is >= 60 and decreasing

Backtest Results:

Ag: Silver/ Agrentum Futures, listed on Shanghai Futures Exchange, China

Profits & Loss:

MACD:

KDJ: 

RSI:

However, there is one BIG problem.

All of these indices, are highly sensitive to different underlying assets. Those performance that is beautiful in Ag, might be pretty bad in some others.

In fact, I have also tested all the other active 34 Futures Contracts listed in China (see in *1), and none of them performs similarly to Ag. Some of the three strategies are valid for some of them, while others may not:

It is possible that good results come from pure luck, not the effectiveness of strategy itself.

Therefore, single index should never be considered the sole best strategy. Like Alpha seeking, a better strategy may be effective when more financial instruments are taken into account.

By the way, one another thing may help: decrease the cycle of investments:

For example, in these examples (MACD/KDJ/RSI), all prices are updated upon daily basis. However, investing in such a long term is more like a fundamental analysis, which is basically too risky to quantitative investments: the max drawdown may be very drastic.

But, can we really transform it into smaller cycles?

I have changed my updating criteria, from daily to every 5 minute of market-time, and all the other variables remain the same.

For instance:

  • The highest price in 9 days now refers to the highest price in 9 5-minute-time, i.e., 45 minutes

Let's see the results:

Profits & Loss:

MACD:

KDJ:

RSI:

Surprise! (In fact, not very surprise to professionals)

A beautiful smooth downward curve! It strongly supports the idea that if we keep the status quo, then all the trends captured by daily cycle would soon disappear in a 5-minute cycle.

Therefore, in determining smaller cycles, we need to be more careful.

I will do some smaller cycle analysis and combining singular trend capturing strategies in the next time.

* 1 See the performance of all the other active Futures Contracts at:
https://drive.google.com/open?id=1V1GF93pYCEmxnfwPCxeOvzqCaUE8ilzU

* 2 For some reasons, Source Code and raw data is not applicable.

* 3 I have tested the precision of MACD, RSI and KDJ prediction of the trend tomorrow. They are mostly around 45%-48%. This seems to be very frustrating but the reality is the correct trend these indexes have captured can be those drastic trend and once captured successfully a large amount of profits can be realized.

BackTest on Dual Thrust

Dual Thrust is basically one of the first investment strategies that I have developed and tested.

It was developed by Michael Chalek in 1980s, and it was one of the most profitable strategies at that time.

Its general idea is to capture an upward or downward momentum signaled by a suddenly increased or decreased price.

This strategy is determined by two lines: one buy-line, the other one sell-line. If the close price / current price is higher than the buy-line, then buy one; else if lower than sell-line, then sell one.

Buy/Sell-line is based on the volatility of current price. Specifically, it is the open price of a certain date plus or minus the parameter 'k' times an another parameter 'range'. Range is composed of max(Highest_High - Lowest_Close, Highest_Close - Lowest_Low), which can be shown more clearly in the followings.

In expression:

  • HH = highest highest price in n days 
  • HC = highest close price in n days
  • LC = lowest close price in n days
  • LL = lowest lowest price in n days
  • range = max(HH-LC, HC-LL)
  • buyline = open + k1*range
  • sellline = open - k2*range

Here we assume that
  • Parameter date is n
  • k1 = k2 = K

The performance of this strategy is doubted. But, why still using such an old, out of date strategy?

For one, I am a Chinese market potential investor. Though it has been generally accepted that US markets are already weakly efficient, Chinese financial markets are still far from that.

For another, Dual Thrust is easy to understand and simple to test.

The financial market I will be testing is Shanghai Futures Exchange, China, and the financial instrument is Futures contracts of Aluminum.

All the data were selected from CSMAR on a daily basis (国泰安金融数据库).


The result is:


Continue with sensitive analysis: change parameters K and date, and we have:
Sharpe       K = 0.5     K = 0.7
date = 8       1.36          1.40
date = 12     1.63         -0.09
date = 16     1.60          1.45
To conclude, we have:

Advantages:
  • Easy to understand and implement

Disadvantages:
  • Static strategies, needs dynamical parameter adaptation
  • Parameters like K and date are sensitive to changes
  • No underlying theory about the authenticity of each parameter

Potential improvements:
  • Smaller trends (e.g. 5-minute Candlestick chart) may stabilize profits in a shorter-run
  • Adjust parameters based on volatility

Conclusion:
  • Static traditional Dual Thrust is valid but not very strong. Its performance is sensitive to many factors, and to improve the performance many improvements need to be done.

Source Code File: To be updated
Raw Data: To be updated

HelloWorld!!!

This is my new blog QuantBottle! HelloWorld!!!

There is a convention to print "HelloWorld!!!" as the first command in learning a new programming language, such as C++, Java, Python, etc.

Coding is also the basement of quantitative trading. High-frequency trading needs coding, as well as alpha seeking, momentum trading, and algorithm trading... Even the most traditional tools like technical and fundamental analysis can be strong weapons with the help of codes.

Hence, as an undergraduate interested in investments, I believe it is highly important to master a programming language, practice it hard, and apply it into real investments.

And the intention to create this blog is to force myself to learn and write, thus to improve my skills in this area.

For those readers coming here by accident, happens to be interested in Quantitative Investments and wants to discuss or share something with me, please send me email or just comment!

Hope I can get any reader at least ;)