Page 2 of 6

Rotating Inversely Correlated Assets – NIFTY and USDINR

Over the last 15 years the economy of India has boomed and it has been reflected in the NIFTY index. The NIFTY has grown 7x since 1998 as the country has grown its exports. According to the UN the one of the primary exports of India are high value services which contributes 30% to their GDP.

We developed a hypothesis that as the strength of the NIFTY grew, the strength of the currency would follow as it is a primarily export economy. As the INR strengthens the ratio to USD falls making it an almost ideally inversely correlated asset.

We first tested this hypothesis treating the USDINR FX pair as a hedge against the NIFTY, but found there were periods where they were positively correlated and the hedge did not work.

Pivoting slightly we experimented with rotating the holdings of the portfolio to focus on the peak performing asset. We used a fixed rolling window to determine the peak performance and then swapped our holdings to focus on that asset.

We used the QuantConnect LEAN 2.0 backtesting engine which allowed us to import financial data from any source to run our analysis. The backtests were conducted over a 16 year period and were completed in 5-10 seconds. We saw phenomenal performance due to the strongly trending nature of the NIFTY and USDINR, achieving a Sharpe Ratio achieving 1.3 vs the NIFTY 0.7, and 42x returns vs 7x of the NIFTY.

To test the resilience of the strategy we experimented with the rolling window period to determine if this was critical to the success of the strategy. We used a rotating window from 3 days up to a 30 day window to optimize the variable for the best performance:

The resulting Sharpe Ratio is fairly robust regardless of the precise value of the rotating window period.

We believe there are many potential future improvements to the strategy to be explored; such as using a dynamically determined rolling window to avoid curve fitting. You could also experiment with different portfolios of inversely correlated assets to pick the best basket of assets.

Backtesting with a REST API

This weekend we reviewed the GIT-API and how people really wanted to use QuantConnect. We built the GIT-API enable using the powerful autocomplete features in Visual Studio. However requiring people to use GIT to submit a backtest was a step learning curve, and prone to errors when the website had traffic spikes.

As a result we made a decision to deprecate the GIT portion of QuantConnect, and replace it with a new RESTful API. It allows you to create projects and submit files for backtesting all via simple JSON commands. The REST API will allow unlimited innovation on top of QuantConnect’s backtesting engine. With just a few URL commands you can tap into our scalable cloud and backtest across terabytes of financial data. See our documentation for how to use the new interface.
Continue reading

‘Lean’ Backtesting Engine v2 Released

After 8 months development we’ve released a new backtesting engine powering QuantConnect called Lean. It is a complete rewrite of QuantConnect’s core technology that can take a generic time-series data source and run a backtest.

We wanted QuantConnect to quickly and easily accept any data source and be able to trade on it as it would equities. Almost every user has their own set of demands, languages, data-sets and trading strategies so we needed a backtesting platform that could accommodate them all.

There are several leaps in engineering with Lean, the key aspects are:

  1. Lightening Speed – We complete a simple backtest across 10 years of 1-minute data in 46 seconds. In head to head benchmarks we are literally 10x faster than the competing platforms (46s vs 7m40s)! This allows you to test ideas faster and design better strategies.
  2. Generic Data – Data sources are dynamically loaded at run-time so you can now backtest any market data that has a Time and Value. You define where the data comes from during backtesting, and can even specify a new streaming source for live trading.
  3. Custom Charting – Plot customized dynamic and flexible charts to the web browser directly from your algorithm. See our last post for some examples on how to use charting in your algorithm.

We’ve been able to maintain backwards compatibility but recommend updating your algorithms to use the new API. There key difference is the name of the data event handler:

//Deprecated v1.0 Event Handler:
public override void OnTradeBar(Dictionary<string, TradeBar> data) { ... }
//New LEAN v2.0 Event Handler:
public void OnData(TradeBars data) { ... }

TradeBars implements an IDictionary<string, TradeBar> so it will work with your current algorithms and make you future proof for updates to come.

If you’re designing locally in Visual Studio we’ve created a new QCAlgorithm base-class, so update your local copies from GitHub.

Here’s an example of importing Bitcoin data to backtest your strategy!

Using the QuantConnect Charting API

We’re pleased to announce the release of a new charting API which lets you create flexible, dynamic charts from your backtest. The charts stream to your browser as the backtest is running and can be configured in many different ways. It is a very simple API, allowing you to create custom charts with just 1 line of code. The minimal usage plots a second line on your strategy’s equity chart. It can be accessed like this:

//Minimum code required for custom plotting:
Plot(string seriesName, decimal/int/float value);
//Example using the 'Strategy Equity' chart by default.
Plot("Portfolio", Portfolio.TotalPortfolioValue);
Custom line plot stacked with your strategy equity.

Custom line plot stacked with your strategy equity.

With just one extra parameter, the chart name, you can also create your own chart and place any series onto it you wish:

//Create your own charts by specifying a chart name:
Plot(string chartName, string seriesName, decimal/int/float value);

