Showing posts with label quantitative analysis. Show all posts
Showing posts with label quantitative analysis. Show all posts

Wednesday, 5 September 2018

Simple trading system, does it work in the Nasdaq?

Introduction

There are so many trading styles and the traders can take their decisions from technical analysis, important levels, value investment, quantitative analysis, price movement, and order book study. Some of them combine more than one method at least to have another point of view or to have another idea generation source.

Nowadays, it's easy to find resources for trading. There are plenty of resources online, such as videos and courses. If you are more traditional, you can search for books and see what the people are saying about them.

Some of the most successful traders are known for being contrarians. What does this mean? Maybe they are aware of how powerful the trends could be, however, they are not investing for the long term. They are looking for a quick profit in a short period of time (depends about the how big is the position, who is executing and what are the targets, it can last from a few seconds to less than 3 months).  How do they act? Basically, if a stock or a future has been raising for a while and has a strong trend, they can consider that the product is overvalued and that it will revert to the moving average or at least it will revert enough to make a profit.

The idea

Now, we know what they do. I always thought about it. One of the problems is the timing when I should enter into a trade like that. There are so many statistical methods that you can apply to that. It can be based on the number of days (imagine that the stock has been raising for the last 60 days and you think that every “X” days, there is a retracement), it can be based on the price change (that you can consider it overvalued), it can be a combination of both. We can see that creativity is another part of the trading research. Probably, I will write a post about the whole process in the future but today we are going to review a simple idea.

The trading system is contrarian so it will consider yesterday % change. If yesterday the stock or the underlying product went up, the system will sell it today. And the other way round, if the stock fell yesterday, the system will buy it today.

Nasdaq


I’ve chosen the Nasdaq index as an example. It represents the technology stocks.

    Nasdaq continuous future, daily, source: TradingView

It hasn’t stopped rising since 2010. I wanted to show the period 2014-2018 that I will study in this article. Considering the strong bullish trend maybe I shouldn´t use a contrarian system. I will show you that one of the most important aspects is the risk management (always combine with a profitable system)

Backtest example

Before we start, I need to explain a couple of things. In my opinion, the market behaves differently when it goes up than when it goes down. The falls usually are very sharp. This is why I decided to choose a tighter stop for the sells. I’ve chosen the stops randomly, the buys have a stop of 4 ticks and the sells have a stop of 2 ticks. Let’s check the results:




                                        Backtesting, own elaboration using R

Good news! The mean is positive which is a good starting point. However, making $9.53 per trade is not enough without considering fees and slippage. The system makes $2190 on the best day. The worst lost is $20. The kurtosis is really high because all the values are concentrated around 0. To be honest, the system only makes money on the 3% of the trades. So it’s not tradable even if it makes 103.65% in four years. It would be great if the system had more entry requirements and the number of trades would be reduced. That way the statistics would improve a lot. The Sharpe ratio isn’t great. 



                                                           Max drawdown, own elaboration using R

Considering that the trading system loses in 97% of the trades, the max drawdown is very good. Obviously, each time that it loses, the amount is very small (around 0.2% of the portfolio)



Trading strategy performance, own elaboration 

We can see the characteristics of the system. A few profitable trades and a bunch of losing trades. The probability of taking the loss is very high with our tight stop losses. In other hand, every time that we are right, we make a lot of money.

Sum up

Sadly, there isn’t a good conclusion for this post. I think that I have a lot of work to improve this system.  In addition, this is not a professional way of running a backtest. We should have a period of time in which we test our idea, another period for optimization and different windows of time to test the optimized parameters. Also, we should always consider broker fees and slippage. The system shown is not tradable but it shows that a sounding risk management system is very important. Another idea that we should take from this post is that even a contrarian system can perform in a market that has a clear trend. I hope you like it.
Have a good trading!







Disclaimer


I wrote this article myself, and it expresses my own opinions that shouldn't be used as a trading advice. Trading carries considerable risk due to the high leverage involved


Thursday, 28 June 2018

Momentum system


Sometimes we look for a clear trend in the different markets. This can be difficult these days because the volatility is back. I believe that there are many opportunities but you need to adjust the strategy’s timeframe. Obviously, when we see the chart at the final of the day,  it´s easy to see the levels where we should have bought or sold. I would be happy as far as you do this in order to learn the order flow and how the news affected the security. However, you shouldn’t take seriously the important levels of the day (if you are only checking the day instead of a longer timeframe) because anyone knows what is going to happen tomorrow. I wouldn´t like to discourage you if it works for you but in my opinion is like singing “if I were a rich man” without trying to make money.

