Commodity Futures Trading Strategies: Trend-Following and Calendar Spreads

Discussion in 'Automated Trading' started by trader221, Jul 12, 2020.

  1. Hello.
    I found this trading approach interesting:
    Commodity Futures Trading Strategies: Trend-Following and Calendar Spreads.
    You will find this strategy really interesting and I would like to code it. I appeal to quant and algos traders to offer suggestions.
    At first I will code it in python now free to you to modify and improve it.

    thank you all
     
  2. Code:
    import quantopian.optimize as opt
    import quantopian.algorithm as algo
    from quantopian.pipeline.domain import US_EQUITIES
    #from quantopian.pipeline.domain import US_Futures
    from quantopian.pipeline import Pipeline
    import numpy as np
    import pandas as pd
    MAX_GROSS_LEVERAGE = 1.0
    def initialize(context):
        """
        Appelé une fois au début de l'algorithme.
        """
        # Enregistrez les contrats à terme que nous négocierons et les procurations correspondantes pour le prix au comptant du sous-jacent.
        # calendar = calendar.US_EQUITIES
        context.contrat = continuous_future("NG", offset=0, roll="calendar", adjustment=None)
        context.proxy = sid(33697)
     
        # Créez des clés vides qui contiendront plus tard notre fenêtre de données de coût de portage.
        context.donnees = []
        context.quantiles = []
       
        # Rééquilibrer tous les jours, 1 heure après l'ouverture du marché.
        algo.schedule_function(train_algorithm, date_rules.every_day(), time_rules.market_open(hours=1))
        algo.schedule_function(daily_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
        algo.schedule_function(enregistrer_variable, date_rules.every_day(), time_rules.market_open())
       
    def train_algorithm(context, data):
        """
        Avant d'exécuter des transactions, nous devons collecter au moins 30 jours de données. Après cela, continuez à faire glisser la fenêtre de 30 jours
        pour supprimer le point de données le plus ancien tout en ajoutant le point le plus récent.
        """
        contrat = data.current(context.contrat, "contract")
        etf = data.current(context.proxy, "price")
       
        if len(context.donnees) < 30:
            calccule_cout(context, data, contrat, etf)
        else:
            calccule_cout(context, data, contrat, etf)
           # Après avoir collecté 30 jours de données, regroupez les points de données en 5 quantiles.
            context.quantiles = pd.qcut(context.donnees, 5, labels=False) + 1
            context.donnees.pop(0)
    def daily_rebalance(context, data):
        """
        Exécutez les commandes en fonction de notre calendrier schedule_function ().
        """
       
        weights = {}
       
       # Après avoir collecté 30 jours de données, exécutez notre logique de commande en achetant des contrats de transport à faible coût.
        contract = data.current(context.contrat, "contract")
       
        if len(context.donnees) >= 30:
            if len(context.quantiles) >= 30:
                if context.quantiles[-1] == 5 and (contract.expiration_date - get_datetime()).days > 19:
                    weights[contract] = -1
                elif context.quantiles[-1] == 1 and (contract.expiration_date - get_datetime()).days > 19:
                    weights[contract] = 1
       
        for security in context.portfolio.positions:
            if (security.expiration_date - get_datetime()).days <= 19:
                weights[security] = 0
       
        if weights:
            leverage_constraint = opt.MaxGrossLeverage(MAX_GROSS_LEVERAGE)
           
            order_optimal_portfolio(
                objective=opt.TargetPortfolioWeights(weights),
                constraints=[
                    leverage_constraint
                ],
                universe=list(weights.keys())
            )
    def enregistrer_variable(context, data):
        """
        Cette fonction est appelée à la fin de chaque journée et les graphiques
        le nombre de positions longues et courtes que nous détenons.
        """
       # Vérifiez combien de positions longues et courtes nous avons.
        ordres_achats = ordres_ventes = 0
        for position in context.portfolio.positions.values():
            if position.amount > 0:
                ordres_achats += 1
            elif position.amount < 0:
                ordres_ventes += 1
        # enregistrer nos variables.
        record(long_count=ordres_achats, short_count=ordres_ventes)
       
    def calccule_cout(context, data, contract, prixspot):
     
        dateencours = get_datetime()
        prixencours = data.current(contract, "price")
        datedematurite = contract.expiration_date
        prixspot = prixspot
        coutcarry = np.log(prixencours / prixspot) / (datedematurite - dateencours).days
        context.donnees.append(coutcarry)
     
  3. Here is the code.
    you can improve it or offer me ideas to improve it ....

    if you have trading strategies that are not very complex for me (I am a beginner in this world) and effective that you want to code, you can tell me about them.
     
  4. backtest
     
    • cap1.PNG
      cap1.PNG
      File size:
      117.3 KB
      Views:
      78
  5. raddo

    raddo

    If you are looking for algo trading examples, then you can check QuantConnect's tutorial:
    https://www.quantconnect.com/tutorials/strategy-library

    Alternatively, you can check Quantpedia for strategies, which also have codes in QuantConnect framework:
    https://quantpedia.com/screener/?FilterQuantConnect=With+QuantConnect+Code