b9974e6f54
* Reformat/cleanup OptionStrategies This file was breaking pretty much every style convention in LEAN. There are other things that should be addressed in here that weren't, such as passing non-argument names as argument names for ArgumentException, as well as preferring constructors over property initializer syntax, but such changes aren't being made to keep this commit strictly reformatting instead of refactoring. Added braces and reformatted long lines to make code more legible. * Add abstract base class for OptionStrategy Option/UnderlyingLegData This allows us to create either or and later use the Invoke method to push it into the appropriate list on OptionStrategy. * Replace O(n) option contract search with 2 O(1) TryGetValue calls A better improvement would be resolving the correct symbol in the strategy, but this immediate change is instead just focused on removing the O(n) search inside a loop. * Add BinaryComparison and supporting methods in ExpressionBuilder We're going to use these binary comparisons to make it possible to create ad-hoc queries against a collection of symbols. Using these expressions, along with type supporting composition of these expression, we'll be able to define predicates that can declaratively define how to match an option strategy with an algorithms current holdings. * Make GetValueOrDefault defaultValue optional Was receiving ambiguous invocations leading to neading to invoke this method explicitly (LinqExtensions.GetValueOrDefault) instead of being able to use it as an extension method. Making the default value optional seems to have resolved this ambiguity, leading to cleaner code in the OptionPositionCollection (forthcoming) * Add OptionPosition and OptionPositionCollection OptionPositionCollection aims to provide a single coherent interface for querying an algorithm's option contract positions and the underlying equity's position in a performant, immutable way. The immutability of the type is necessary for how the options matcher will operate. We need to recursively evaluate potential matches, each step down the stack removing positions from the collection consumed by each leg matched. This will enable parallelism of the solution as well as simplifying the mental model for understanding due to not needing to track mutations to the collection instance. * Add Option test class for easily creating option symbol objects * Add OptionStrategyLegPredicate and OptionStrategyLegDefinition The definition is a composition of predicates, and each predicate supports matching against a set of pre-existing legs and a current position being checked for the next leg (this leg). In addition to the matching functionality, it also supports filtering the OptionPositionCollection, which is where much of the work for resolving potential option strategies is done. By successively filtering the OptionPositionCollection through successive application of predicates, we wil end up with a small set of remaining positions that can be individually evaluated for best margin impacts. All of this effectively unrolls into a giant evaluation tree. Because of this inherent structure, common in combinatorial optimization, the OptionPositionCollection is an immutable type to support concurrent evaluations of different branches of the tree. For large position collections this will dramatically improve strategy resolution times. Finally, the interface between the predicate and the positions collection is purposefully thin and provides a target for future optimizations. * Add OptionStrategyDefinition and OptionStrategyDefinitions pre-defined definitions The OptionStrategyDefinition is a definitional object provided a template and functions used to match algorithm holdings (via OptionPositionCollection) to this definition. The definition defines a particular way in which option positions can be combined in order to achieve a more favorable margin requirement, thereby allowing the algorithm to hold more positions than otherwise possible. This ties into the existing OptionStrategy classes and the end result of the matching process will be OptionStrategy instances definiing all strategies matched according to the provided definitions. * Add OptionStrategyMatcher and Options class, w/ supporting types OptionStrategyMatcherOptions aims to provide some knobs and dials to control how the matcher behaves, and more importantly, which positions get prioritized when matching. Prioritization is controlled via two different enumerators, one controller which definitions are matched first and the other controller which positions are matched first. Still unimplemented, is computing multiple solutions and running the provided objective function to determine the best match. When this gets implemented, we'll also want to implement the timer. For anyone looking to implement these features, please talk with Michael Handschuh as there's a particular way of representing these types of combinatorial solutions (a 3D tree) that can be used as a variation of the linear simplex method for optimizing combinatorial problems. * OptionStrategyMatcher: Address PR review comments * Ensure created OptionStrategy legs all have the same multiplier Each leg definition match gets it's own multiplier which indicates the maximum number of times we matched that particular leg. When we finish matching all legs, we pick the smallest multiplier from all the legs in the definition and use that as the definition's multiplier. When we go to create the OptionStrategy object we MUST make sure we're using the multiplier from the definition and not from the individual legs. This change fixes this issue and also provides a guard clause to ensure that we're not trying to use a multiplier larger than what was matched. * Add XML docs for OptionStrategyDefinitions from OptionStrategies
168 lines
9.1 KiB
C#
168 lines
9.1 KiB
C#
/*
|
|
* 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.
|
|
*/
|
|
|
|
using System;
|
|
using System.Collections.Immutable;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace QuantConnect.Securities.Option.StrategyMatcher
|
|
{
|
|
/// <summary>
|
|
/// Provides a listing of pre-defined <see cref="OptionStrategyDefinition"/>
|
|
/// These definitions are blueprints for <see cref="OptionStrategy"/> instances.
|
|
/// Factory functions for those can be found at <see cref="OptionStrategies"/>
|
|
/// </summary>
|
|
public static class OptionStrategyDefinitions
|
|
{
|
|
// lazy since 'AllDefinitions' is at top of file and static members are evaluated in order
|
|
private static readonly Lazy<ImmutableList<OptionStrategyDefinition>> All
|
|
= new Lazy<ImmutableList<OptionStrategyDefinition>>(() =>
|
|
typeof(OptionStrategyDefinitions)
|
|
.GetProperties(BindingFlags.Public | BindingFlags.Static)
|
|
.Where(property => property.PropertyType == typeof(OptionStrategyDefinition))
|
|
.Select(property => (OptionStrategyDefinition) property.GetValue(null))
|
|
.ToImmutableList()
|
|
);
|
|
|
|
public static ImmutableList<OptionStrategyDefinition> AllDefinitions => All.Value;
|
|
|
|
/// <summary>
|
|
/// Hold 1 lot of the underlying and sell 1 call contract
|
|
/// </summary>
|
|
public static OptionStrategyDefinition CoveredCall { get; }
|
|
= OptionStrategyDefinition.Create("Covered Call", 1,
|
|
OptionStrategyDefinition.CallLeg(-1)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Bear Call Spread strategy consists of two calls with the same expiration but different strikes.
|
|
/// The strike price of the short call is below the strike of the long call. This is a credit spread.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition BearCallSpread { get; }
|
|
= OptionStrategyDefinition.Create("Bear Call Spread",
|
|
OptionStrategyDefinition.CallLeg(-1),
|
|
OptionStrategyDefinition.CallLeg(+1, (legs, p) => p.Strike <= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Bear Put Spread strategy consists of two puts with the same expiration but different strikes.
|
|
/// The strike price of the short put is below the strike of the long put. This is a debit spread.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition BearPutSpread { get; }
|
|
= OptionStrategyDefinition.Create("Bear Put Spread",
|
|
OptionStrategyDefinition.PutLeg(1),
|
|
OptionStrategyDefinition.PutLeg(-1, (legs, p) => p.Strike >= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Bull Call Spread strategy consists of two calls with the same expiration but different strikes.
|
|
/// The strike price of the short call is higher than the strike of the long call. This is a debit spread.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition BullCallSpread { get; }
|
|
= OptionStrategyDefinition.Create("Bull Call Spread",
|
|
OptionStrategyDefinition.CallLeg(+1),
|
|
OptionStrategyDefinition.CallLeg(-1, (legs, p) => p.Strike <= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Method creates new Bull Put Spread strategy, that consists of two puts with the same expiration but
|
|
/// different strikes. The strike price of the short put is above the strike of the long put. This is a
|
|
/// credit spread.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition BullPutSpread { get; }
|
|
= OptionStrategyDefinition.Create("Bull Put Spread",
|
|
OptionStrategyDefinition.PutLeg(-1),
|
|
OptionStrategyDefinition.PutLeg(+1, (legs, p) => p.Strike <= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Straddle strategy is a combination of buying a call and buying a put, both with the same strike price
|
|
/// and expiration.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition Straddle { get; }
|
|
= OptionStrategyDefinition.Create("Straddle",
|
|
OptionStrategyDefinition.CallLeg(+1),
|
|
OptionStrategyDefinition.PutLeg(-1, (legs, p) => p.Strike == legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Strangle strategy consists of buying a call option and a put option with the same expiration date.
|
|
/// The strike price of the call is above the strike of the put.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition Strangle { get; }
|
|
= OptionStrategyDefinition.Create("Strangle",
|
|
OptionStrategyDefinition.CallLeg(+1),
|
|
OptionStrategyDefinition.PutLeg(+1, (legs, p) => p.Strike <= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Call Butterfly strategy consists of two short calls at a middle strike, and one long call each at a lower
|
|
/// and upper strike. The upper and lower strikes must both be equidistant from the middle strike.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition CallButterfly { get; }
|
|
= OptionStrategyDefinition.Create("Call Butterfly",
|
|
OptionStrategyDefinition.CallLeg(+1),
|
|
OptionStrategyDefinition.CallLeg(-2, (legs, p) => p.Strike >= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration),
|
|
OptionStrategyDefinition.CallLeg(+1, (legs, p) => p.Strike >= legs[1].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration,
|
|
(legs, p) => p.Strike - legs[1].Strike == legs[1].Strike - legs[0].Strike)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Put Butterfly strategy consists of two short puts at a middle strike, and one long put each at a lower and
|
|
/// upper strike. The upper and lower strikes must both be equidistant from the middle strike.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition PutButterfly { get; }
|
|
= OptionStrategyDefinition.Create("Put Butterfly",
|
|
OptionStrategyDefinition.PutLeg(+1),
|
|
OptionStrategyDefinition.PutLeg(-2, (legs, p) => p.Strike >= legs[0].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration),
|
|
OptionStrategyDefinition.PutLeg(+1, (legs, p) => p.Strike >= legs[1].Strike,
|
|
(legs, p) => p.Expiration == legs[0].Expiration,
|
|
(legs, p) => p.Strike - legs[1].Strike == legs[1].Strike - legs[0].Strike)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Call Calendar Spread strategy is a short one call option and long a second call option with a more distant
|
|
/// expiration.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition CallCalendarSpread { get; }
|
|
= OptionStrategyDefinition.Create("Call Calendar Spread",
|
|
OptionStrategyDefinition.CallLeg(+1),
|
|
OptionStrategyDefinition.CallLeg(+1, (legs, p) => p.Strike == legs[0].Strike,
|
|
(legs, p) => p.Expiration <= legs[0].Expiration)
|
|
);
|
|
|
|
/// <summary>
|
|
/// Put Calendar Spread strategy is a short one put option and long a second put option with a more distant
|
|
/// expiration.
|
|
/// </summary>
|
|
public static OptionStrategyDefinition PutCalendarSpread { get; }
|
|
= OptionStrategyDefinition.Create("Put Calendar Spread",
|
|
OptionStrategyDefinition.PutLeg(+1),
|
|
OptionStrategyDefinition.PutLeg(+1, (legs, p) => p.Strike == legs[0].Strike,
|
|
(legs, p) => p.Expiration <= legs[0].Expiration)
|
|
);
|
|
}
|
|
}
|