Why is the data important? Introduction to the system

As I said indirectly in the first paragraph, I don’t know what the asset prices are going to do tomorrow. The most important for me, leaving my thoughts apart, is the historical data. Here is where statistics takes importance. Let’s get biased for a minute thinking that every time that the price is above an indicator (or another variable) we should buy and every time is below the chosen variable we should sell.


Let´s take the Moving Average 9 as this variable and check the probabilities.

                                               Probability table, example own elaboration

Only to sum up, we have a buy signal every time that the opening is above the MA9 and a sell-side every time the opening is below this indicator. This example is not the best one. I wouldn’t publish this screenshot in a book. Apart from this joke, we had 426 buy signals but only 203 days that the future closes above the opening. Investing in a strategy that has 47.7% success ratio doesn´t seem the smartest thing to do but this is where the money management comes! In the case of the sell signals, it's slightly better showing 52.4%.

Backtesting

Before I show the results I would like to confirm that I´ve used the 5-day moving average instead of the MA9.  The main reason is that the performance was better and the drawdown was lower. This test has been done with the FESB historical data (Eurostoxx Banks). The reason why I chose this product is because I thought that it was directional enough to apply the strategy.





                                                  Backtesting statistics, own elaboration using R programming

As you can see the backtesting results are not bad. Each trade generated 6.42 EUR on average. The biggest win was 740 euros which is great considering that we started with 10000 EUR. I used a tight stop loss, only 2 ticks. Even with that, we can see that the FESB is very directional and the stop was hit only on 53% of the trades. The return has been 56.60% in almost 3 years and a half.



      PnL curve, own elaboration using R programming


The most interesting thing is that after the max drawdown (1570 between the 98th day to the 270th day) it has been rising. Obviously, when your portfolio has grown and you are using the same money management and risk management, the drawdowns are smaller than at the beginning. 



                                                      Max drawdown, own elaboration using R programming


Each trade was simulated with 2 lots and the maximum daily loss was 20 EUR (2% of the initial capital)

Sum up

I like analyzing trading systems and I´ve been working on this strategy for a while. I´m surprised about its performance because I expected worse statistics. Surprisingly, the % of successful trades were almost the same as the previous example shown above. This post doesn´t show the real performance because the commisions are not included. I will write a post in the future explaining why the short-term moving averages fit better than the long term in this kind of system. I hope you like it.
Have a good trading!! 




Disclaimer


I wrote this article myself, and it expresses my own opinions that shouldn't be used as a trading advice. Trading carries considerable risk due to the high leverage involved

Monday, 18 June 2018

Recommended article

Hi. I have been reading a lot these days. One of the best articles I´ve read lately is the following:

http://www.zerohedge.com/news/2018-06-16/global-bond-curve-just-inverted-why-jpm-thinks-market-crash-may-be-imminent

It doesn't matter if it comes from JP Morgan (like this case) or from a top Hedge Fund. The analysis is excellent. I'm a big fan of the interest rate curve. Its movements are only monitored by top traders and portfolio managers but you can extrapolate a lot of investment ideas. The main problem, as always, is getting the data. I would like to congratulate ZeroHedge for bringing this kind of content. Thanks.


Have a good trading!!

Thursday, 9 November 2017

Why should we use R to backtest some strategies? Quantitative approach

We live in a technological era. Basically, we can have whatever we imagine. Walt Disney said once: “If you can dream it, you can do it”. What happens if we put together the technology and the investment world?


Algo Functionality or develop from scratch with a programming language


I know that there are a lot of trading platforms that offer their own easy language or built-in algo functionality, sadly, in my opinion, is not flexible. Let me explain in a better way, you can do a lot of things but mostly it’s focused on Technical Analysis.
Using programming languages allows you to apply whatever you have in mind as far as you can code it. However, it´s more difficult and learning takes time. There are a lot of books and online courses.  
I started with R a couple of years ago. It’s an open source programming language and software environment focused on statistics. I think is one of the easiest and it has similarities with Excel. There are a lot of specific packages that contain different functions and studies. It’s a powerful tool to backest some strategies.

     R Studio screenshot, own elaboration

Create your own systems


Let me sum up some of the advantages and disadvantages of developing a trading system in R.

