Skip to content

Commit

Permalink
Merge pull request QuantConnect#3787 from QuantConnect/bug-3784-algor…
Browse files Browse the repository at this point in the history
…ithm-leverage-precedence

Adding Security.NullLeverage
  • Loading branch information
jaredbroad authored Nov 4, 2019
2 parents 9ee98d2 + 62753b5 commit 7e33be1
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 12 deletions.
115 changes: 115 additions & 0 deletions Algorithm.CSharp/LeveragePrecedenceRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* 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 QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm which reproduce GH issue 3784, where *default* <see cref="IAlgorithm.UniverseSettings"/>
/// Leverage value took precedence over <see cref="IAlgorithm.BrokerageModel"/>
/// </summary>
public class LeveragePrecedenceRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;

/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);

SetBrokerageModel(new TestBrokerageModel());

_spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
SetUniverseSelection(new ManualUniverseSelectionModel(_spy));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, null));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}

/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_spy, 10);
Debug("Purchased Stock");
}

if (Securities[_spy].Leverage != 10)
{
throw new Exception($"Expecting leverage to be 10, was {Securities[_spy].Leverage}");
}
}

/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;

/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.06%"},
{"Compounding Annual Return", "220.077%"},
{"Drawdown", "2.200%"},
{"Expectancy", "-1"},
{"Net Profit", "1.606%"},
{"Sharpe Ratio", "3.923"},
{"Probabilistic Sharpe Ratio", "67.651%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.572"},
{"Beta", "0.311"},
{"Annual Standard Deviation", "0.174"},
{"Annual Variance", "0.03"},
{"Information Ratio", "1.559"},
{"Tracking Error", "0.209"},
{"Treynor Ratio", "2.199"},
{"Total Fees", "$61.90"}
};

private class TestBrokerageModel : DefaultBrokerageModel
{
public override decimal GetLeverage(Security security)
{
return 10;
}
}
}
}
1 change: 1 addition & 0 deletions Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@
<Compile Include="DynamicSecurityDataAlgorithm.cs" />
<Compile Include="ConfidenceWeightedFrameworkAlgorithm.cs" />
<Compile Include="FreePortfolioValueRegressionAlgorithm.cs" />
<Compile Include="LeveragePrecedenceRegressionAlgorithm.cs" />
<Compile Include="MarginRemainingRegressionAlgorithm.cs" />
<Compile Include="SmartInsiderDataAlgorithm.cs" />
<Compile Include="BasicTemplateAlgorithm.cs" />
Expand Down
20 changes: 10 additions & 10 deletions Algorithm/QCAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public QCAlgorithm()
// universe selection
UniverseManager = new UniverseManager();
Universe = new UniverseDefinitions(this);
UniverseSettings = new UniverseSettings(Resolution.Minute, 2m, true, false, TimeSpan.FromDays(1));
UniverseSettings = new UniverseSettings(Resolution.Minute, Security.NullLeverage, true, false, TimeSpan.FromDays(1));

// initialize our scheduler, this acts as a liason to the real time handler
Schedule = new ScheduleManager(Securities, TimeZone);
Expand Down Expand Up @@ -1406,7 +1406,7 @@ public void SetTradeBuilder(ITradeBuilder tradeBuilder)
/// <param name="extendedMarketHours">Show the after market data as well</param>
public Security AddSecurity(SecurityType securityType, string ticker, Resolution resolution = Resolution.Minute, bool fillDataForward = true, bool extendedMarketHours = false)
{
return AddSecurity(securityType, ticker, resolution, fillDataForward, 0, extendedMarketHours);
return AddSecurity(securityType, ticker, resolution, fillDataForward, Security.NullLeverage, extendedMarketHours);
}

