Menu

Trading strategy backtesting in r

4 Comments

trading strategy backtesting in r

It is a well known and recognized data feed provider geared toward retail users and small institutions. Stanislav Kovalevsky has developed a package backtesting QuantTools. It allows to download and organize historical market data backtesting multiple sources like Yahoo, Google, Finam, MOEX and IQFeed. The feature that interests me the most is the ability to backtesting IQFeed to R. More information can be found here. QuantTools offers four main functionalities: First make sure that IQfeed is open. You can either download daily or intraday data. Trading below code downloads daily prices Open, High, Low, Close for SPY from 1st Jan to 1st June Note the period parameter. It can take any of the following values: QuantTools makes the process of managing and storing tick market data easy. You just setup storage parameters and you are ready to go. The parameters are where, since what date and which symbols you would like to be stored. Any time you can add more symbols and if strategy are not present in backtesting storage, QuantTools tries to get the data from specified start date. The code below will save the data in the following directory: There is one sub folder by instrument and the data is aved trading. You can also store data between specific strategy. In the example below, I first retrieve the data stored above, then select the first price observations and finally draw the chart. Two things to notice: You can refer to the Examples section on QuantTools website. Overall I find the package extremely useful and well documented. The only missing bit is the live feed between R and IQFeed which will make the package a real end to end solution. A few months ago a reader point me out this new way of connecting R and Excel. BERT stands for Basic Excel R Toolkit. At the time of writing the current version of BERT is 1. From a trading technical perspective, BERT is designed to support running Strategy functions from Excel spreadsheet cells. By combining the power of XML, VBA, R and BERT I can create a good looking yet powerful application in the form of an Excel file with minimum VBA code. Ultimately I have a single Excel file gathering all the necessary tasks to manage my portfolio: In the next sections I present the prerequisite to developed such an approach and a step by step guide that explains how BERT could be used for simply passing data from R to Excel with minimal VBA code. Once the installation has completed you should have a new Add-Ins menu in Excel with the buttons as shown below. This is how BERT materialized in Excel. The Custom UI Editor allows to create user defined menus and buttons in Excel ribbon. This is what we want to retrieve in Excel. Save this in a file called myRCode. R any other name is fine in a directory backtesting your choice. In this file paste the following code. This is just sourcing into BERT the R file you created above. Then save and close the file functions. Create and save a file called myFile. This is a macro-enabled file that you save in the directory of your choice. Once the file is saved close it. Once the file is open, paste the below code. You should see something like this. Paste the code below in the newly created module. You should see something like the below appearing. From my perspective the interest of such an approach is the ability to glue together R and Excel obviously but also to include via XML and batch pieces of code from Python, SQL and more. This is exactly what I needed. Finally I would be curious to know if anyone has any experience with BERT? Making the most of the out of sample data August 19,9: Then a comparison of the in and out of sample data help to decide whether the model is robust enough. This post aims at going a backtesting further and provides a statistical method to decide whether the out of sample data is in line with what was created in sample. There is a non-parametric statistical test that does exactly this: Using the Kruskal-Wallis Testwe can decide whether the population distributions are identical without assuming them to follow the normal distribution. It exists other tests of the same nature that could fit into that framework. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. As usual with those things just a kind reminder: This is a very first version of trading project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc… to: Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible even without an internet connection. The most efficient way to do this for me has been to maintain a set of csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: Simple yet very efficient so far. The process is summarized in the chart below. In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc… In addition I present the process of updating daily price data. The code below is placed on a. Note that I added an output file updateLog. The process above is extremely simple because it only describes how to update daily price data. When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. In trading post I focus on two simple and widely used metrics: The IC gives an overview of the factor forecasting ability. Obviously ICs must be as high as possible in absolute terms. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. Obviously there is a survival ship bias: This measure is much less sensitive to outliers than arithmetic mean. This is very significant and powerful for such a simple factor not really a surprise though…. Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark. An IC of 0. Formal significance tests can be evaluated but this is beyond the scope of this article. In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so strategy a few months before you gain a bit of credibility. In the chart below I simulated the experiment with one of my strategies. You start trading in 1st June and all goes well until 23rd Jul. If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. Still on the chart above, assume you get really unlucky and you start trading toward mid-June You would have started in early August trading allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date…. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. I added a few improvements that make the app a bit better at least for me! Below is the list of new features:. I also made the app totally self contained. For the keen reader, this link explains in full details how to package a Shiny app into a desktop app Windows only for now. Besides the interactivity, the Shiny App also solves two problems:. There are essentially 3 files. Genetic backtesting GA are well suited tools to answer that question. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. The general process follows the steps below:. From a trading perspective GA are very useful because they are good at dealing with highly nonlinear problems. However they exhibit some nasty features that are worth mentioning:. There are several R packages dealing with GA, I chose to use the most common one: Daily closing prices for most liquid ETFs from Yahoo finance going back to January The in sample period goes from January to December The Out of sample period starts on January The logic is as following: The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes. The other key element is the fitness function. We might want to use something like: In what follows, I chose to maximise the Sharpe ratio. Before commenting the above results, I want to explain a few trading points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period e. Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. A few potential improvement to explore would be:. The code used in this post is available on a Gist repository. The R Trader Using R and related tools in Quantitative Finance. Linking R to IQFeed with the QuantTools package June 4,7: FInancial Data LoadeR April 21,8: Maintaining a database of price files in R December 13,2: Factor Evaluation in Quantitative Portfolio Management March 23,8: A Simple Shiny App for Monitoring Trading Strategies — Part II August 7,8: Below is the list of new features: I trading included an icon RTraderTradingApp. The app uses as backtesting several csv files one for each strategy. Each file has two columns: There is an example of such a file in the Github repository. The code is essentially made of 3 files. You can load as much strategies as you want as long as the corresponding csv file has the right format see below. R file in a separate directory. R file change the inputPath, inputFile and keepColumns parameters to match your settings. The first two strategy self explanatory the third one is a list of column names within the csv file. Keep only date and daily return. R file Add an extra element to the choice parameter in the first selectInput in the sidebarPanel within the ui. Remove the input in the data reactive function corresponding to the strategy you want to remove within the server. R file Remove the element in the choice parameter in the first selectInput in the sidebarPanel corresponding to the strategy you want to remove within the ui. A Simple Shiny App for Monitoring Trading Strategies June 25,9: Besides the interactivity, the Shiny App also solves two problems: I can focus on a specific time period. It loads the data and format strategy. There is one csv file per strategy each containing at least two columns: You can load as much strategies as you want as long as they have the right format. Using Genetic Algorithms in Quantitative Trading Strategy 14,1: Strategy Posts Linking R to IQFeed with the QuantTools package BERT: Making the most of the out of sample data Introducing fidlr: Entries RSS and Comments RSS. Valid XHTML and CSS. Powered by WordPress and Fluid Blue theme. trading strategy backtesting in r

4 thoughts on “Trading strategy backtesting in r”

  1. androidevil says:

    It provides comprehensive education, health, nutrition and parent involvement services to low-income children and their families.

  2. Abteil says:

    To answer these questions, let me first address the culture in which we live and why marriage is an institution that is countercultural.

  3. afanasm says:

    This reference is a complete acknowledgement of the author(s) and information on how the audience can find the referenced material.

  4. AdVitam says:

    This Fanciulla is such a wonderful issue because, for once, none of the three protagonists ever recorded their role commercially, so that one is spared the many doublings often met in live recordings.

Leave a Reply

Your email address will not be published. Required fields are marked *

inserted by FC2 system