Skip to content
All library documents

Executing Long and Short Put Calendar Spreads with Option Strategy Helpers

Article Strategy library · Author: QuantConnect

Summary

This example demonstrates how an options strategy helper can submit and close a put calendar spread as a grouped position. It filters an option chain to puts, sorts contracts by proximity to the underlying price, and finds a strike with at least two expirations. It then uses the nearest and next expiration at that strike to build the spread and submits two units.

The position check expects two legs: short two near-expiration puts and long two farther-expiration puts. To liquidate, the algorithm submits the inverse, short calendar spread. The document illustrates order construction and position validation in a trading engine; it does not report market results or evaluate profitability, pricing, or risk. Its selection logic chooses the first qualifying strike in the sorted chain, so it is an implementation example rather than a complete strike-selection or trade-management method.

Key ideas

  • A put calendar spread combines puts at one strike with different expiration dates.
  • The example selects a strike near the underlying price that has contracts at two expirations.
  • Buying two spreads creates a short near-expiration leg and a long farther-expiration leg.
  • The inverse short calendar spread is used to close the position.

Tags

Full text
# LongAndShortPutCalendarSpreadStrategiesAlgorithm


# LongAndShortPutCalendarSpreadStrategiesAlgorithm









This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In this case, the algorithm tests the Put Calendar Spread and Short Put Calendar Spread strategies.

## Source (Apache-2.0)

```python
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from AlgorithmImports import *

import itertools

from OptionStrategyFactoryMethodsBaseAlgorithm import *

### <summary>
### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
### In this case, the algorithm tests the Put Calendar Spread and Short Put Calendar Spread strategies.
### </summary>
class LongAndShortPutCalendarSpreadStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):

    def expected_orders_count(self) -> int:
        return 4

    def trade_strategy(self, chain: OptionChain, option_symbol: Symbol) -> None:
        put_contracts = sorted((contract for contract in chain if contract.right == OptionRight.PUT),
                              key=lambda x: abs(x.strike - chain.underlying.value))
        for strike, group in itertools.groupby(put_contracts, lambda x: x.strike):
            contracts = sorted(group, key=lambda x: x.expiry)
            if len(contracts) < 2:
                continue

            self._near_expiration = contracts[0].expiry
            self._far_expiration = contracts[1].expiry

            self._put_calendar_spread = OptionStrategies.put_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
            self._short_put_calendar_spread = OptionStrategies.short_put_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
            self.buy(self._put_calendar_spread, 2)
            return

    def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol) -> None:
        positions = list(position_group.positions)
        if len(positions) != 2:
            raise AssertionError(f"Expected position group to have 2 positions. Actual: {len(positions)}")

        near_expiration_position = next((position for position in positions
                                       if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.date == self._near_expiration),
                                      None)
        if not near_expiration_position or near_expiration_position.quantity != -2:
            raise AssertionError(f"Expected near expiration position to be -2. Actual: {near_expiration_position.quantity}")

        far_expiration_position = next((position for position in positions
                                      if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.date == self._far_expiration),
                                     None)
        if not far_expiration_position or far_expiration_position.quantity != 2:
            raise AssertionError(f"Expected far expiration position to be 2. Actual: {far_expiration_position.quantity}")

    def liquidate_strategy(self) -> None:
        # We should be able to close the position using the inverse strategy (a short put calendar spread)
        self.buy(self._short_put_calendar_spread, 2)

```

Shown in full with attribution under the source's licence. Licence: Apache-2.0

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.