/// <summary>
Expand Down Expand Up @@ -1488,7 +1488,7 @@ public Security AddSecurity(SecurityType securityType, string ticker, Resolution
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <param name="extendedMarketHours">True to send data during pre and post market sessions. Default is <value>false</value></param>
/// <returns>The new <see cref="Equity"/> security</returns>
public Equity AddEquity(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m, bool extendedMarketHours = false)
public Equity AddEquity(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage, bool extendedMarketHours = false)
{
return AddSecurity<Equity>(SecurityType.Equity, ticker, resolution, market, fillDataForward, leverage, extendedMarketHours);
}
Expand All @@ -1502,7 +1502,7 @@ public Equity AddEquity(string ticker, Resolution resolution = Resolution.Minute
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Option"/> security</returns>
public Option AddOption(string underlying, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
public Option AddOption(string underlying, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
if (market == null)
{
Expand Down Expand Up @@ -1552,7 +1552,7 @@ public Option AddOption(string underlying, Resolution resolution = Resolution.Mi
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Future"/> security</returns>
public Future AddFuture(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
public Future AddFuture(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
if (market == null)
{
Expand Down Expand Up @@ -1599,7 +1599,7 @@ public Future AddFuture(string ticker, Resolution resolution = Resolution.Minute
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Future"/> security</returns>
public Future AddFutureContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 0m)
public Future AddFutureContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
var configs = SubscriptionManager.SubscriptionDataConfigService.Add(symbol, resolution, fillDataForward);
var future = (Future)Securities.CreateSecurity(symbol, configs, leverage);
Expand All @@ -1616,7 +1616,7 @@ public Future AddFutureContract(Symbol symbol, Resolution resolution = Resolutio
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Option"/> security</returns>
public Option AddOptionContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 0m)
public Option AddOptionContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
var configs = SubscriptionManager.SubscriptionDataConfigService.Add(symbol, resolution, fillDataForward);
var option = (Option)Securities.CreateSecurity(symbol, configs, leverage);
Expand Down Expand Up @@ -1667,7 +1667,7 @@ public Option AddOptionContract(Symbol symbol, Resolution resolution = Resolutio
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Forex"/> security</returns>
public Forex AddForex(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
public Forex AddForex(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
return AddSecurity<Forex>(SecurityType.Forex, ticker, resolution, market, fillDataForward, leverage, false);
}
Expand All @@ -1681,7 +1681,7 @@ public Forex AddForex(string ticker, Resolution resolution = Resolution.Minute,
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Cfd"/> security</returns>
public Cfd AddCfd(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
public Cfd AddCfd(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
return AddSecurity<Cfd>(SecurityType.Cfd, ticker, resolution, market, fillDataForward, leverage, false);
}
Expand All @@ -1695,7 +1695,7 @@ public Cfd AddCfd(string ticker, Resolution resolution = Resolution.Minute, stri
/// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <returns>The new <see cref="Crypto"/> security</returns>
public Crypto AddCrypto(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
public Crypto AddCrypto(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = Security.NullLeverage)
{
return AddSecurity<Crypto>(SecurityType.Crypto, ticker, resolution, market, fillDataForward, leverage, false);
}
Expand Down
2 changes: 1 addition & 1 deletion Common/Data/UniverseSelection/UniverseSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class UniverseSettings
/// <param name="resolution">The resolution</param>
/// <param name="leverage">The leverage to be used</param>
/// <param name="fillForward">True to fill data forward, false otherwise</param>
/// <param name="extendedMarketHours">True to allow exended market hours data, false otherwise</param>
/// <param name="extendedMarketHours">True to allow extended market hours data, false otherwise</param>
/// <param name="minimumTimeInUniverse">Defines the minimum amount of time a security must remain in the universe before being removed</param>
/// <param name="dataNormalizationMode">Defines how universe data is normalized before being send into the algorithm</param>
public UniverseSettings(Resolution resolution, decimal leverage, bool fillForward, bool extendedMarketHours, TimeSpan minimumTimeInUniverse, DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted)
Expand Down
7 changes: 7 additions & 0 deletions Common/Securities/Security.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ public class Security : ISecurityPrice
// using concurrent bag to avoid list enumeration threading issues
protected readonly ConcurrentBag<SubscriptionDataConfig> SubscriptionsBag;

/// <summary>
/// A null security leverage value
/// </summary>
/// <remarks>This value is used to determine when the
/// <see cref="SecurityInitializer"/> leverage is used</remarks>
public const decimal NullLeverage = 0;

/// <summary>
/// Gets all the subscriptions for this security
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion Common/Securities/SecurityService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public Security CreateSecurity(Symbol symbol,

// if leverage was specified then apply to security after the initializer has run, parameters of this
// method take precedence over the intializer
if (leverage > 0)
if (leverage != Security.NullLeverage)
{
security.SetLeverage(leverage);
}
Expand Down

0 comments on commit 7e33be1

Please sign in to comment.