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
  
      expected_fill_price = self.data_portal.get_scalar_asset_spot_value(
          self.equity,
          "close",
          # we expect to kill in the second bar of the first day
          self.equity_minutes[1],
          "minute",
      )
  
      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(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.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,
                  data.current(self.equity, "close"),
              )
              assert_equal(position.asset, self.equity)
              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.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(data, context, first_bar)
  
      perf = self.run_algorithm(
          initialize=initialize,
          handle_data=handle_data,
      )
  
      zeros = pd.Series(0.0, index=self.equity_closes)
      all_zero_fields = [
          "excess_return",
          "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.equity_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.asset_daily_close,
              index=self.equity_closes,
          )
          exposure_fields = "long_value", "long_exposure"
      else:
          expected_exposure = pd.Series(
              -self.asset_daily_close,
              index=self.equity_closes,
          )
          exposure_fields = "short_value", "short_exposure"
  
      for field in exposure_fields:
          assert_equal(
              perf[field],
              expected_exposure,
              check_names=False,
              msg=field,
          )
  
      if direction == "long":
          delta = self.asset_daily_close - expected_fill_price
      else:
          delta = -self.asset_daily_close + expected_fill_price
      expected_portfolio_value = pd.Series(
          self.SIM_PARAMS_CAPITAL_BASE + delta,
          index=self.equity_closes,
      )
  
      assert_equal(
          perf["portfolio_value"],
          expected_portfolio_value,
          check_names=False,
      )
  
      capital_base_series = pd.Series(
          self.SIM_PARAMS_CAPITAL_BASE,
          index=self.equity_closes,
      )
  
      # 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_cash = capital_base_series.copy()
      if direction == "long":
          # we purchased one share on the first day
          cash_modifier = -expected_fill_price
      else:
          # we sold one share on the first day
          cash_modifier = +expected_fill_price
  
      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.equity_closes)
      expected_capital_used[0] += cash_modifier
  
      assert_equal(
          perf["capital_used"],
          expected_capital_used,
          check_names=False,
      )
  
      for field in "ending_value", "ending_exposure":
          # for equities, position value and position exposure are the same
          assert_equal(
              perf[field],
              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
      for field in "starting_value", "starting_exposure":
          # for equities, position value and position exposure are the same
          assert_equal(
              perf[field],
              expected_starting_exposure,
              check_names=False,
              msg=field,
          )
  
      assert_equal(
          perf["trading_days"],
          pd.Series(
              np.arange(len(self.equity_closes)) + 1,
              index=self.equity_closes,
              dtype=np.int64,
          ),
          check_names=False,
      )
  
      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.equity_closes) - 1
      )
  
      assert_equal(
          orders.tolist(),
          expected_orders,
          check_names=False,
      )
      assert_equal(
          orders.index,
          self.equity_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": self.data_portal.get_scalar_asset_spot_value(
              self.equity,
              "close",
              T("2014-01-06 14:32"),
              "minute",
          ),
          "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.equity_closes) - 1
      )
  
      assert_equal(
          transactions.tolist(),
          expected_transactions,
      )
      assert_equal(
          transactions.index,
          self.equity_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.equity_minutes,
      )
      assert_equal(
          portfolio_snapshots["starting_cash"],
          expected_starting_cash,
          check_names=False,
      )
  
      expected_portfolio_capital_used = pd.Series(
          cash_modifier,
          index=self.equity_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,
      )
  
      minute_prices = self.data_portal.get_history_window(
          [self.equity],
          self.equity_minutes[-1],
          len(self.equity_minutes),
          "1m",
          "close",
          "minute",
      )[self.equity]
  
      expected_pnl = minute_prices.diff()
      # we don't enter the position until the second minute
      expected_pnl.iloc[:2] = 0.0
      expected_pnl = expected_pnl.cumsum()
  
      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()
      # we don't enter the position until the second minute
      expected_exposure.iloc[0] = 0.0
      if direction == "short":
          expected_exposure = -expected_exposure
  
      for field in "positions_value", "positions_exposure":
          assert_equal(
              portfolio_snapshots[field],
              expected_exposure,
              check_names=False,
              msg=field,
          )
  
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 7 for calling the TestFixedReturns obj's underlying member method code with example usage: obj.test_equity_single_position(direction, check_portfolio_during_simulation) without return types