Underneath the Plot() function are two key classes: Chart and Series. The Chart class is the canvas you’d like to draw on, it can be set so the Series are Stacked or Overlayed. The Series classes are the data on the chart, they default to Line plots but can be set to be Candles or Scatter. Below is an example of creating a customized chart and plotting our trades on top of the asset price:

Plot prices with trades to see where your algorithm is working.

Plot prices with trades to see where your algorithm is working.

//Our custom chart, id: "Currency Plotter", Overlay the series.
Chart plotter = new Chart("Currency Plotter", ChartType.Overlay);
//Line series for our EURUSD pricing.
plotter.AddSeries(new Series("EURUSD", SeriesType.Line));
//Scatter-series for our BUY-orders.
plotter.AddSeries(new Series("Buy", SeriesType.Scatter));
//Scatter-series for our SELL-orders
plotter.AddSeries(new Series("Sell", SeriesType.Scatter));   
AddChart(plotter); //Add the Chart to our algorithm

Once you’ve setup your custom chart you can access it with the Plot() function.

Plot("Currency Plotter", "EURUSD", price);      // Save End of Day prices.
Plot("Currency Plotter", "Buy", purchasePrice); // Plot purchasing prices.
Plot("Currency Plotter", "Sell", salePrice);    // Plot sale prices.

The SeriesType enum controls the style of a series. Data passed into candle plots gets automatically converted into Daily or Weekly candles depending on the quantity of data. Because of technical limitations of working in a browser all series are capped at 4000 samples. If you find your browser slowing down try sampling less!

Class Chart(string chartName, ChartType type);
Class Series(string seriesName, SeriesType type);
Enum ChartType { Overlay, Stacked }
Enum SeriesType { Line, Scatter, Candle }

Putting it all together the results are fairly exciting, we hope you’ll enjoy! To get you started we’ve made a demonstration algorithm which generates the charts below. Clone it and copy the bits you like into your algorithm.

Harnessing the Twitter API for Sentiment Strategies

In this project we will be writing an application which downloads tweets from Twitter. We are continuing our journey leaning C#, as we started with our Yahoo Finance data downloader.

Twitter has a REST API that allows us to  search for tweets, users, timelines, or even post new messages. We will use an incredible C# Twitter Library called Tweetinvi. It has everything you need to start building your own program. There are other alternatives, but we found this was the easiest and most complete. To use this program, you need to have a Twitter developer account, and use your own credentials.

Continue reading

Downloading Yahoo Finance Data with C#

The following post is the first in a series by Raul Pefaur on Learning C#. Over the last month Raul has taught himself C# with a variety of projects, tutorials and books which he will describe to help others on their journey to using C# for finance. Raul has a Master of Finance and lives in Santiago, Chile.

Yahoo has a popular API which lets you download daily financial data from its enormous library. In this blog post, I will be using this API to download financial data through a C# console application. It was created in Visual Studio and is free for you to download an use, though I recommend you try to build it yourself. If you like, use mine as a reference (I know there’s a lot of improvements in my code you could make. If you do, please share!). Continue reading

RSI Indicator with Martingale Position Sizing

Martingale is a bet sizing technique for increasing odds of winning at the expense of increased risk. The classic example is a coin flipping game where the gambler doubles his bet if he loses, in the hopes of making back any losses to break even. He will continue doubling his bet through subsequent losses until the bet breaks even. Once he returns to whole he continues betting with a unit bet. In theory with infinite capital and exactly 50-50 probability martingale can ensure the gambler will always return a profit.

Martingale portfolios typically display near perfect equity curves with dramatic, short term drawdowns.

Martingale portfolios typically display near perfect equity curves with dramatic, short term drawdowns.

Martingale position sizing is sometimes used in trading strategies without knowing its true risks. Continue reading

The Importance of Benchmarking

There are two different techniques for measuring your strategy performance; relative and absolute performance. Before you design your strategy its important to define your metrics for success. As you iterate through strategy ideas this will help you know where you need to improve.

An absolute return strategy aims to make a consistent steady return independent of market conditions. It might rely on assets which are not affected by the market volatility such as bonds. Strategies which trade long and short are easier to be designed for an absolute return. Continue reading

Three Common Implementation Mistakes

In our work at QuantConnect we have helped with thousands of budding quants over the years. Our algorithm development terminal is a powerful backtesting platform that allows members to design strategies on 15 years of past equities data.

We see several very common mistakes in even the most basic strategies. For our latest free video tutorial – Coding the Exponential Moving Average Strategy – we wanted to start by helping users avoid these common mistakes and show how they could avoid them. These common mistakes are… Continue reading

New HTML5 IDE and Community Discussion Feed

Over the last 12 months we’ve been working day and night, silently and constantly pushing feature updates to make QuantConnect better. It is a very humbling experience looking back on the earlier, cluttered and buggy coding environment.

We decided to do a review, and revisit your needs from scratch to focus on what you really want. We reimagined the coding environment with fresh eyes and after taking a pause, we made the leap deciding to scrap the entire v1.0 interface and rebuild it from scratch. The lessons we’d learned, and changes required were not iterative, they were revolutionary… so we set to work. Continue reading

« Older posts Newer posts »

© 2017 QuantConnect Blog

Democratizing algorithmic investments Up ↑