code: def test_future_single_position(
      self, direction, check_portfolio_during_simulation
  ):
      if direction not in ("long", "short"):
          raise ValueError(
              "direction must be either long or short, got: %r"
              % direction,
          )
  
      contracts = 1 if direction == "long" else -1
  
      expected_fill_price = self.futures_data_portal.get_scalar_asset_spot_value(
          self.future,
          "close",
          # we expect to kill in the second bar of the first day
          self.future_minutes[1],
          "minute",
      )
  
      future_execution_close_prices = pd.Series(
          [
              self.futures_data_portal.get_scalar_asset_spot_value(
                  self.future,
                  "close",
                  execution_close_minute,
                  "minute",
              )
              for execution_close_minute in self.future_closes
          ],
          index=self.future_closes,
      )
  
      future_execution_open_prices = pd.Series(
          [
              self.futures_data_portal.get_scalar_asset_spot_value(
                  self.future,
                  "close",
                  execution_open_minute,
                  "minute",
              )
              for execution_open_minute in self.future_opens
          ],
          index=self.future_opens,
      )
  
      def initialize(context):
          api.set_benchmark(self.equity)
  
          api.set_slippage(us_futures=api.slippage.NoSlippage())
          api.set_commission(us_futures=api.commission.NoCommission())
  
          context.first_bar = True
  
      if check_portfolio_during_simulation:
          portfolio_snapshots = {}
  
          def check_portfolio(data, context, first_bar):
              portfolio = context.portfolio
              portfolio_snapshots[
                  api.get_datetime()
              ] = portfolio_snapshot(
                  portfolio,
              )
  
              positions = portfolio.positions
              if first_bar:
                  assert_equal(positions, {})
                  return
  
              assert_equal(list(positions), [self.future])
              position = positions[self.future]
              assert_equal(position.last_sale_date, api.get_datetime())
              assert_equal(position.amount, contracts)
              assert_equal(
                  position.last_sale_price,
                  data.current(self.future, "close"),
              )
              assert_equal(position.asset, self.future)
              assert_equal(
                  position.cost_basis,
                  expected_fill_price,
              )
  
      else:
  
          def check_portfolio(data, context, first_bar):
              pass
  
      def handle_data(context, data):
          first_bar = context.first_bar
          if first_bar:
              api.order(self.future, contracts)
              context.first_bar = False
  
          # take the snapshot after the order; ordering does not affect
          # the portfolio on the bar of the order, only the following bars
          check_portfolio(data, context, first_bar)
  
      perf = self.run_algorithm(
          initialize=initialize,
          handle_data=handle_data,
          trading_calendar=self.trading_calendars[Future],
          data_portal=self.futures_data_portal,
      )
  
      zeros = pd.Series(0.0, index=self.future_closes)
      all_zero_fields = [
          "excess_return",
          "treasury_period_return",
          "short_value",
          "long_value",
          "starting_value",
          "ending_value",
      ]
      if direction == "long":
          all_zero_fields.append("shorts_count")
      else:
          all_zero_fields.append("longs_count")
  
      for field in all_zero_fields:
          assert_equal(
              perf[field],
              zeros,
              check_names=False,
              check_dtype=False,
              msg=field,
          )
  
      ones = pd.Series(1, index=self.future_closes)
      if direction == "long":
          count_field = "longs_count"
      else:
          count_field = "shorts_count"
  
      assert_equal(
          perf[count_field],
          ones,
          check_names=False,
          msg=field,
      )
  
      expected_exposure = pd.Series(
          future_execution_close_prices
          * self.future_contract_multiplier,
          index=self.future_closes,
      )
      exposure_field = "long_exposure"
      if direction == "short":
          exposure_field = "short_exposure"
          expected_exposure = -expected_exposure
  
      assert_equal(
          perf[exposure_field],
          expected_exposure,
          check_names=False,
          msg=exposure_field,
          check_dtype=False,
      )
  
      if direction == "long":
          delta = future_execution_close_prices - expected_fill_price
      else:
          delta = -future_execution_close_prices + expected_fill_price
  
      expected_portfolio_value = pd.Series(
          (
              self.SIM_PARAMS_CAPITAL_BASE
              + self.future_contract_multiplier * delta
          ),
          index=self.future_closes,
      )
  
      assert_equal(
          perf["portfolio_value"],
          expected_portfolio_value,
          check_names=False,
      )
  
      # leverage is gross market exposure / current notional capital
      # gross market exposure is
      # sum(long_exposure) + sum(abs(short_exposure))
      # current notional capital is the current portfolio value
      expected_max_leverage = np.maximum.accumulate(
          expected_exposure.abs() / expected_portfolio_value,
      )
      assert_equal(
          perf["max_leverage"],
          expected_max_leverage,
          check_names=False,
      )
  
      expected_cashflow = pd.Series(
          (
              self.future_contract_multiplier
              * (future_execution_close_prices - expected_fill_price)
          ),
          index=self.future_closes,
      )
      if direction == "short":
          expected_cashflow = -expected_cashflow
  
      expected_cash = self.SIM_PARAMS_CAPITAL_BASE + expected_cashflow
      assert_equal(
          perf["ending_cash"],
          expected_cash,
          check_names=False,
      )
  
      delta = self.future_contract_multiplier * (
          future_execution_open_prices - expected_fill_price
      )
      if direction == "short":
          delta = -delta
  
      # NOTE: this seems really wrong to me: we should report the cash
      # as of the start of the session, not the cash at the end of the
      # previous session
      expected_starting_cash = expected_cash.shift(1)
      expected_starting_cash.iloc[0] = self.SIM_PARAMS_CAPITAL_BASE
  
      assert_equal(
          perf["starting_cash"],
          expected_starting_cash,
          check_names=False,
      )
  
      assert_equal(
          perf["capital_used"],
          perf["ending_cash"] - perf["starting_cash"],
          check_names=False,
      )
  
      # for equities, position value and position exposure are the same
      assert_equal(
          perf["ending_exposure"],
          expected_exposure,
          check_names=False,
          msg=field,
      )
  
      # we don't start with any positions; the first day has no starting
      # exposure
      expected_starting_exposure = expected_exposure.shift(1)
      expected_starting_exposure[0] = 0.0
      assert_equal(
          perf["starting_exposure"],
          expected_starting_exposure,
          check_names=False,
          msg=field,
      )
  
      assert_equal(
          perf["trading_days"],
          pd.Series(
              np.arange(len(self.future_closes)) + 1,
              index=self.future_closes,
          ),
          check_names=False,
      )
  
      orders = perf["orders"]
  
      expected_single_order = {
          "amount": contracts,
          "commission": 0.0,
          "created": self.future_minutes[0],
          "dt": self.future_minutes[1],
          "filled": contracts,
          "id": wildcard,
          "limit": None,
          "limit_reached": False,
          "reason": None,
          "sid": self.future,
          "status": 1,
          "stop": None,
          "stop_reached": False,
      }
  
      # we only order on the first day
      expected_orders = [[expected_single_order]] + [[]] * (
          len(self.future_closes) - 1
      )
  
      assert_equal(
          orders.tolist(),
          expected_orders,
          check_names=False,
      )
      assert_equal(
          orders.index,
          self.future_closes,
          check_names=False,
      )
  
      transactions = perf["transactions"]
  
      dt = self.future_minutes[1]
      expected_single_transaction = {
          "amount": contracts,
          "commission": None,
          "dt": dt,
          "order_id": wildcard,
          "price": self.futures_data_portal.get_scalar_asset_spot_value(
              self.future,
              "close",
              dt,
              "minute",
          ),
          "sid": self.future,
      }
  
      # since we only order on the first day, we should only transact on the
      # first day
      expected_transactions = [[expected_single_transaction]] + [[]] * (
          len(self.future_closes) - 1
      )
  
      assert_equal(
          transactions.tolist(),
          expected_transactions,
      )
      assert_equal(
          transactions.index,
          self.future_closes,
          check_names=False,
      )
  
      if not check_portfolio_during_simulation:
          return
  
      portfolio_snapshots = pd.DataFrame.from_dict(
          portfolio_snapshots,
          orient="index",
      )
  
      expected_starting_cash = pd.Series(
          self.SIM_PARAMS_CAPITAL_BASE,
          index=self.future_minutes,
      )
      assert_equal(
          portfolio_snapshots["starting_cash"],
          expected_starting_cash,
          check_names=False,
      )
  
      execution_minute_prices = pd.Series(
          [
              self.futures_data_portal.get_scalar_asset_spot_value(
                  self.future,
                  "close",
                  minute,
                  "minute",
              )
              for minute in self.future_minutes
          ],
          index=self.future_minutes,
      )
      expected_portfolio_capital_used = (
          self.future_contract_multiplier
          * (execution_minute_prices - expected_fill_price)
      )
      if direction == "short":
          expected_portfolio_capital_used = (
              -expected_portfolio_capital_used
          )
  
      # we don't execute until the second minute; then cash adjustments begin
      expected_portfolio_capital_used.iloc[:2] = 0.0
      assert_equal(
          portfolio_snapshots["cash_flow"],
          expected_portfolio_capital_used,
          check_names=False,
      )
  
      all_minutes = self.trading_calendars[
          Future
      ].minutes_for_sessions_in_range(
          self.START_DATE,
          self.END_DATE,
      )
      valid_minutes = all_minutes[
          all_minutes.slice_indexer(
              self.future_minutes[1],
              self.future_minutes[-1],
          )
      ]
      minute_prices = self.futures_data_portal.get_history_window(
          [self.future],
          self.future_minutes[-1],
          len(valid_minutes) + 1,
          "1m",
          "close",
          "minute",
      )[self.future]
  
      raw_pnl = minute_prices.diff()
      # we don't execute until the second minute; then cash adjustments begin
      raw_pnl.iloc[:2] = 0.0
      raw_pnl = raw_pnl.cumsum() * self.future_contract_multiplier
  
      expected_pnl = raw_pnl.reindex(self.future_minutes)
      if direction == "short":
          expected_pnl = -expected_pnl
  
      assert_equal(
          portfolio_snapshots["pnl"],
          expected_pnl,
          check_names=False,
      )
  
      expected_portfolio_value = (
          self.SIM_PARAMS_CAPITAL_BASE + expected_pnl
      )
      assert_equal(
          portfolio_snapshots["portfolio_value"],
          expected_portfolio_value,
          check_names=False,
      )
  
      expected_returns = (
          portfolio_snapshots["portfolio_value"]
          / self.SIM_PARAMS_CAPITAL_BASE
      ) - 1
      assert_equal(
          portfolio_snapshots["returns"],
          expected_returns,
          check_names=False,
      )
  
      expected_exposure = (
          minute_prices.copy() * self.future_contract_multiplier
      ).reindex(self.future_minutes)
      # we don't enter the position until the second minute
      expected_exposure.iloc[0] = 0.0
      if direction == "short":
          expected_exposure = -expected_exposure
  
      assert_equal(
          portfolio_snapshots["positions_exposure"],
          expected_exposure,
          check_names=False,
      )
  
      expected_value = pd.Series(0.0, index=self.future_minutes)
      assert_equal(
          portfolio_snapshots["positions_value"],
          expected_value,
          check_names=False,
          check_dtype=False,
      )
  
imports: import unittest
  import numpy
  import pandas
  from zipline import api
  from zipline.assets import Equity, Future
  from zipline.assets.synthetic import make_commodity_future_info
  from zipline.data.data_portal import DataPortal
  from zipline.data.resample import MinuteResampleSessionBarReader
  from zipline.testing import parameter_space, prices_generating_returns, simulate_minutes_for_day
  from zipline.testing.fixtures import WithMakeAlgo, WithConstantEquityMinuteBarData, WithConstantFutureMinuteBarData, WithWerror, ZiplineTestCase
  from zipline.testing.predicates import assert_equal, wildcard
label_desc: Use image node_id 8 for calling the TestFixedReturns obj's underlying member method code with example usage: obj.test_future_single_position(direction, check_portfolio_during_simulation) without return types