Hide navigation sidebar
Hide table of contents sidebar
Back to top
Toggle table of contents sidebar

# def trace_stats

Lifecycle method that will be executed after on_trading_iteration. context is a dictionary containing the result of locals() of on_trading_iteration() at the end of its execution.

locals() returns a dictionary of the variables defined in the scope where it is called.

Use this method to dump stats

    import random
    class MyStrategy(Strategy):
    def on_trading_iteration(self):
        google_symbol = "GOOG"

    def trace_stats(self, context, snapshot_before):
        print(context)
        # printing
        # { "google_symbol":"GOOG"}
        random_number = random.randint(0, 100)
        row = {"my_custom_stat": random_number}

        return row

## Reference

strategies.strategy.Strategy.trace_stats(self, context, snapshot_before)

  Lifecycle method that will be executed after on_trading_iteration. context is a dictionary containing on_trading_iteration locals() in last call. Use this method to dump stats

  Parameters:

    - context (dict) – Dictionary containing locals() from current call to on_trading_iteration method.

    - snapshot_before (dict) – Dictionary containing locals() from last call to on_trading_iteration method.

  Returns:

    Dictionary containing the stats to be logged.

  Return type:

    dict

  Example

      >>> def trace_stats(self, context, snapshot_before):
      >>>     self.log_message("Trace stats")
      >>>     self.log_message(f"Context: {context}")
      >>>     self.log_message(f"Snapshot before: {snapshot_before}")
      >>>     return {
      >>>         "my_stat": context["my_stat"],
      >>>         "my_other_stat": context["my_other_stat"],
      >>>         "portfolio_value": self.portfolio_value,
      >>>         "cash": self.cash,
      >>>     }