Advantages

  • You can analyze and backtest large datasets
  • The statistical insights you get from the data can help you to build new systems.
  • It’s more flexible, you can base your decisions purely on the data or even support with some technical analysis.
  • You can optimize the different variables and see how it affects to the system
  • Once the system is live, the risk management won´t be discretionary and you will know the maximum risk you are taking.
  • Attaching  risk management systems and money management systems provide interesting scenarios to consider


Disadvantages

  • Takes time to learning about programming
  • I would recommend to have a good knowledge of trading or investing
  • You will find out that the most part of your ideas are not profitable
  • Programming some of the trading ideas is challenging
  • Linking with the Brokerage API can be difficult


Successful Hedge Funds and Market Makers

There are a lot of Hedge Funds that are known for their specialization on systematic trading using only quantitative models.  Renaissance  Technologies is well known in the sector and they started this way of trading a long time ago. In the recent years, more hedge funds are following these methods and some of the reasons are above. Developing and applying these systems are the hardest part.  Can we emulate this activity in our home? Well, in my humble opinion, we can try. First, we should now that our possibilities are reduced in comparison to a hedge fund or investment bank. These companies employ big teams of people, they can afford to invest money in the latest technology and they have been a long time in the business.

What is the process I follow?

First is the idea generation. Before this step, you should be familiar with the product and understand how it moves. It can be as simple as buying at 9:00 and selling after 5 minutes. You can complicate as much as you want but you should think that you need to code it later. Adding variables to the system will reduce the times that you trade and you will need a larger data sample to meet statistical significance.

Second, you need to download the data from your trading platform or data vendor. Remember to check if the data contains any error. Even if you know the product, I recommend analyzing from a statistical point of view. This can provide you better insights than the chart. The size of the sample should be big enough to meet the statistical significance

Third, code your strategy. Try to make the code as flexible as possible because you will need to optimize some variables in future tests. I would recommend focussing on the risk management and money management because they are key parts for the success of the system. Add ratios to measure the performance, the risk-reward, the biggest drawdown, the success ratio…

Four, applying the strategy to the data. If you are not happy with the ratios shown, try to optimize some variables.

The last step should be adapting your code to the brokerage API to execute the trades.

My little system


I’m not going to disclosure the strategy but it’s based on mean reversion. I chose the Euro-Bund (FGBL) for its liquidity and I believe that we can see significant moves in the near term. The system is designed to open and close positions on the same day. I do apologize for any error as the strategy is at an early stage. Let’s check how is performing from the beginning of the year.

The initial portfolio was set up as 20000 Euros.
    Statistics and ratios from the strategy, own elaboration using R Studio

Let me briefly comment these ratios. As you can see each trade generates 79.35 EUR gain on average, please consider 77 trades because the system doesn’t trade every day. The biggest gain was 910 EUR. The worst day it lost 620 EUR, which shouldn’t be right because I limited the losses to 250 EUR per day. After a while, I discover that it was due to an error in the data. The system has generated 6110 euros this year that considering the initial portfolio of 20000 euros brings a 30.55% return. The probability of a successful trade is 59.65%. The Sharpe Ratio is 2.38.




   Histogram of the closed trades, own elaboration

This is the distribution of the PnL generate by each trade. Sadly it’s concentrated around -250 euros and this is because some movements trigger the stops. 


   PnL Curve since the beginning of the year, own elaboration

I like this chart because it shows that in general terms the system is making money consistently. There are certain drawdowns that I would like to smooth if I decide to optimize some variables of the system.

Finally one of my favourites metrics, the maximum drawdown:


    Max Drawdown, own elaboration

The maximum drawdown is 2650 Euros which was the equivalent to around 10% of the portfolio at that time. It happened between the trades 51 and 62.
I think that the metrics are good, but discussing the performance is not the purpose of this post. You should focus on the process and how to get the advantage of that. Don’t think that every mean reversion system is profitable, I’m sure that if I change the risk parameters and I run the backtest again the system can show loses.

Conclusion


I hope you like it. If you like trading and coding, I recommend following this kind of approach at least for a second opinion. Some of the biggest hedge funds are investing in this kind of technology and they are trying to create systems that emulate the most experienced and successful traders. Thanks.

Have a good trading!




Disclaimer

I wrote this article myself, and it expresses my own opinions that shouldn't be used as a trading advice. Trading carries considerable risk due to the high leverage involved


#trading #quantitativeanalysis  #tradingstrategies #tradingsystems #Rstudio #riskmetrics #performance #FGBL


8th day small profit that helps me to keep going in the competition

After a successful week and most importantly from recovering almost $6k, I wanted to consolidate my positive results. My desire was to b...