Navigation

    Quantiacs Community

    • Register
    • Login
    • Search
    • Categories
    • News
    • Recent
    • Tags
    • Popular
    • Users
    • Groups

    Help in using optimizer for the custom args trend following strategy

    Support
    2
    3
    173
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • magenta.grimer
      magenta.grimer last edited by magenta.grimer

      Hi!

      This strategy has many custom params and I would like to get an help in using the optimizer to test them!

      # 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 > sideways_threshold
          # negtive trend direction
          negative_trend = roc < -sideways_threshold 
          # sideways
          sideways_trend = abs(roc) <= 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') > 0), 0, position)
          position = xr.where(xruf.logical_and(sell_stop_signal, position.ffill('time') < 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'])
      '''
      
      magenta.grimer 1 Reply Last reply Reply Quote 0
      • magenta.grimer
        magenta.grimer @magenta.grimer last edited by

        @magenta-grimer thank you @support 🙇 🙇 🙇 🙇 🙇 🙇
        My compliments four your exceptional python skills

        1 Reply Last reply Reply Quote 0
        • support
          support last edited by

          This post is deleted!
          1 Reply Last reply Reply Quote 0
          • First post
            Last post
          Powered by NodeBB | Contributors
          • Documentation
          • About
          • Career
          • My account
          • Privacy policy
          • Terms and Conditions
          • Cookies policy
          Home
          Copyright © 2014 - 2021 Quantiacs LLC.
          Powered by NodeBB | Contributors