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% (35948152 of 35948152) |############| Elapsed Time: 0:00:00 Time:  0:00:00
100% (2470024 of 2470024) |##############| 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% (4791 of 4791) |####################| Elapsed Time: 0:00:35 Time:  0:00:35
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-09-11
Sharpe Ratio = 0.24775296130884997
ERROR! The Sharpe Ratio is too low. 0.24775296130884997 < 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-08-29 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-08-30 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-02 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-03 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-04 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-05 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-06 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-09 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-10 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2024-09-11 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-08-29 1.245509 0.0 0.047708 -0.028672 -0.116132 0.247984 0.011831 0.0 1.0 0.011671 7.482759
2024-08-30 1.245509 0.0 0.047703 -0.028672 -0.116132 0.247959 0.011828 0.0 1.0 0.011669 7.482759
2024-09-02 1.245509 0.0 0.047698 -0.028672 -0.116132 0.247933 0.011826 0.0 1.0 0.011667 7.482759
2024-09-03 1.245509 0.0 0.047693 -0.028672 -0.116132 0.247907 0.011823 0.0 1.0 0.011664 7.482759
2024-09-04 1.245509 0.0 0.047688 -0.028672 -0.116132 0.247881 0.011821 0.0 1.0 0.011662 7.482759
2024-09-05 1.245509 0.0 0.047683 -0.028672 -0.116132 0.247856 0.011819 0.0 1.0 0.011659 7.482759
2024-09-06 1.245509 0.0 0.047678 -0.028672 -0.116132 0.247830 0.011816 0.0 1.0 0.011657 7.482759
2024-09-09 1.245509 0.0 0.047673 -0.028672 -0.116132 0.247804 0.011814 0.0 1.0 0.011655 7.482759
2024-09-10 1.245509 0.0 0.047669 -0.028672 -0.116132 0.247779 0.011811 0.0 1.0 0.011652 7.482759
2024-09-11 1.245509 0.0 0.047664 -0.028672 -0.116132 0.247753 0.011809 0.0 1.0 0.011650 7.482759