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
253 lines
8.8 KiB
C#
253 lines
8.8 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;
|
|
|
|
namespace QuantConnect.Securities.Option.StrategyMatcher
|
|
{
|
|
/// <summary>
|
|
/// Defines a lightweight structure representing a position in an option contract or underlying.
|
|
/// This type is heavily utilized by the options strategy matcher and is the parameter type of
|
|
/// option strategy definition predicates. Underlying quantities should be represented in lot sizes,
|
|
/// which is equal to the quantity of shares divided by the contract's multiplier and then rounded
|
|
/// down towards zero (truncate)
|
|
/// </summary>
|
|
public struct OptionPosition : IEquatable<OptionPosition>
|
|
{
|
|
/// <summary>
|
|
/// Gets a new <see cref="OptionPosition"/> with zero <see cref="Quantity"/>
|
|
/// </summary>
|
|
public static OptionPosition None(Symbol symbol)
|
|
=> new OptionPosition(symbol, 0);
|
|
|
|
/// <summary>
|
|
/// Determines whether or not this position has any quantity
|
|
/// </summary>
|
|
public bool HasQuantity => Quantity != 0;
|
|
|
|
/// <summary>
|
|
/// Determines whether or not this position is for the underlying symbol
|
|
/// </summary>
|
|
public bool IsUnderlying => !Symbol.HasUnderlying;
|
|
|
|
/// <summary>
|
|
/// Number of contracts held, can be positive or negative
|
|
/// </summary>
|
|
public int Quantity { get; }
|
|
|
|
/// <summary>
|
|
/// Option contract symbol
|
|
/// </summary>
|
|
public Symbol Symbol { get; }
|
|
|
|
/// <summary>
|
|
/// Gets the underlying symbol. If this position represents the underlying,
|
|
/// then this property is the same as the <see cref="Symbol"/> property
|
|
/// </summary>
|
|
public Symbol Underlying => IsUnderlying ? Symbol : Symbol.Underlying;
|
|
|
|
/// <summary>
|
|
/// Option contract expiration date
|
|
/// </summary>
|
|
public DateTime Expiration
|
|
{
|
|
get
|
|
{
|
|
if (Symbol.HasUnderlying)
|
|
{
|
|
return Symbol.ID.Date;
|
|
}
|
|
|
|
throw new InvalidOperationException($"{nameof(Expiration)} is not valid for underlying symbols: {Symbol}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Option contract strike price
|
|
/// </summary>
|
|
public decimal Strike
|
|
{
|
|
get
|
|
{
|
|
if (Symbol.HasUnderlying)
|
|
{
|
|
return Symbol.ID.StrikePrice;
|
|
}
|
|
|
|
throw new InvalidOperationException($"{nameof(Strike)} is not valid for underlying symbols: {Symbol}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Option contract right (put/call)
|
|
/// </summary>
|
|
public OptionRight Right
|
|
{
|
|
get
|
|
{
|
|
if (Symbol.HasUnderlying)
|
|
{
|
|
return Symbol.ID.OptionRight;
|
|
}
|
|
|
|
throw new InvalidOperationException($"{nameof(Right)} is not valid for underlying symbols: {Symbol}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets whether this position is short/long/none
|
|
/// </summary>
|
|
public PositionSide Side => (PositionSide) Math.Sign(Quantity);
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="OptionPosition"/> structure
|
|
/// </summary>
|
|
/// <param name="symbol">The option contract symbol</param>
|
|
/// <param name="quantity">The number of contracts held</param>
|
|
public OptionPosition(Symbol symbol, int quantity)
|
|
{
|
|
Symbol = symbol;
|
|
Quantity = quantity;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new <see cref="OptionPosition"/> instance with negative <see cref="Quantity"/>
|
|
/// </summary>
|
|
public OptionPosition Negate()
|
|
{
|
|
return new OptionPosition(Symbol, -Quantity);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new <see cref="OptionPosition"/> with this position's <see cref="Symbol"/>
|
|
/// and the provided <paramref name="quantity"/>
|
|
/// </summary>
|
|
public OptionPosition WithQuantity(int quantity)
|
|
{
|
|
return new OptionPosition(Symbol, quantity);
|
|
}
|
|
|
|
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
|
|
/// <param name="other">An object to compare with this object.</param>
|
|
/// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
|
|
public bool Equals(OptionPosition other)
|
|
{
|
|
return Equals(Symbol, other.Symbol) && Quantity == other.Quantity;
|
|
}
|
|
|
|
/// <summary>Indicates whether this instance and a specified object are equal.</summary>
|
|
/// <param name="obj">The object to compare with the current instance. </param>
|
|
/// <returns>true if <paramref name="obj" /> and this instance are the same type and represent the same value; otherwise, false. </returns>
|
|
public override bool Equals(object obj)
|
|
{
|
|
if (ReferenceEquals(null, obj))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (obj.GetType() != GetType())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return Equals((OptionPosition) obj);
|
|
}
|
|
|
|
/// <summary>Returns the hash code for this instance.</summary>
|
|
/// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
|
|
public override int GetHashCode()
|
|
{
|
|
unchecked
|
|
{
|
|
return ((Symbol != null ? Symbol.GetHashCode() : 0) * 397) ^ Quantity;
|
|
}
|
|
}
|
|
|
|
/// <summary>Returns the fully qualified type name of this instance.</summary>
|
|
/// <returns>The fully qualified type name.</returns>
|
|
public override string ToString()
|
|
{
|
|
var s = Quantity == 1 ? "" : "s";
|
|
if (Symbol.HasUnderlying)
|
|
{
|
|
return $"{Quantity} {Right.ToLower()}{s} on {Symbol.Underlying.Value} at ${Strike} expiring on {Expiration:yyyy-MM-dd}";
|
|
}
|
|
|
|
return $"{Quantity} share{s} of {Symbol.Value}";
|
|
}
|
|
|
|
public static OptionPosition operator *(OptionPosition left, int factor)
|
|
{
|
|
return new OptionPosition(left.Symbol, factor * left.Quantity);
|
|
}
|
|
|
|
public static OptionPosition operator *(int factor, OptionPosition right)
|
|
{
|
|
return new OptionPosition(right.Symbol, factor * right.Quantity);
|
|
}
|
|
|
|
public static OptionPosition operator +(OptionPosition left, OptionPosition right)
|
|
{
|
|
if (!Equals(left.Symbol, right.Symbol))
|
|
{
|
|
if (left == default(OptionPosition))
|
|
{
|
|
return right;
|
|
}
|
|
|
|
if (right == default(OptionPosition))
|
|
{
|
|
return left;
|
|
}
|
|
|
|
throw new InvalidOperationException("Unable to add OptionPosition instances with different symbols");
|
|
}
|
|
|
|
return new OptionPosition(left.Symbol, left.Quantity + right.Quantity);
|
|
}
|
|
|
|
public static OptionPosition operator -(OptionPosition left, OptionPosition right)
|
|
{
|
|
if (!Equals(left.Symbol, right.Symbol))
|
|
{
|
|
if (left == default(OptionPosition))
|
|
{
|
|
// 0 - right
|
|
return right.Negate();
|
|
}
|
|
|
|
if (right == default(OptionPosition))
|
|
{
|
|
// left - 0
|
|
return left;
|
|
}
|
|
|
|
throw new InvalidOperationException("Unable to subtract OptionPosition instances with different symbols");
|
|
}
|
|
|
|
return new OptionPosition(left.Symbol, left.Quantity - right.Quantity);
|
|
}
|
|
|
|
public static bool operator ==(OptionPosition left, OptionPosition right)
|
|
{
|
|
return Equals(left, right);
|
|
}
|
|
|
|
public static bool operator !=(OptionPosition left, OptionPosition right)
|
|
{
|
|
return !Equals(left, right);
|
|
}
|
|
}
|
|
} |