code: def test_equity_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,
          )
  
      shares = 1 if direction == "long" else -1
  
      def initialize(context):
          api.set_benchmark(self.equity)
  
          api.set_slippage(api.slippage.NoSlippage())
          api.set_commission(api.commission.NoCommission())
  
          context.first_bar = True
  
      if check_portfolio_during_simulation:
          portfolio_snapshots = {}
  
          def check_portfolio(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.equity])
              position = positions[self.equity]
              assert_equal(position.last_sale_date, api.get_datetime())
              assert_equal(position.amount, shares)
              assert_equal(
                  position.last_sale_price,
                  self.EQUITY_MINUTE_CONSTANT_CLOSE,
              )
              assert_equal(position.asset, self.equity)
              assert_equal(
                  position.cost_basis,
                  self.EQUITY_MINUTE_CONSTANT_CLOSE,
              )
  
      else:
  
          def check_portfolio(context, first_bar):
              pass
  
      def handle_data(context, data):
          first_bar = context.first_bar
          if first_bar:
              api.order(self.equity, shares)
              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(context, first_bar)
  
      perf = self.run_algorithm(
          initialize=initialize,
          handle_data=handle_data,
      )
  
      zeros = pd.Series(0.0, index=self.closes)
      all_zero_fields = [
          "algorithm_period_return",
          "benchmark_period_return",
          "excess_return",
          "max_drawdown",
          "treasury_period_return",
      ]
      if direction == "long":
          all_zero_fields.extend(
              (
                  "short_value",
                  "shorts_count",
              )
          )
      else:
          all_zero_fields.extend(
              (
                  "long_value",
                  "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.closes)
      if direction == "long":
          count_field = "longs_count"
      else:
          count_field = "shorts_count"
  
      assert_equal(
          perf[count_field],
          ones,
          check_names=False,
          msg=field,
      )
  
      if direction == "long":
          expected_exposure = pd.Series(
              self.EQUITY_MINUTE_CONSTANT_CLOSE,
              index=self.closes,
          )
          for field in "long_value", "long_exposure":
              assert_equal(
                  perf[field],
                  expected_exposure,
                  check_names=False,
              )
      else:
          expected_exposure = pd.Series(
              -self.EQUITY_MINUTE_CONSTANT_CLOSE,
              index=self.closes,
          )
          for field in "short_value", "short_exposure":
              assert_equal(
                  perf[field],
                  expected_exposure,
                  check_names=False,
              )
  
      nan_then_zero = pd.Series(0.0, index=self.closes)
      nan_then_zero[0] = float("nan")
      nan_then_zero_fields = (
          "algo_volatility",
          "benchmark_volatility",
      )
      for field in nan_then_zero_fields:
          assert_equal(
              perf[field],
              nan_then_zero,
              check_names=False,
              check_dtype=False,
              msg=field,
          )
  
      capital_base_series = pd.Series(
          self.SIM_PARAMS_CAPITAL_BASE,
          index=self.closes,
      )
  
      # with no commissions, slippage, or returns our portfolio value stays
      # constant (at the capital base)
      assert_equal(
          perf["portfolio_value"],
          capital_base_series,
          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 = (
          # we are exposed to only one share, the portfolio value is the
          # capital_base because we have no commissions, slippage, or
          # returns
          self.EQUITY_MINUTE_CONSTANT_CLOSE
          / capital_base_series
      )
      assert_equal(
          perf["max_leverage"],
          expected_max_leverage,
          check_names=False,
      )
  
      expected_cash = capital_base_series.copy()
      if direction == "long":
          # we purchased one share on the first day
          cash_modifier = -self.EQUITY_MINUTE_CONSTANT_CLOSE
      else:
          # we sold one share on the first day
          cash_modifier = +self.EQUITY_MINUTE_CONSTANT_CLOSE
  
      expected_cash[1:] += cash_modifier
  
      assert_equal(
          perf["starting_cash"],
          expected_cash,
          check_names=False,
      )
  
      expected_cash[0] += cash_modifier
      assert_equal(
          perf["ending_cash"],
          expected_cash,
          check_names=False,
      )
  
      # we purchased one share on the first day
      expected_capital_used = pd.Series(0.0, index=self.closes)
      expected_capital_used[0] += cash_modifier
  
      assert_equal(
          perf["capital_used"],
          expected_capital_used,
          check_names=False,
      )
  
      # we hold one share so our positions exposure is that one share's price
      expected_position_exposure = pd.Series(
          -cash_modifier,
          index=self.closes,
      )
      for field in "ending_value", "ending_exposure":
          # for equities, position value and position exposure are the same
          assert_equal(
              perf[field],
              expected_position_exposure,
              check_names=False,
              msg=field,
          )
  
      # we don't start with any positions; the first day has no starting
      # exposure
      expected_position_exposure[0] = 0
      for field in "starting_value", "starting_exposure":
          # for equities, position value and position exposure are the same
          assert_equal(
              perf[field],
              expected_position_exposure,
              check_names=False,
              msg=field,
          )
  
      assert_equal(
          perf["trading_days"],
          pd.Series(
              np.arange(len(self.closes)) + 1,
              index=self.closes,
              dtype=np.int64,
          ),
          check_names=False,
      )
  
      all_none = pd.Series(
          [None] * len(self.closes),
          index=self.closes,
          dtype=object,
      )
      all_none_fields = (
          "alpha",
          "beta",
          "sortino",
      )
      for field in all_none_fields:
          assert_equal(
              perf[field],
              all_none,
              check_names=False,
              msg=field,
          )
  
      orders = perf["orders"]
  
      expected_single_order = {
          "amount": shares,
          "commission": 0.0,
          "created": T("2014-01-06 14:31"),
          "dt": T("2014-01-06 14:32"),
          "filled": shares,
          "id": wildcard,
          "limit": None,
          "limit_reached": False,
          "reason": None,
          "sid": self.equity,
          "status": 1,
          "stop": None,
          "stop_reached": False,
      }
  
      # we only order on the first day
      expected_orders = [[expected_single_order]] + [[]] * (
          len(self.closes) - 1
      )
  
      assert_equal(
          orders.tolist(),
          expected_orders,
          check_names=False,
      )
      assert_equal(
          orders.index,
          self.closes,
          check_names=False,
      )
  
      transactions = perf["transactions"]
  
      expected_single_transaction = {
          "amount": shares,
          "commission": None,
          "dt": T("2014-01-06 14:32"),
          "order_id": wildcard,
          "price": 1.0,
          "sid": self.equity,
      }
  
      # since we only order on the first day, we should only transact on the
      # first day
      expected_transactions = [[expected_single_transaction]] + [[]] * (
          len(self.closes) - 1
      )
  
      assert_equal(
          transactions.tolist(),
          expected_transactions,
      )
      assert_equal(
          transactions.index,
          self.closes,
          check_names=False,
      )
  
      if not check_portfolio_during_simulation:
          return
  
      portfolio_snapshots = pd.DataFrame.from_dict(
          portfolio_snapshots,
          orient="index",
      )
  
      expected_cash = pd.Series(
          self.SIM_PARAMS_CAPITAL_BASE,
          index=self.trading_minutes,
      )
      if direction == "long":
          expected_cash.iloc[1:] -= self.EQUITY_MINUTE_CONSTANT_CLOSE
      else:
          expected_cash.iloc[1:] += self.EQUITY_MINUTE_CONSTANT_CLOSE
      assert_equal(
          portfolio_snapshots["cash"],
          expected_cash,
          check_names=False,
      )
  
      expected_portfolio_capital_used = pd.Series(
          cash_modifier,
          index=self.trading_minutes,
      )
      expected_portfolio_capital_used[0] = 0.0
      expected_capital_used[0] = 0
      assert_equal(
          portfolio_snapshots["cash_flow"],
          expected_portfolio_capital_used,
          check_names=False,
      )
  
      zero_minutes = pd.Series(0.0, index=self.trading_minutes)
      for field in "pnl", "returns":
          assert_equal(
              portfolio_snapshots[field],
              zero_minutes,
              check_names=False,
              msg=field,
          )
  
      reindex_columns = sorted(
          set(portfolio_snapshots.columns)
          - {
              "starting_cash",
              "cash_flow",
              "pnl",
              "returns",
              "positions",
          },
      )
      minute_reindex = perf.rename(
          columns={
              "capital_used": "cash_flow",
              "ending_cash": "cash",
              "ending_exposure": "positions_exposure",
              "ending_value": "positions_value",
          },
      )[reindex_columns].reindex(
          self.trading_minutes,
          method="bfill",
      )
  
      first_minute = self.trading_minutes[0]
      # the first minute should have the default values because we haven't
      # done anything yet
      minute_reindex.loc[
          first_minute, "cash"
      ] = self.SIM_PARAMS_CAPITAL_BASE
      minute_reindex.loc[
          first_minute,
          ["positions_exposure", "positions_value"],
      ] = 0
  
      assert_equal(
          portfolio_snapshots[reindex_columns],
          minute_reindex,
          check_names=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 6 for calling the TestConstantPrice obj's underlying member method code with example usage: obj.test_equity_single_position(direction, check_portfolio_during_simulation) without return types