Files
quantconnect--lean/Common/Securities/Option/StrategyMatcher/OptionStrategyMatcherOptions.cs
Michael Handschuh b9974e6f54 Add OptionStrategyMatcher (#4924)
* 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
2020-12-02 18:42:24 -03:00

258 lines
11 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.Generic;
using System.Linq;
namespace QuantConnect.Securities.Option.StrategyMatcher
{
/// <summary>
/// Defines options that influence how the matcher operates.
/// </summary>
/// <remarks>
/// Many properties in this type are not implemented in the matcher but are provided to document
/// the types of things that can be added to the matcher in the future as necessary. Some of the
/// features contemplated in this class would require updating the various matching/filtering/slicing
/// functions to accept these options, or a particular property. This is the case for the enumerators
/// which would be used to prioritize which positions to try and match first. A great implementation
/// of the <see cref="IOptionPositionCollectionEnumerator"/> would be to yield positions with the
/// highest margin requirements first. At time of writing, the goal is to achieve a workable rev0,
/// and we can later improve the efficiency/optimization of the matching process.
/// </remarks>
public class OptionStrategyMatcherOptions
{
/// <summary>
/// The maximum amount of time spent trying to find an optimal solution.
/// </summary>
public TimeSpan MaximumDuration { get; }
/// <summary>
/// The maximum number of matches to evaluate for the entire portfolio.
/// </summary>
public int MaximumSolutionCount { get; }
/// <summary>
/// Indexed by leg index, defines the max matches to evaluate per leg.
/// For example, MaximumCountPerLeg[1] is the max matches to evaluate
/// for the second leg (index=1).
/// </summary>
public IReadOnlyList<int> MaximumCountPerLeg { get; }
/// <summary>
/// The definitions to be used for matching.
/// </summary>
public IEnumerable<OptionStrategyDefinition> Definitions
=> _definitionEnumerator.Enumerate(_definitions);
/// <summary>
/// Objective function used to compare different match solutions for a given set of positions/definitions
/// </summary>
public IOptionStrategyMatchObjectiveFunction ObjectiveFunction { get; }
private readonly IReadOnlyList<OptionStrategyDefinition> _definitions;
private readonly IOptionPositionCollectionEnumerator _positionEnumerator;
private readonly IOptionStrategyDefinitionEnumerator _definitionEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="OptionStrategyMatcherOptions"/> class, providing
/// options that control the behavior of the <see cref="OptionStrategyMatcher"/>
/// </summary>
public OptionStrategyMatcherOptions(
IReadOnlyList<OptionStrategyDefinition> definitions,
IReadOnlyList<int> maximumCountPerLeg,
TimeSpan maximumDuration = default(TimeSpan),
int maximumSolutionCount = 100,
IOptionStrategyDefinitionEnumerator definitionEnumerator = null,
IOptionStrategyMatchObjectiveFunction objectiveFunction = null,
IOptionPositionCollectionEnumerator positionEnumerator = null
)
{
if (maximumDuration == default(TimeSpan))
{
maximumDuration = Time.OneMinute;
}
if (definitionEnumerator == null)
{
definitionEnumerator = new IdentityOptionStrategyDefinitionEnumerator();
}
if (objectiveFunction == null)
{
objectiveFunction = new UnmatchedPositionCountOptionStrategyMatchObjectiveFunction();
}
if (positionEnumerator == null)
{
positionEnumerator = new DefaultOptionPositionCollectionEnumerator();
}
_definitions = definitions;
MaximumDuration = maximumDuration;
ObjectiveFunction = objectiveFunction;
MaximumCountPerLeg = maximumCountPerLeg;
_positionEnumerator = positionEnumerator;
_definitionEnumerator = definitionEnumerator;
MaximumSolutionCount = maximumSolutionCount;
}
/// <summary>
/// Gets the maximum number of leg matches to be evaluated. This is to limit evaluating exponential
/// numbers of potential matches as a result of large numbers of unique option positions for the same
/// underlying security.
/// </summary>
public int GetMaximumLegMatches(int legIndex)
{
return MaximumCountPerLeg[legIndex];
}
/// <summary>
/// Enumerates the specified <paramref name="positions"/> according to the configured
/// <see cref="IOptionPositionCollectionEnumerator"/>
/// </summary>
public IEnumerable<OptionPosition> Enumerate(OptionPositionCollection positions)
{
return _positionEnumerator.Enumerate(positions);
}
/// <summary>
/// Creates a new <see cref="OptionStrategyMatcherOptions"/> with the specified <paramref name="definitions"/>,
/// with no limits of maximum matches per leg and default values for the remaining options
/// </summary>
public static OptionStrategyMatcherOptions ForDefinitions(params OptionStrategyDefinition[] definitions)
{
return ForDefinitions(definitions.AsEnumerable());
}
/// <summary>
/// Creates a new <see cref="OptionStrategyMatcherOptions"/> with the specified <paramref name="definitions"/>,
/// with no limits of maximum matches per leg and default values for the remaining options
/// </summary>
public static OptionStrategyMatcherOptions ForDefinitions(IEnumerable<OptionStrategyDefinition> definitions)
{
var maximumCountPerLeg = new[] {int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue};
return new OptionStrategyMatcherOptions(definitions.ToList(), maximumCountPerLeg);
}
/// <summary>
/// Specifies the maximum time provided for obtaining an optimal solution.
/// </summary>
public OptionStrategyMatcherOptions WithMaximumDuration(TimeSpan duration)
{
return new OptionStrategyMatcherOptions(
_definitions,
MaximumCountPerLeg,
duration,
MaximumSolutionCount,
_definitionEnumerator,
ObjectiveFunction,
_positionEnumerator
);
}
/// <summary>
/// Specifies the maximum number of solutions to evaluate via the objective function.
/// </summary>
public OptionStrategyMatcherOptions WithMaximumSolutionCount(int count)
{
return new OptionStrategyMatcherOptions(
_definitions,
MaximumCountPerLeg,
MaximumDuration,
count,
_definitionEnumerator,
ObjectiveFunction,
_positionEnumerator
);
}
/// <summary>
/// Specifies the maximum number of solutions per leg index in a solution. Matching is a recursive
/// process, for example, we'll find a very large number of positions to match the first leg. Matching
/// the second leg we'll see less, and third still even less. This is because each subsequent leg must
/// abide by all the previous legs. This parameter defines how many potential matches to evaluate at
/// each leg. For the first leg, we'll evaluate counts[0] matches. For the second leg we'll evaluate
/// counts[1] matches and so on. By decreasing this parameter we can evaluate more total, complete
/// solutions for the entire portfolio rather than evaluation every single permutation of matches for
/// a particular strategy definition, which grows in absurd exponential fashion as the portfolio grows.
/// </summary>
public OptionStrategyMatcherOptions WithMaximumCountPerLeg(IReadOnlyList<int> counts)
{
return new OptionStrategyMatcherOptions(
_definitions,
counts,
MaximumDuration,
MaximumSolutionCount,
_definitionEnumerator,
ObjectiveFunction,
_positionEnumerator
);
}
/// <summary>
/// Specifies a function used to evaluate how desirable a particular solution is. A good implementation for
/// this would be to minimize the total margin required to hold all of the positions.
/// </summary>
public OptionStrategyMatcherOptions WithObjectiveFunction(IOptionStrategyMatchObjectiveFunction function)
{
return new OptionStrategyMatcherOptions(
_definitions,
MaximumCountPerLeg,
MaximumDuration,
MaximumSolutionCount,
_definitionEnumerator,
function,
_positionEnumerator
);
}
/// <summary>
/// Specifies the order in which definitions are evaluated. Definitions evaluated sooner are more likely to
/// find matches than ones evaluated later.
/// </summary>
public OptionStrategyMatcherOptions WithDefinitionEnumerator(IOptionStrategyDefinitionEnumerator enumerator)
{
return new OptionStrategyMatcherOptions(
_definitions,
MaximumCountPerLeg,
MaximumDuration,
MaximumSolutionCount,
enumerator,
ObjectiveFunction,
_positionEnumerator
);
}
/// <summary>
/// Specifies the order in which positions are evaluated. Positions evaluated sooner are more likely to
/// find matches than ones evaluated later. A good implementation for this is its stand-alone margin required,
/// which would encourage the algorithm to match higher margin positions before matching lower margin positiosn.
/// </summary>
public OptionStrategyMatcherOptions WithPositionEnumerator(IOptionPositionCollectionEnumerator enumerator)
{
return new OptionStrategyMatcherOptions(
_definitions,
MaximumCountPerLeg,
MaximumDuration,
MaximumSolutionCount,
_definitionEnumerator,
ObjectiveFunction,
enumerator
);
}
}
}