<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Help in using optimizer for the custom args trend following strategy]]></title><description><![CDATA[<p dir="auto">Hi!</p>
<p dir="auto">This strategy has many custom params and I would like to get an help in using the optimizer to test them!</p>
<pre><code># In your final submission you can remove/deactivate all the other cells to reduce the checking time.
# The checking system will run this book multiple times for every trading day within the in-sample period.
# Every pass the available data will be isolated till the current day.
# qnt.backtester is optimized to work with the checking system.
# The checking system will override test_period=1 to make your strategy to produce weights for 1 day per pass.

import xarray as xr
import numpy as np

import qnt.ta as qnta
import qnt.backtester as qnbt
import qnt.data as qndata
import qnt.xr_talib as xrtl
import xarray.ufuncs as xruf
import qnt.ta as qnta


def load_data(period):
    return qndata.futures_load_data(tail=period)


def calc_positions(futures, ma_periods, roc_periods, sideways_threshold):
    """ Calculates positions for given data(futures) and parameters """
    close = futures.sel(field='close')
    
    # calculate MA 
    ma = qnta.lwma(close, ma_periods)
    # calcuate ROC
    roc = qnta.roc(ma, roc_periods)

    # positive trend direction
    positive_trend = roc &gt; sideways_threshold
    # negtive trend direction
    negative_trend = roc &lt; -sideways_threshold 
    # sideways
    sideways_trend = abs(roc) &lt;= sideways_threshold
    
    # We suppose that a sideways trend after a positive trend is also positive
    side_positive_trend = positive_trend.where(sideways_trend == False).ffill('time').fillna(False)
    # and a sideways trend after a negative trend is also negative
    side_negative_trend = negative_trend.where(sideways_trend == False).ffill('time').fillna(False)

    # define signals
    buy_signal = positive_trend
    buy_stop_signal = side_negative_trend

    sell_signal = negative_trend
    sell_stop_signal = side_positive_trend

    # calc positions 
    position = close.copy(True)
    position[:] = np.nan
    position = xr.where(buy_signal, 1, position)
    position = xr.where(sell_signal, -1, position)
    position = xr.where(xruf.logical_and(buy_stop_signal, position.ffill('time') &gt; 0), 0, position)
    position = xr.where(xruf.logical_and(sell_stop_signal, position.ffill('time') &lt; 0), 0, position)
    position = position.ffill('time').fillna(0)

    return position


def calc_output_all(data, params):
    positions = data.sel(field='close').copy(True)
    positions[:] = np.nan
    for futures_name in params.keys(): 
        p = params[futures_name]
        futures_data = data.sel(asset=futures_name).dropna('time','any')
        p = calc_positions(futures_data, p['ma_periods'], p['roc_periods'], p['sideways_threshold'])
        positions.loc[{'asset':futures_name, 'time':p.time}] = p
    
    return positions

# say we select futures and their parameters for technical algorithm
params = {
    'F_NY': {
        'ma_periods': 200, 
        'roc_periods': 5, 
        'sideways_threshold': 2,
    },
    'F_GX': {
        'ma_periods': 200, 
        'roc_periods': 20, 
        'sideways_threshold': 2
    },
    'F_DX': {
        'ma_periods': 40, 
        'roc_periods': 6, 
        'sideways_threshold': 1
    },
    'F_AE': {
        'ma_periods': 400, 
        'roc_periods': 60, 
        'sideways_threshold': 1
    },
}


futures_list = list(params.keys())


def strategy(data):
    output = calc_output_all(data.sel(asset = futures_list), params)
    return output.isel(time=-1)



weights = qnbt.backtest(
    competition_type="futures",
    load_data=load_data,
    lookback_period=5*365,
    start_date='2006-01-01',
    strategy=strategy
)

'''


def stats_function(data, output):
    start_date = qns.get_default_is_start_date_for_type('cryptofutures')
    stat = qns.calc_stat(data['cryptofutures'], output.sel(time=slice(start_date, None)))
    return stat.isel(time=-1).to_pandas().to_dict()


result = qnop.optimize_strategy(
    data,
    strategy,
    qnop.full_range_args_generator(
        param1=range(5, 1500, 10),  # min, max, step
        param2=range(5, 1500, 10)  # min, max, step
    ),
    workers=1,  # you can set more workers on your PC
    stats_function=stats_function,
)

qnop.build_plot(result)

print("---")
print("Best iteration:")
print(result['best_iteration'])
'''
</code></pre>
]]></description><link>http://quantiacs.com/community/topic/84/help-in-using-optimizer-for-the-custom-args-trend-following-strategy</link><generator>RSS for Node</generator><lastBuildDate>Fri, 15 May 2026 05:38:15 GMT</lastBuildDate><atom:link href="http://quantiacs.com/community/topic/84.rss" rel="self" type="application/rss+xml"/><pubDate>Fri, 28 May 2021 14:19:51 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Help in using optimizer for the custom args trend following strategy on Fri, 28 May 2021 16:07:25 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/15">@magenta-grimer</a> thank you <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a>  <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /> <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /> <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /> <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /> <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /> <img src="http://quantiacs.com/community/plugins/nodebb-plugin-emoji/emoji/android/1f647.png?v=o92lv7m3jt8" class="not-responsive emoji emoji-android emoji--bow" title=":bow:" alt="🙇" /><br />
My compliments four your exceptional python skills</p>
]]></description><link>http://quantiacs.com/community/post/353</link><guid isPermaLink="true">http://quantiacs.com/community/post/353</guid><dc:creator><![CDATA[magenta.grimer]]></dc:creator><pubDate>Fri, 28 May 2021 16:07:25 GMT</pubDate></item></channel></rss>