Accessing Portfolio Positions for Stop-Loss and Take-Profit Rules
Summary
This debugging note follows an attempt to combine a daily top-ten stock selection strategy with exits when a holding gains about 9% or loses 5%. The author reports that `context.options['data']` is a DataSource and has no `positions` attribute, so it cannot provide position cost bases. The later code instead reads positions from `context.portfolio.positions`, while the strategy also obtains current holdings through `context.get_account_positions()`.
The snippets show how the proposed logic compares market prices with cost basis, submits orders to close positions, and adjusts holdings based on the latest market-cap ranking. The document offers a concrete error trace and a revised code attempt, but does not establish that the revised version runs successfully. Its examples also leave practical questions, including how holdings and orders update during a bar, and the final buy-count condition appears inconsistent with the stated ten-position limit. Treat it as a debugging account rather than validated strategy guidance.
Key ideas
- A data source passed through strategy options is not the portfolio object and does not expose positions.
- The shown error occurs when code tries to read positions from the data source.
- The revised snippet retrieves cost bases from the strategy context portfolio positions.
- The example combines price-based exits with daily market-cap ranking and rebalancing.
- The post does not confirm that its final code runs or that order and holding counts stay synchronized.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.