strategy

Technical Analysis using atr, lwma

Predicting stocks using technical indicators (atr, lwma)

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


This template shows you the basic steps for taking part to the NASDAQ-100 Stock Long-Short contest.

In [1]:
import xarray as xr

import qnt.ta as qnta
import qnt.data as qndata
import qnt.output as qnout
import qnt.stats as qns
import xarray as xr

import qnt.ta as qnta
import qnt.backtester as qnbt
import qnt.data as qndata


def strategy2(data, wma, limit):
    vol = data.sel(field="vol")
    liq = data.sel(field="is_liquid")
    close = data.sel(field="close")
    high = data.sel(field="high")
    low = data.sel(field="low")

    atr = qnta.atr(high=high, low=low, close=close, ma=14)
    ratio = atr / close
    weights = xr.where(ratio > limit, 0, 1)

    money_vol = vol * liq * close
    total_money_vol = money_vol.sum(dim='asset')
    money_vol_share = money_vol / total_money_vol

    return qnta.lwma(money_vol_share, wma) * weights


data = qndata.stocks.load_ndx_data(min_date="2005-01-01")
weights_1 = strategy2(data, wma=135, limit=0.0205)
100% (367973 of 367973) |################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (39443 of 39443) |##################| Elapsed Time: 0:00:00 Time:  0:00:00
100% (14729328 of 14729328) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 1/6 1s
100% (14732356 of 14732356) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 2/6 2s
100% (14729296 of 14729296) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 3/6 4s
100% (14729212 of 14729212) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 4/6 5s
100% (14729212 of 14729212) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 5/6 6s
100% (13678636 of 13678636) |############| Elapsed Time: 0:00:00 Time:  0:00:00
fetched chunk 6/6 7s
Data loaded 7s
In [2]:
def get_enough_bid_for(weights_):
    time_traded = weights_.time[abs(weights_).fillna(0).sum('asset') > 0]
    is_strategy_traded = len(time_traded)
    if is_strategy_traded:
        return xr.where(weights_.time < time_traded.min(), data.sel(field="is_liquid"), weights_)
    return weights_

weights_new = get_enough_bid_for(weights_1)
weights_new = weights_new.sel(time=slice("2006-01-01", None))

weights = qnout.clean(output=weights_new, data=data, kind="stocks_nasdaq100")
Output cleaning...
fix uniq
ffill if the current price is None...
Check liquidity...
WARNING! Strategy trades non-liquid assets.
Fix liquidity...
Ok.
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
In [3]:
def print_statistic(data, weights_all):
    import qnt.stats as qnstats

    stats = qnstats.calc_stat(data, weights_all)
    display(stats.to_pandas().tail(5))
    # graph
    performance = stats.to_pandas()["equity"]
    import qnt.graph as qngraph

    qngraph.make_plot_filled(performance.index, performance, name="PnL (Equity)", type="log")

print_statistic(data, weights)
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2024-04-24 2.512924 0.001677 0.049191 -0.011370 -0.102797 1.050421 0.051671 1.0 183.0 0.026718 22.259062
2024-04-25 2.507053 -0.002336 0.049189 -0.013680 -0.102797 1.047491 0.051525 1.0 183.0 0.026715 22.258882
2024-04-26 2.519952 0.005145 0.049198 -0.008606 -0.102797 1.053079 0.051809 1.0 183.0 0.026724 22.246530
2024-04-29 2.523691 0.001484 0.049193 -0.007134 -0.102797 1.054672 0.051883 1.0 183.0 0.026730 22.330534
2024-04-30 2.519375 -0.001710 0.049190 -0.008832 -0.102797 1.052508 0.051773 1.0 183.0 0.026726 22.412274
In [4]:
qnout.check(weights, data, "stocks_nasdaq100")
qnout.write(weights)  # to participate in the competition
Check liquidity...
Ok.
Check missed dates...
Ok.
Check the sharpe ratio...
Period: 2006-01-01 - 2024-04-30
Sharpe Ratio = 1.0525084265716194
Ok.
Check correlation.
WARNING! Can't calculate correlation.
Correlation check failed.
Write output: /root/fractions.nc.gz
In [5]:
weights
Out[5]:
<xarray.DataArray (time: 4613, asset: 249)>
array([[0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
        0.        ],
       ...,
       [0.        , 0.06287894, 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.06285837, 0.        , ..., 0.        , 0.        ,
        0.        ],
       [0.        , 0.06282246, 0.        , ..., 0.        , 0.        ,
        0.        ]])
Coordinates:
  * time     (time) datetime64[ns] 2006-01-03 2006-01-04 ... 2024-04-30
  * asset    (asset) <U10 'NAS:AAL' 'NAS:AAPL' ... 'NYS:RHT' 'NYS:TEVA'
In [6]:
data
Out[6]:
<xarray.DataArray 'stocks_nasdaq100' (field: 9, time: 4865, asset: 249)>
array([[[     nan,   1.1568,      nan, ...,  12.08  ,  13.41  ,
          29.81  ],
        [     nan,   1.1393,      nan, ...,  12.49  ,  13.05  ,
          29.2   ],
        [     nan,   1.1511,      nan, ...,  12.11  ,  12.6   ,
          27.97  ],
        ...,
        [ 14.07  , 169.88  , 163.68  , ...,  41.1   ,      nan,
          13.31  ],
        [ 13.85  , 173.37  , 164.75  , ...,  41.88  ,      nan,
          13.83  ],
        [ 13.85  , 173.33  , 160.56  , ...,  41.49  ,      nan,
          13.99  ]],

       [[     nan,   1.1179,      nan, ...,  11.9   ,  13.03  ,
          29.06  ],
        [     nan,   1.1245,      nan, ...,  11.97  ,  12.54  ,
          28.02  ],
        [     nan,   1.1438,      nan, ...,  11.97  ,  12.25  ,
          27.31  ],
...
        [  1.    ,   1.    ,   1.    , ...,   1.    ,      nan,
           1.    ],
        [  1.    ,   1.    ,   1.    , ...,   1.    ,      nan,
           1.    ],
        [  1.    ,   1.    ,   1.    , ...,   1.    ,      nan,
           1.    ]],

       [[     nan,   1.    ,      nan, ...,   0.    ,   0.    ,
           1.    ],
        [     nan,   1.    ,      nan, ...,   0.    ,   0.    ,
           1.    ],
        [     nan,   1.    ,      nan, ...,   0.    ,   0.    ,
           1.    ],
        ...,
        [  0.    ,   1.    ,   1.    , ...,   0.    ,      nan,
           0.    ],
        [  0.    ,   1.    ,   1.    , ...,   0.    ,      nan,
           0.    ],
        [  0.    ,   1.    ,   1.    , ...,   0.    ,      nan,
           0.    ]]])
Coordinates:
  * time     (time) datetime64[ns] 2005-01-03 2005-01-04 ... 2024-04-30
  * asset    (asset) <U10 'NAS:AAL' 'NAS:AAPL' ... 'NYS:RHT' 'NYS:TEVA'
  * field    (field) object 'open' 'low' 'high' ... 'split_cumprod' 'is_liquid'