strategy

Futures - IMF Currency Data

This template uses currency data from the International Monetary Fund and shows an algorithm for futures contracts.

You can clone and edit this example there (tab Examples).


The International Monetary Fund (IMF) publishes a range of time series data on IMF lending, exchange rates and other economic and financial indicators.

In this template we show how to to use currency data for developing a trading algorithm.

Need help? Check the Documentation and find solutions/report problems in the Forum section.

More help with Jupyter? Check the official Jupyter page.

Documentation on the IMF data can be found here.

Once you are done, click on Submit to the contest and take part to our competitions.

API reference:

  • data: check how to work with data;

  • backtesting: read how to run the simulation and check the results.

In this template we use the optimizer function described in:

  • optimization: read more on our article.
In [1]:
%%javascript
window.IPython && (IPython.OutputArea.prototype._should_scroll = function(lines) { return false; })
// disable widget scrolling
In [2]:
import xarray as xr
import numpy as np
import pandas as pd

import qnt.ta as qnta
import qnt.backtester as qnbt
import qnt.data as qndata
In [3]:
# currencies listing
currency_list = qndata.imf_load_currency_list()
pd.DataFrame(currency_list)
100% (1887 of 1887) |####################| Elapsed Time: 0:00:00 Time:  0:00:00
Out[3]:
id name
0 AED U.A.E. dirham
1 AUD Australian dollar
2 BND Brunei dollar
3 BRL Brazilian real
4 BWP Botswana pula
5 CAD Canadian dollar
6 CHF Swiss franc
7 CLP Chilean peso
8 CNY Chinese yuan
9 COP Colombian peso
10 CZK Czech koruna
11 DKK Danish krone
12 DZD Algerian dinar
13 EUR Euro
14 GBP U.K. pound
15 ILS Israeli New Shekel
16 INR Indian rupee
17 JPY Japanese yen
18 KRW Korean won
19 KWD Kuwaiti dinar
20 MUR Mauritian rupee
21 MXN Mexican peso
22 MYR Malaysian ringgit
23 NOK Norwegian krone
24 NZD New Zealand dollar
25 OMR Omani rial
26 PEN Peruvian sol
27 PHP Philippine peso
28 PLN Polish zloty
29 QAR Qatari riyal
30 RUB Russian ruble
31 SAR Saudi Arabian riyal
32 SEK Swedish krona
33 SGD Singapore dollar
34 THB Thai baht
35 TTD Trinidadian dollar
36 USD U.S. dollar
37 UYU Uruguayan peso
38 ZAR South African rand
In [4]:
def load_data(period):
    # load the AEX Index data and the spot EUR rate:
    futures  = qndata.futures_load_data(assets=['F_AE'], tail=period, dims=('time','field','asset'))
    currency = qndata.imf_load_currency_data(assets=['EUR'], tail=period).isel(asset=0)
    return dict(currency=currency, futures=futures), futures.time.values


def window(data, max_date: np.datetime64, lookback_period: int):
    # build sliding window for rolling evaluation:
    min_date = max_date - np.timedelta64(lookback_period, 'D')
    return dict(
        futures  = data['futures'].sel(time=slice(min_date, max_date)),
        currency = data['currency'].sel(time=slice(min_date, max_date))
    )


def strategy(data):
    # this strategy uses the currency data as predictors for the Futures contract:   
    close = data['futures'].sel(field='close')
    currency = data['currency']
    
    ma1 = qnta.lwma(currency,10)
    ma2 = qnta.lwma(currency,50)
    ma3 = qnta.lwma(currency,250)
    
    if ma1.isel(time=-1) > ma2.isel(time=-1) and ma2.isel(time=-1) < ma3.isel(time=-1):
        return xr.ones_like(close.isel(time=-1))
    else:
        return xr.zeros_like(close.isel(time=-1))


weights = qnbt.backtest(
    competition_type='futures',
    load_data=load_data,
    window=window,
    lookback_period=365,
    start_date='2006-01-01',
    strategy=strategy,
    analyze=True,
    build_plots=True
)
Run last pass...
Load data...
100% (35526272 of 35526272) |############| Elapsed Time: 0:00:00 Time:  0:00:00
100% (2437792 of 2437792) |##############| Elapsed Time: 0:00:00 Time:  0:00:00
Run strategy...
Load data for cleanup...
Output cleaning...
fix uniq
Normalization...
Output cleaning is complete.
Write result...
Write output: /root/fractions.nc.gz
---
Run first pass...
Load data...
100% (16521772 of 16521772) |############| Elapsed Time: 0:00:00 Time:  0:00:00
100% (987036 of 987036) |################| Elapsed Time: 0:00:00 Time:  0:00:00
Run strategy...
---
Load full data...
---
Run iterations...

100% (4685 of 4685) |####################| Elapsed Time: 0:00:34 Time:  0:00:34
Merge outputs...
Load data for cleanup and analysis...
Output cleaning...
fix uniq
ffill if the current price is None...
Check missed dates...
WARNING! Output contain missed dates.
Adding missed dates and set zero...
Normalization...
Output cleaning is complete.
Write result...
Write output: /root/fractions.nc.gz
---
Analyze results...
Check...
Check missed dates...
Ok.
Check the sharpe ratio...
Period: 2006-01-01 - 2024-04-16
Sharpe Ratio = 0.2505212788902309
ERROR! The Sharpe Ratio is too low. 0.2505212788902309 < 1
Improve the strategy and make sure that the in-sample Sharpe Ratio more than 1.
Check correlation.
WARNING! Can't calculate correlation.
Correlation check failed.
---
Align...
Calc global stats...
---
Calc stats per asset...
Build plots...
---
Output:
asset F_AD F_AE F_AG F_AH F_AX F_BC F_BG F_BO F_BP F_C
time
2024-04-03 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-04 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-05 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-08 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-09 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-10 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-11 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-12 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-15 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-04-16 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
Stats:
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2024-04-03 1.245509 0.0 0.048235 -0.028672 -0.116132 0.250761 0.012095 0.0 1.0 0.011931 7.482759
2024-04-04 1.245509 0.0 0.048230 -0.028672 -0.116132 0.250734 0.012093 0.0 1.0 0.011929 7.482759
2024-04-05 1.245509 0.0 0.048225 -0.028672 -0.116132 0.250707 0.012090 0.0 1.0 0.011926 7.482759
2024-04-08 1.245509 0.0 0.048220 -0.028672 -0.116132 0.250681 0.012088 0.0 1.0 0.011924 7.482759
2024-04-09 1.245509 0.0 0.048215 -0.028672 -0.116132 0.250654 0.012085 0.0 1.0 0.011921 7.482759
2024-04-10 1.245509 0.0 0.048210 -0.028672 -0.116132 0.250628 0.012083 0.0 1.0 0.011919 7.482759
2024-04-11 1.245509 0.0 0.048205 -0.028672 -0.116132 0.250601 0.012080 0.0 1.0 0.011916 7.482759
2024-04-12 1.245509 0.0 0.048200 -0.028672 -0.116132 0.250574 0.012078 0.0 1.0 0.011914 7.482759
2024-04-15 1.245509 0.0 0.048195 -0.028672 -0.116132 0.250548 0.012075 0.0 1.0 0.011911 7.482759
2024-04-16 1.245509 0.0 0.048190 -0.028672 -0.116132 0.250521 0.012073 0.0 1.0 0.011909 7.482759
---