Compare commits
112 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c75b4a98b4 | ||
|
|
288501bd3b | ||
|
|
9e7ead1a19 | ||
|
|
b80e274d4f | ||
|
|
9a355c9be5 | ||
|
|
303b95ab50 | ||
|
|
d826d267f4 | ||
|
|
eb55311052 | ||
|
|
27d18fa2e8 | ||
|
|
bb0c671e7c | ||
|
|
c8dc343c13 | ||
|
|
b6815d22de | ||
|
|
459f60603b | ||
|
|
1aaaa20c61 | ||
|
|
07b6572bf9 | ||
|
|
a675aca7e5 | ||
|
|
87db3fe379 | ||
|
|
74321d1727 | ||
|
|
9fd50a302e | ||
|
|
fc0b2f3fa4 | ||
|
|
c4a2d6eef4 | ||
|
|
c2b60e4e48 | ||
|
|
ca9e55fda6 | ||
|
|
b698641c90 | ||
|
|
e5c709ee29 | ||
|
|
ca787d0a25 | ||
|
|
b1a1277eca | ||
|
|
30d7fb042b | ||
|
|
d1bb70fbb7 | ||
|
|
0946bfc2fb | ||
|
|
f34be8e3ff | ||
|
|
e1d1e28bb8 | ||
|
|
5ea9f04b10 | ||
|
|
2529ba124d | ||
|
|
472f78cc53 | ||
|
|
0c26d42561 | ||
|
|
4b94f50754 | ||
|
|
5bdc60b137 | ||
|
|
3837c32b36 | ||
|
|
0e298edcb2 | ||
|
|
7a753bfa3f | ||
|
|
8e2554b110 | ||
|
|
bfa58b4692 | ||
|
|
e3375bc45e | ||
|
|
ac8b500ba2 | ||
|
|
2557a36feb | ||
|
|
55cb3bdaff | ||
|
|
10bb627fc2 | ||
|
|
3d3733c0fb | ||
|
|
1303ccf843 | ||
|
|
3b5f3fcf42 | ||
|
|
e2de241c2b | ||
|
|
68e2a9170a | ||
|
|
d395f704b3 | ||
|
|
4d1fc7e05a | ||
|
|
e3a562d3c9 | ||
|
|
4fdd60d146 | ||
|
|
abbb50e209 | ||
|
|
0e1cc288a6 | ||
|
|
3b826535c7 | ||
|
|
59da486e30 | ||
|
|
f42d7bb3a2 | ||
|
|
87bd0d7792 | ||
|
|
8ca9258e70 | ||
|
|
72105539fc | ||
|
|
589e8a9293 | ||
|
|
dd27a382f7 | ||
|
|
62a8aee38c | ||
|
|
7e7c27416b | ||
|
|
26f2f88c67 | ||
|
|
c08c129860 | ||
|
|
bae10389ae | ||
|
|
4301d7cead | ||
|
|
d49f1d0d6c | ||
|
|
264c3c8374 | ||
|
|
8a1f67edfc | ||
|
|
5f434f2fa5 | ||
|
|
e37f8ae878 | ||
|
|
b4e95209f6 | ||
|
|
ea65c61dc8 | ||
|
|
6bf6ff1a6a | ||
|
|
d1a35e6281 | ||
|
|
fed1fa929b | ||
|
|
9e7962f5a2 | ||
|
|
3e66733413 | ||
|
|
c11a09e08a | ||
|
|
f06bab944d | ||
|
|
df63b6f5d6 | ||
|
|
1358bd8115 | ||
|
|
40cc7a808a | ||
|
|
e3a4fa1838 | ||
|
|
1d8243ecac | ||
|
|
a8c81cad2a | ||
|
|
5f95a9ba77 | ||
|
|
a9b914c9ef | ||
|
|
5436275901 | ||
|
|
0a315b0ae6 | ||
|
|
33599b473d | ||
|
|
325e788728 | ||
|
|
57ac4d6497 | ||
|
|
664dca2236 | ||
|
|
5415fe6bc0 | ||
|
|
b2517cbbb4 | ||
|
|
b8b0d18993 | ||
|
|
ad865e2a53 | ||
|
|
57f0d17c5d | ||
|
|
d234d69abc | ||
|
|
dd4da7ba95 | ||
|
|
27f5223cd2 | ||
|
|
b3d3df3a3c | ||
|
|
3c1ddb7b96 | ||
|
|
926ac3879a |
2
.github/workflows/gh-actions.yml
vendored
2
.github/workflows/gh-actions.yml
vendored
@@ -28,3 +28,5 @@ jobs:
|
||||
./ci_build_stubs.sh -t -g -p
|
||||
env:
|
||||
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
|
||||
ADDITIONAL_STUBS_REPOS: ${{ secrets.ADDITIONAL_STUBS_REPOS }}
|
||||
QC_GIT_TOKEN: ${{ secrets.QC_GIT_TOKEN }}
|
||||
|
||||
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
@@ -8,8 +8,8 @@
|
||||
marketplace.
|
||||
|
||||
Attach to Python:
|
||||
Will attempt to attach to LEAN running locally using PTVSD. Requires that the process is
|
||||
actively running and config is set: "debugging": true, "debugging-method": "PTVSD",
|
||||
Will attempt to attach to LEAN running locally using DebugPy. Requires that the process is
|
||||
actively running and config is set: "debugging": true, "debugging-method": "DebugPy",
|
||||
Requires Python extension from the marketplace. Currently only works with algorithms in
|
||||
Algorithm.Python directory. This is because we map that directory to our build directory
|
||||
that contains the py file at runtime. If using another location change "localRoot" value
|
||||
|
||||
2
.vscode/readme.md
vendored
2
.vscode/readme.md
vendored
@@ -95,7 +95,7 @@ Python algorithms require a little extra work in order to be able to debug them.
|
||||
First in order to debug a Python algorithm in VS Code we must make the following change to our configuration (Launcher\config.json) under the comment debugging configuration:
|
||||
|
||||
"debugging": true,
|
||||
"debugging-method": "PTVSD",
|
||||
"debugging-method": "DebugPy,
|
||||
|
||||
In setting this we are telling Lean to expect a debugger connection using ‘Python Tools for Visual Studio Debugger’. Once this is set Lean will stop upon initialization and await a connection to the debugger via port 5678.
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm reproducing GH issue #5971 where we add and remove an option in the same loop
|
||||
/// </summary>
|
||||
public class AddAndRemoveSecuritySameLoopRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contract;
|
||||
private bool _hasRemoved;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
|
||||
|
||||
var aapl = AddEquity("AAPL").Symbol;
|
||||
|
||||
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (_hasRemoved)
|
||||
{
|
||||
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
|
||||
}
|
||||
|
||||
_hasRemoved = true;
|
||||
AddOptionContract(_contract);
|
||||
|
||||
// changed my mind!
|
||||
RemoveOptionContract(_contract);
|
||||
RemoveSecurity(_contract.Underlying);
|
||||
|
||||
RemoveSecurity(AddEquity("SPY", Resolution.Daily).Symbol);
|
||||
}
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
throw new Exception("We did not remove the option contract!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "0"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-9.486"},
|
||||
{"Tracking Error", "0.008"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
151
Algorithm.CSharp/AddBetaIndicatorRegressionAlgorithm.cs
Normal file
151
Algorithm.CSharp/AddBetaIndicatorRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* 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.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression test to explain how Beta indicator works
|
||||
/// </summary>
|
||||
public class AddBetaIndicatorRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Beta _beta;
|
||||
private SimpleMovingAverage _sma;
|
||||
private decimal _lastSMAValue;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 07);
|
||||
SetEndDate(2013, 10, 15);
|
||||
SetCash(10000);
|
||||
|
||||
AddEquity("IBM");
|
||||
AddEquity("SPY");
|
||||
|
||||
EnableAutomaticIndicatorWarmUp = true;
|
||||
_beta = B("IBM", "SPY", 3, Resolution.Daily);
|
||||
_sma = SMA("SPY", 3, Resolution.Daily);
|
||||
_lastSMAValue = 0;
|
||||
|
||||
if (!_beta.IsReady)
|
||||
{
|
||||
throw new Exception("_beta indicator was expected to be ready");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnData(Slice data)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
var price = data["IBM"].Close;
|
||||
Buy("IBM", 10);
|
||||
LimitOrder("IBM", 10, price * 0.1m);
|
||||
StopMarketOrder("IBM", 10, price / 0.1m);
|
||||
}
|
||||
|
||||
if (_beta.Current.Value < 0m || _beta.Current.Value > 2.80m)
|
||||
{
|
||||
throw new Exception($"_beta value was expected to be between 0 and 2.80 but was {_beta.Current.Value}");
|
||||
}
|
||||
|
||||
Log($"Beta between IBM and SPY is: {_beta.Current.Value}");
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
var order = Transactions.GetOrderById(orderEvent.OrderId);
|
||||
var goUpwards = _lastSMAValue < _sma.Current.Value;
|
||||
_lastSMAValue = _sma.Current.Value;
|
||||
|
||||
if (order.Status == OrderStatus.Filled)
|
||||
{
|
||||
if (order.Type == OrderType.Limit && Math.Abs(_beta.Current.Value - 1) < 0.2m && goUpwards)
|
||||
{
|
||||
Transactions.CancelOpenOrders(order.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
if (order.Status == OrderStatus.Canceled)
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual 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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "12.939%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.289%"},
|
||||
{"Sharpe Ratio", "4.233"},
|
||||
{"Probabilistic Sharpe Ratio", "68.349%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.035"},
|
||||
{"Beta", "0.122"},
|
||||
{"Annual Standard Deviation", "0.024"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.181"},
|
||||
{"Tracking Error", "0.142"},
|
||||
{"Treynor Ratio", "0.842"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$35000000.00"},
|
||||
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.022"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "8.508"},
|
||||
{"Return Over Maximum Drawdown", "58.894"},
|
||||
{"Portfolio Turnover", "0.022"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "bd88c6a0e10c7e146b05377205101a12"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// and a future contract at the same time
|
||||
/// </summary>
|
||||
public class AddFutureContractWithContinuousRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _currentMappedSymbol;
|
||||
private Future _continuousContract;
|
||||
private Future _futureContract;
|
||||
private bool _ended;
|
||||
|
||||
/// <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, 6);
|
||||
SetEndDate(2013, 10, 10);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
|
||||
_futureContract = AddFutureContract(FutureChainProvider.GetFutureContractList(_continuousContract.Symbol, Time).First());
|
||||
}
|
||||
|
||||
/// <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 (_ended)
|
||||
{
|
||||
throw new Exception($"Algorithm should of ended!");
|
||||
}
|
||||
if (data.Keys.Count > 2)
|
||||
{
|
||||
throw new Exception($"Getting data for more than 2 symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
if (UniverseManager.Count != 3)
|
||||
{
|
||||
throw new Exception($"Expecting 3 universes (chain, continuous and user defined) but have {UniverseManager.Count}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy(_futureContract.Symbol, 1);
|
||||
Buy(_continuousContract.Mapped, 1);
|
||||
|
||||
RemoveSecurity(_futureContract.Symbol);
|
||||
RemoveSecurity(_continuousContract.Symbol);
|
||||
|
||||
_ended = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
|
||||
if (changes.AddedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol)
|
||||
|| changes.RemovedSecurities.Any(security => security.Symbol != _continuousContract.Symbol && security.Symbol != _futureContract.Symbol))
|
||||
{
|
||||
throw new Exception($"We got an unexpected security changes {changes}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "3"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.03%"},
|
||||
{"Compounding Annual Return", "-2.503%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.032%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.678"},
|
||||
{"Tracking Error", "0.243"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$2100000.00"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.419"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-81.557"},
|
||||
{"Portfolio Turnover", "0.837"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "68775c18eb40c1bde212653faec4016e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -139,8 +139,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Tracking Error", "0.049"},
|
||||
{"Treynor Ratio", "1.372"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$45000000.00"},
|
||||
{"Lowest Capacity Asset", "AOL R735QTJ8XC9X"},
|
||||
{"Estimated Strategy Capacity", "$67000000.00"},
|
||||
{"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -160,7 +160,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "b006bb7864c0b2f1a6552fb2aa7f03b8"}
|
||||
{"OrderListHash", "4f50b8360ea317ef974801649088bd06"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
165
Algorithm.CSharp/AddOptionContractTwiceRegressionAlgorithm.cs
Normal file
165
Algorithm.CSharp/AddOptionContractTwiceRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm reproducing GH issue #6073 where we remove and re add an option and expect it to work
|
||||
/// </summary>
|
||||
public class AddOptionContractTwiceRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contract;
|
||||
private bool _hasRemoved;
|
||||
private bool _reAdded;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
|
||||
UniverseSettings.FillForward = false;
|
||||
|
||||
AddEquity("SPY", Resolution.Daily);
|
||||
|
||||
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
|
||||
_contract = OptionChainProvider.GetOptionContractList(aapl, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American);
|
||||
AddOptionContract(_contract);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (_hasRemoved)
|
||||
{
|
||||
if (!_reAdded && slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
throw new Exception("Getting data for removed option and underlying!");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested && _reAdded)
|
||||
{
|
||||
var option = Securities[_contract];
|
||||
var optionUnderlying = Securities[_contract.Underlying];
|
||||
if (option.IsTradable && optionUnderlying.IsTradable
|
||||
&& slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
Buy(_contract, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!Securities[_contract].IsTradable
|
||||
&& !Securities[_contract.Underlying].IsTradable
|
||||
&& !_reAdded)
|
||||
{
|
||||
// ha changed my mind!
|
||||
AddOptionContract(_contract);
|
||||
_reAdded = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (slice.ContainsKey(_contract) && slice.ContainsKey(_contract.Underlying))
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
RemoveOptionContract(_contract);
|
||||
RemoveSecurity(_contract.Underlying);
|
||||
_hasRemoved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
throw new Exception("We did not remove the option contract!");
|
||||
}
|
||||
if (!_reAdded)
|
||||
{
|
||||
throw new Exception("We did not re add the option contract!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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.05%"},
|
||||
{"Compounding Annual Return", "-4.548%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.051%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-9.486"},
|
||||
{"Tracking Error", "0.008"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$30000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL VXBK4Q9ZIFD2|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-89.181"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "7fbcd12db40304d50b3a34d7878eb3cf"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private int _expectedContractIndex;
|
||||
private readonly List<Symbol> _expectedContracts = new List<Symbol>
|
||||
{
|
||||
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
|
||||
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
|
||||
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
|
||||
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
|
||||
};
|
||||
|
||||
@@ -109,6 +109,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var googOptionChain = AddOption(UnderlyingTicker);
|
||||
googOptionChain.SetFilter(u =>
|
||||
{
|
||||
// we added the universe at 10, the universe selection data should not be from before
|
||||
if (u.Underlying.EndTime.Hour < 10)
|
||||
{
|
||||
throw new Exception($"Unexpected underlying data point {u.Underlying.EndTime} {u.Underlying}");
|
||||
}
|
||||
// find first put above market price
|
||||
return u.IncludeWeeklys()
|
||||
.Strikes(+1, +1)
|
||||
@@ -231,7 +236,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$6.00"},
|
||||
{"Estimated Strategy Capacity", "$2000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV 305RBQ2BZBZT2|GOOCV VP83T1ZUHROL"},
|
||||
{"Lowest Capacity Asset", "GOOCV 305RBR0BSWIX2|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -251,7 +256,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "1e7b3e90918777b9dbf46353a96f3329"}
|
||||
{"OrderListHash", "550a99c482106defd8ba15f48183768e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm reproducing issue where underlying option contract would be removed with the first call
|
||||
/// too RemoveOptionContract
|
||||
/// </summary>
|
||||
public class AddTwoAndRemoveOneOptionContractRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contract1;
|
||||
private Symbol _contract2;
|
||||
private bool _hasRemoved;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 06);
|
||||
|
||||
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
|
||||
UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero;
|
||||
|
||||
var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
|
||||
|
||||
var contracts = OptionChainProvider.GetOptionContractList(aapl, Time)
|
||||
.OrderBy(symbol => symbol.ID.Symbol)
|
||||
.Where(optionContract => optionContract.ID.OptionRight == OptionRight.Call
|
||||
&& optionContract.ID.OptionStyle == OptionStyle.American)
|
||||
.Take(2)
|
||||
.ToList();
|
||||
|
||||
_contract1 = contracts[0];
|
||||
_contract2 = contracts[1];
|
||||
AddOptionContract(_contract1);
|
||||
AddOptionContract(_contract2);
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (slice.HasData)
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
RemoveOptionContract(_contract1);
|
||||
_hasRemoved = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
var subscriptions =
|
||||
SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs("AAPL");
|
||||
if (subscriptions.Count == 0)
|
||||
{
|
||||
throw new Exception("No configuration for underlying was found!");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy(_contract2, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_hasRemoved)
|
||||
{
|
||||
throw new Exception("Expect a single call to OnData where we removed the option and underlying");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$230000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL VXBK4QQIRLZA|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "228194dcc6fd8689a67f383577ee2d85"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
private Symbol _aapl;
|
||||
private const string Ticker = "AAPL";
|
||||
private FactorFile _factorFile;
|
||||
private CorporateFactorProvider _factorFile;
|
||||
private readonly IEnumerator<decimal> _expectedAdjustedVolume = new List<decimal> { 6164842, 3044047, 3680347, 3468303, 2169943, 2652523,
|
||||
1499707, 1518215, 1655219, 1510487 }.GetEnumerator();
|
||||
private readonly IEnumerator<decimal> _expectedAdjustedAskSize = new List<decimal> { 215600, 5600, 25200, 8400, 5600, 5600, 2800,
|
||||
@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
factorFileProvider.Initialize(mapFileProvider, dataProvider);
|
||||
|
||||
|
||||
_factorFile = factorFileProvider.Get(_aapl);
|
||||
_factorFile = factorFileProvider.Get(_aapl) as CorporateFactorProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -83,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetSplitFactor(aaplData.Time);
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedVolume = aaplData.Volume / dayFactor;
|
||||
|
||||
if (_expectedAdjustedVolume.Current == probableAdjustedVolume)
|
||||
@@ -107,7 +107,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time);
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedAskSize = aaplQuoteData.LastAskSize / dayFactor;
|
||||
|
||||
if (_expectedAdjustedAskSize.Current == probableAdjustedAskSize)
|
||||
@@ -126,7 +126,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (_expectedAdjustedBidSize.MoveNext() && _expectedAdjustedBidSize.Current != aaplQuoteData.LastBidSize)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time);
|
||||
var dayFactor = _factorFile.GetPriceScale(aaplQuoteData.Time, DataNormalizationMode.SplitAdjusted);
|
||||
var probableAdjustedBidSize = aaplQuoteData.LastBidSize / dayFactor;
|
||||
|
||||
if (_expectedAdjustedBidSize.Current == probableAdjustedBidSize)
|
||||
|
||||
@@ -13,15 +13,12 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Brokerages;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
@@ -32,8 +29,6 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Dictionary<Symbol, HashSet<Symbol>> _symbolsPerAlpha = new Dictionary<Symbol, HashSet<Symbol>>();
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
/// </summary>
|
||||
@@ -42,10 +37,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetStartDate(2018, 04, 04);
|
||||
SetEndDate(2018, 04, 06);
|
||||
|
||||
SetAlpha(new AlphaStreamAlphaModule());
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
|
||||
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
|
||||
|
||||
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
|
||||
new FuncSecuritySeeder(GetLastKnownPrices)));
|
||||
|
||||
@@ -55,77 +50,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
foreach (var portfolioState in data.Get<AlphaStreamsPortfolioState>().Values)
|
||||
{
|
||||
ProcessPortfolioState(portfolioState);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log($"OnOrderEvent: {orderEvent}");
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
changes.FilterCustomSecurities = false;
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
if (addedSecurity.Symbol.IsCustomDataType<AlphaStreamsPortfolioState>())
|
||||
{
|
||||
if (!_symbolsPerAlpha.ContainsKey(addedSecurity.Symbol))
|
||||
{
|
||||
_symbolsPerAlpha[addedSecurity.Symbol] = new HashSet<Symbol>();
|
||||
}
|
||||
// warmup alpha state, adding target securities
|
||||
ProcessPortfolioState(addedSecurity.Cache.GetData<AlphaStreamsPortfolioState>());
|
||||
}
|
||||
}
|
||||
|
||||
Log($"OnSecuritiesChanged: {changes}");
|
||||
}
|
||||
|
||||
private bool UsedBySomeAlpha(Symbol asset)
|
||||
{
|
||||
return _symbolsPerAlpha.Any(pair => pair.Value.Contains(asset));
|
||||
}
|
||||
|
||||
private void ProcessPortfolioState(AlphaStreamsPortfolioState portfolioState)
|
||||
{
|
||||
if (portfolioState == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var alphaId = portfolioState.Symbol;
|
||||
if (!_symbolsPerAlpha.TryGetValue(alphaId, out var currentSymbols))
|
||||
{
|
||||
_symbolsPerAlpha[alphaId] = currentSymbols = new HashSet<Symbol>();
|
||||
}
|
||||
|
||||
var newSymbols = new HashSet<Symbol>(currentSymbols.Count);
|
||||
foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions).Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>())
|
||||
{
|
||||
// only add it if it's not used by any alpha (already added check)
|
||||
if (newSymbols.Add(symbol) && !UsedBySomeAlpha(symbol))
|
||||
{
|
||||
AddSecurity(symbol, resolution: UniverseSettings.Resolution, extendedMarketHours: UniverseSettings.ExtendedMarketHours);
|
||||
}
|
||||
}
|
||||
_symbolsPerAlpha[alphaId] = newSymbols;
|
||||
|
||||
foreach (var symbol in currentSymbols.Where(symbol => !UsedBySomeAlpha(symbol)))
|
||||
{
|
||||
RemoveSecurity(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
|
||||
@@ -14,9 +14,11 @@
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
@@ -26,7 +28,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <summary>
|
||||
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
|
||||
/// </summary>
|
||||
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : AlphaStreamsBasicTemplateAlgorithm
|
||||
public class AlphaStreamsUniverseSelectionTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
@@ -36,6 +38,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetStartDate(2018, 04, 04);
|
||||
SetEndDate(2018, 04, 06);
|
||||
|
||||
SetAlpha(new AlphaStreamAlphaModule());
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
|
||||
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
|
||||
@@ -65,10 +68,20 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Orders.Fees;
|
||||
using QuantConnect.Data.Custom;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
using QuantConnect.Algorithm.Framework.Execution;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
using QuantConnect.Algorithm.Framework.Risk;
|
||||
using QuantConnect.Algorithm.Framework.Selection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp.Alphas
|
||||
{
|
||||
///<summary>
|
||||
/// This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
|
||||
/// generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
|
||||
/// regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
|
||||
/// to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
|
||||
/// estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
|
||||
/// estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
|
||||
/// based on volatility and rate deviation from its historic mean.
|
||||
///
|
||||
/// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
|
||||
/// sourced so the community and client funds can see an example of an alpha.
|
||||
///</summary>
|
||||
public class MortgageRateVolatilityAlgorithm : QCAlgorithm
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2017, 1, 1); //Set Start Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
|
||||
UniverseSettings.Resolution = Resolution.Daily;
|
||||
SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));
|
||||
|
||||
// Basket of 6 liquid real estate ETFs
|
||||
Func<string, Symbol> toSymbol = x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA);
|
||||
var realEstateETFs = new[] { "VNQ", "REET", "TAO", "FREL", "SRET", "HIPS" }.Select(toSymbol).ToArray();
|
||||
SetUniverseSelection(new ManualUniverseSelectionModel(realEstateETFs));
|
||||
|
||||
SetAlpha(new MortgageRateVolatilityAlphaModel(this));
|
||||
|
||||
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
|
||||
|
||||
SetExecution(new ImmediateExecutionModel());
|
||||
|
||||
SetRiskManagement(new NullRiskManagementModel());
|
||||
|
||||
}
|
||||
|
||||
private class MortgageRateVolatilityAlphaModel : AlphaModel
|
||||
{
|
||||
private readonly int _indicatorPeriod;
|
||||
private readonly Resolution _resolution;
|
||||
private readonly TimeSpan _insightDuration;
|
||||
private readonly int _deviations;
|
||||
private readonly double _insightMagnitude;
|
||||
private readonly Symbol _mortgageRate;
|
||||
private readonly SimpleMovingAverage _mortgageRateSma;
|
||||
private readonly StandardDeviation _mortgageRateStd;
|
||||
|
||||
public MortgageRateVolatilityAlphaModel(
|
||||
QCAlgorithm algorithm,
|
||||
int indicatorPeriod = 15,
|
||||
double insightMagnitude = 0.0005,
|
||||
int deviations = 2,
|
||||
Resolution resolution = Resolution.Daily
|
||||
)
|
||||
{
|
||||
// Add Quandl data for a Well's Fargo 30-year Fixed Rate mortgage
|
||||
_mortgageRate = algorithm.AddData<QuandlMortgagePriceColumns>("WFC/PR_GOV_30YFIXEDVA_APR").Symbol;
|
||||
_indicatorPeriod = indicatorPeriod;
|
||||
_resolution = resolution;
|
||||
_insightDuration = resolution.ToTimeSpan().Multiply(indicatorPeriod);
|
||||
_insightMagnitude = insightMagnitude;
|
||||
_deviations = deviations;
|
||||
|
||||
// Add indicators for the mortgage rate -- Standard Deviation and Simple Moving Average
|
||||
_mortgageRateStd = algorithm.STD(_mortgageRate, _indicatorPeriod, resolution);
|
||||
_mortgageRateSma = algorithm.SMA(_mortgageRate, _indicatorPeriod, resolution);
|
||||
|
||||
// Use a history call to warm-up the indicators
|
||||
WarmUpIndicators(algorithm);
|
||||
}
|
||||
|
||||
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
|
||||
{
|
||||
var insights = new List<Insight>();
|
||||
|
||||
// Return empty list if data slice doesn't contain monrtgage rate data
|
||||
if (!data.Keys.Contains(_mortgageRate))
|
||||
{
|
||||
return insights;
|
||||
}
|
||||
// Extract current mortgage rate, the current STD indicator value, and current SMA value
|
||||
var rate = data[_mortgageRate].Value;
|
||||
var deviation = _deviations * _mortgageRateStd;
|
||||
var sma = _mortgageRateSma;
|
||||
|
||||
// Loop through all Active Securities to emit insights
|
||||
foreach (var security in algorithm.ActiveSecurities.Keys)
|
||||
{
|
||||
// Mortgage rate Symbol will be in the collection, so skip it
|
||||
if (security == _mortgageRate)
|
||||
{
|
||||
return insights;
|
||||
}
|
||||
|
||||
// If volatility in mortgage rates is high, then we emit an Insight to sell
|
||||
if ((rate < sma - deviation) || (rate > sma + deviation))
|
||||
{
|
||||
insights.Add(Insight.Price(security, _insightDuration, InsightDirection.Down, _insightMagnitude));
|
||||
}
|
||||
|
||||
// If volatility in mortgage rates is low, then we emit an Insight to buy
|
||||
if ((rate < sma - (decimal)deviation/2) || (rate > sma + (decimal)deviation/2))
|
||||
{
|
||||
insights.Add(Insight.Price(security, _insightDuration, InsightDirection.Up, _insightMagnitude));
|
||||
}
|
||||
}
|
||||
|
||||
return insights;
|
||||
}
|
||||
|
||||
private void WarmUpIndicators(QCAlgorithm algorithm)
|
||||
{
|
||||
// Make a history call and update the indicators
|
||||
algorithm.History(new[] { _mortgageRate }, _indicatorPeriod, _resolution).PushThrough(bar =>
|
||||
{
|
||||
_mortgageRateSma.Update(bar.EndTime, bar.Value);
|
||||
_mortgageRateStd.Update(bar.EndTime, bar.Value);
|
||||
});
|
||||
}
|
||||
}
|
||||
public class QuandlMortgagePriceColumns : Quandl
|
||||
{
|
||||
public QuandlMortgagePriceColumns()
|
||||
|
||||
// Rename the Quandl object column to the data we want, which is the 'Value' column
|
||||
// of the CSV that our API call returns
|
||||
: base(valueColumnName: "Value")
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -339,7 +339,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "7f99e1a8ce4675a1e8bbe1ba45967ccd"}
|
||||
{"OrderListHash", "f67306bc706a2cf66288f1cadf6148ed"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,10 +86,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "93.443%"},
|
||||
{"Compounding Annual Return", "93.340%"},
|
||||
{"Drawdown", "1.100%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0.847%"},
|
||||
{"Net Profit", "0.846%"},
|
||||
{"Sharpe Ratio", "6.515"},
|
||||
{"Probabilistic Sharpe Ratio", "67.535%"},
|
||||
{"Loss Rate", "0%"},
|
||||
@@ -102,14 +102,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "6.515"},
|
||||
{"Tracking Error", "0.11"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.52"},
|
||||
{"Total Fees", "$1.20"},
|
||||
{"Estimated Strategy Capacity", "$8600000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.124"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "78.376"},
|
||||
{"Return Over Maximum Drawdown", "78.222"},
|
||||
{"Portfolio Turnover", "0.124"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
|
||||
166
Algorithm.CSharp/BasicTemplateContinuousFutureAlgorithm.cs
Normal file
166
Algorithm.CSharp/BasicTemplateContinuousFutureAlgorithm.cs
Normal file
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
using Futures = QuantConnect.Securities.Futures;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Basic Continuous Futures Template Algorithm
|
||||
/// </summary>
|
||||
public class BasicTemplateContinuousFutureAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Future _continuousContract;
|
||||
private Security _currentContract;
|
||||
private SimpleMovingAverage _fast;
|
||||
private SimpleMovingAverage _slow;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
|
||||
_fast = SMA(_continuousContract.Symbol, 3, Resolution.Daily);
|
||||
_slow = SMA(_continuousContract.Symbol, 10, Resolution.Daily);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
Debug($"{Time} - SymbolChanged event: {changedEvent}");
|
||||
if (Time.TimeOfDay != TimeSpan.Zero)
|
||||
{
|
||||
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
|
||||
}
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
if(_fast > _slow)
|
||||
{
|
||||
_currentContract = Securities[_continuousContract.Mapped];
|
||||
Buy(_currentContract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
else if(_fast < _slow)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
|
||||
if (_currentContract != null && _currentContract.Symbol != _continuousContract.Mapped)
|
||||
{
|
||||
Log($"{Time} - rolling position from {_currentContract.Symbol} to {_continuousContract.Mapped}");
|
||||
|
||||
var currentPositionSize = _currentContract.Holdings.Quantity;
|
||||
Liquidate(_currentContract.Symbol);
|
||||
Buy(_continuousContract.Mapped, currentPositionSize);
|
||||
_currentContract = Securities[_continuousContract.Mapped];
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Debug($"{orderEvent}");
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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.00%"},
|
||||
{"Compounding Annual Return", "-0.007%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.004%"},
|
||||
{"Sharpe Ratio", "-0.369"},
|
||||
{"Probabilistic Sharpe Ratio", "10.640%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.751"},
|
||||
{"Tracking Error", "0.082"},
|
||||
{"Treynor Ratio", "-0.616"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-0.738"},
|
||||
{"Portfolio Turnover", "0.01"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "bd7fbe57802dfedb36c85609b7234016"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Securities.Future;
|
||||
@@ -64,6 +65,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
var benchmark = AddEquity("SPY");
|
||||
SetBenchmark(benchmark.Symbol);
|
||||
|
||||
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
|
||||
SetSecurityInitializer(security => seeder.SeedSecurity(security));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -72,6 +76,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
|
||||
{
|
||||
Debug($"{Time} - SymbolChanged event: {changedEvent}");
|
||||
if (Time.TimeOfDay != TimeSpan.Zero)
|
||||
{
|
||||
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
|
||||
}
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
foreach(var chain in slice.FutureChains)
|
||||
@@ -112,6 +125,19 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
var maintenanceIntraday = futureMarginModel.MaintenanceIntradayMarginRequirement;
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
if (addedSecurity.Symbol.SecurityType == SecurityType.Future
|
||||
&& !addedSecurity.Symbol.IsCanonical()
|
||||
&& !addedSecurity.HasData)
|
||||
{
|
||||
throw new Exception($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
|
||||
160
Algorithm.CSharp/BasicTemplateFuturesDailyAlgorithm.cs
Normal file
160
Algorithm.CSharp/BasicTemplateFuturesDailyAlgorithm.cs
Normal file
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add futures with daily resolution.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="futures" />
|
||||
public class BasicTemplateFuturesDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _contractSymbol;
|
||||
protected virtual Resolution Resolution => Resolution.Daily;
|
||||
|
||||
// S&P 500 EMini futures
|
||||
private const string RootSP500 = Futures.Indices.SP500EMini;
|
||||
|
||||
// Gold futures
|
||||
private const string RootGold = Futures.Metals.Gold;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 08);
|
||||
SetEndDate(2014, 10, 10);
|
||||
SetCash(1000000);
|
||||
|
||||
var futureSP500 = AddFuture(RootSP500, Resolution);
|
||||
var futureGold = AddFuture(RootGold, Resolution);
|
||||
|
||||
// set our expiry filter for this futures chain
|
||||
// SetFilter method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
futureSP500.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
|
||||
futureGold.SetFilter(0, 182);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
foreach(var chain in slice.FutureChains)
|
||||
{
|
||||
// find the front contract expiring no earlier than in 90 days
|
||||
var contract = (
|
||||
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
|
||||
where futuresContract.Expiry > Time.Date.AddDays(90)
|
||||
select futuresContract
|
||||
).FirstOrDefault();
|
||||
|
||||
// if found, trade it
|
||||
if (contract != null && IsMarketOpen(contract.Symbol))
|
||||
{
|
||||
_contractSymbol = contract.Symbol;
|
||||
MarketOrder(_contractSymbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
|
||||
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (Time.TimeOfDay != TimeSpan.Zero)
|
||||
{
|
||||
throw new Exception($"{Time} unexpected symbol changed event {changedEvent}!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "92"},
|
||||
{"Average Win", "0.08%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-0.450%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "-0.824"},
|
||||
{"Net Profit", "-0.453%"},
|
||||
{"Sharpe Ratio", "-1.803"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "98%"},
|
||||
{"Win Rate", "2%"},
|
||||
{"Profit-Loss Ratio", "7.09"},
|
||||
{"Alpha", "-0.003"},
|
||||
{"Beta", "-0.001"},
|
||||
{"Annual Standard Deviation", "0.002"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.394"},
|
||||
{"Tracking Error", "0.089"},
|
||||
{"Treynor Ratio", "4.298"},
|
||||
{"Total Fees", "$170.20"},
|
||||
{"Estimated Strategy Capacity", "$36000.00"},
|
||||
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
|
||||
{"Fitness Score", "0.009"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.8"},
|
||||
{"Return Over Maximum Drawdown", "-0.992"},
|
||||
{"Portfolio Turnover", "0.025"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "09b2f274fa2385597a803e58b784f675"}
|
||||
};
|
||||
}
|
||||
}
|
||||
96
Algorithm.CSharp/BasicTemplateFuturesHourlyAlgorithm.cs
Normal file
96
Algorithm.CSharp/BasicTemplateFuturesHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regressions tests the BasicTemplateFuturesDailyAlgorithm with hour data
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="futures" />
|
||||
public class BasicTemplateFuturesHourlyAlgorithm : BasicTemplateFuturesDailyAlgorithm
|
||||
{
|
||||
private Symbol _contractSymbol;
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "1988"},
|
||||
{"Average Win", "0.01%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-4.120%"},
|
||||
{"Drawdown", "4.200%"},
|
||||
{"Expectancy", "-0.870"},
|
||||
{"Net Profit", "-4.150%"},
|
||||
{"Sharpe Ratio", "-6.061"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "97%"},
|
||||
{"Win Rate", "3%"},
|
||||
{"Profit-Loss Ratio", "2.92"},
|
||||
{"Alpha", "-0.027"},
|
||||
{"Beta", "-0.006"},
|
||||
{"Annual Standard Deviation", "0.005"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.66"},
|
||||
{"Tracking Error", "0.089"},
|
||||
{"Treynor Ratio", "4.919"},
|
||||
{"Total Fees", "$3677.80"},
|
||||
{"Estimated Strategy Capacity", "$2000.00"},
|
||||
{"Lowest Capacity Asset", "ES VP274HSU1AF5"},
|
||||
{"Fitness Score", "0.128"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-6.856"},
|
||||
{"Return Over Maximum Drawdown", "-0.995"},
|
||||
{"Portfolio Turnover", "0.648"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "87d2b127c9859cad9d2c65ac9d76deb5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,36 +30,39 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="indexes" />
|
||||
public class BasicTemplateIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _spx;
|
||||
private Symbol _spxOption;
|
||||
protected Symbol Spx;
|
||||
protected Symbol SpxOption;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
|
||||
protected virtual Resolution Resolution => Resolution.Minute;
|
||||
protected virtual int StartDay => 4;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
SetEndDate(2021, 1, 15);
|
||||
SetStartDate(2021, 1, StartDay);
|
||||
SetEndDate(2021, 1, 18);
|
||||
SetCash(1000000);
|
||||
|
||||
// Use indicator for signal; but it cannot be traded
|
||||
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
|
||||
Spx = AddIndex("SPX", Resolution).Symbol;
|
||||
|
||||
// Trade on SPX ITM calls
|
||||
_spxOption = QuantConnect.Symbol.CreateOption(
|
||||
_spx,
|
||||
SpxOption = QuantConnect.Symbol.CreateOption(
|
||||
Spx,
|
||||
Market.USA,
|
||||
OptionStyle.European,
|
||||
OptionRight.Call,
|
||||
3200m,
|
||||
new DateTime(2021, 1, 15));
|
||||
|
||||
AddIndexOptionContract(_spxOption, Resolution.Minute);
|
||||
AddIndexOptionContract(SpxOption, Resolution);
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
_emaFast = EMA(_spx, 200);
|
||||
_emaSlow = EMA(Spx, 80);
|
||||
_emaFast = EMA(Spx, 200);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,7 +70,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!slice.Bars.ContainsKey(_spx) || !slice.Bars.ContainsKey(_spxOption))
|
||||
if (!slice.Bars.ContainsKey(Spx) || !slice.Bars.ContainsKey(SpxOption))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -80,7 +83,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
if (_emaFast > _emaSlow)
|
||||
{
|
||||
SetHoldings(_spxOption, 1);
|
||||
SetHoldings(SpxOption, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -90,7 +93,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio[_spx].TotalSaleVolume > 0)
|
||||
if (Portfolio[Spx].TotalSaleVolume > 0)
|
||||
{
|
||||
throw new Exception("Index is not tradable.");
|
||||
}
|
||||
@@ -99,46 +102,46 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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;
|
||||
public virtual 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, Language.Python };
|
||||
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <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>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-53.10%"},
|
||||
{"Compounding Annual Return", "-96.172%"},
|
||||
{"Compounding Annual Return", "-92.544%"},
|
||||
{"Drawdown", "10.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-9.915%"},
|
||||
{"Sharpe Ratio", "-4.068"},
|
||||
{"Probabilistic Sharpe Ratio", "0.055%"},
|
||||
{"Sharpe Ratio", "-3.845"},
|
||||
{"Probabilistic Sharpe Ratio", "0.053%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.745"},
|
||||
{"Beta", "0.432"},
|
||||
{"Annual Standard Deviation", "0.126"},
|
||||
{"Annual Variance", "0.016"},
|
||||
{"Information Ratio", "-7.972"},
|
||||
{"Tracking Error", "0.132"},
|
||||
{"Treynor Ratio", "-1.189"},
|
||||
{"Alpha", "-0.558"},
|
||||
{"Beta", "0.313"},
|
||||
{"Annual Standard Deviation", "0.112"},
|
||||
{"Annual Variance", "0.013"},
|
||||
{"Information Ratio", "-6.652"},
|
||||
{"Tracking Error", "0.125"},
|
||||
{"Treynor Ratio", "-1.379"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$14000000.00"},
|
||||
{"Estimated Strategy Capacity", "$13000000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.044"},
|
||||
{"Fitness Score", "0.039"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.96"},
|
||||
{"Return Over Maximum Drawdown", "-10.171"},
|
||||
{"Portfolio Turnover", "0.34"},
|
||||
{"Sortino Ratio", "-1.763"},
|
||||
{"Return Over Maximum Drawdown", "-9.371"},
|
||||
{"Portfolio Turnover", "0.278"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -152,7 +155,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "52521ab779446daf4d38a7c9bbbdd893"}
|
||||
{"OrderListHash", "0668385036aba3e95127607dfc2f1a59"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
108
Algorithm.CSharp/BasicTemplateIndexDailyAlgorithm.cs
Normal file
108
Algorithm.CSharp/BasicTemplateIndexDailyAlgorithm.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an Index algorithm with Daily data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexDailyAlgorithm : BasicTemplateIndexAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Daily;
|
||||
protected override int StartDay => 1;
|
||||
|
||||
// two complete weeks starting from the 5th plus the 18th bar
|
||||
protected virtual int ExpectedBarCount => 2 * 5 + 1;
|
||||
protected int BarCounter = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Purchase a contract when we are not invested, liquidate otherwise
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
// SPX Index is not tradable, but we can trade an option
|
||||
MarketOrder(SpxOption, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
|
||||
// Count how many slices we receive with SPX data in it to assert later
|
||||
if (slice.ContainsKey(Spx))
|
||||
{
|
||||
BarCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (BarCounter != ExpectedBarCount)
|
||||
{
|
||||
throw new ArgumentException($"Bar Count {BarCounter} is not expected count of {ExpectedBarCount}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override 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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "9"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-39.42%"},
|
||||
{"Compounding Annual Return", "394.321%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "8.219%"},
|
||||
{"Sharpe Ratio", "6.812"},
|
||||
{"Probabilistic Sharpe Ratio", "91.380%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "2.236"},
|
||||
{"Beta", "-1.003"},
|
||||
{"Annual Standard Deviation", "0.317"},
|
||||
{"Annual Variance", "0.101"},
|
||||
{"Information Ratio", "5.805"},
|
||||
{"Tracking Error", "0.359"},
|
||||
{"Treynor Ratio", "-2.153"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.027"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "1776.081"},
|
||||
{"Portfolio Turnover", "0.027"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "474e8e0e28ee84c869f8c69ec3efe371"}
|
||||
};
|
||||
}
|
||||
}
|
||||
72
Algorithm.CSharp/BasicTemplateIndexHourlyAlgorithm.cs
Normal file
72
Algorithm.CSharp/BasicTemplateIndexHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an Index algorithm with Hourly data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexHourlyAlgorithm : BasicTemplateIndexDailyAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
protected override int ExpectedBarCount => base.ExpectedBarCount * 8;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override 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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "70"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.23%"},
|
||||
{"Compounding Annual Return", "-34.441%"},
|
||||
{"Drawdown", "2.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-2.028%"},
|
||||
{"Sharpe Ratio", "-11.139"},
|
||||
{"Probabilistic Sharpe Ratio", "0.000%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.269"},
|
||||
{"Beta", "0.086"},
|
||||
{"Annual Standard Deviation", "0.023"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.624"},
|
||||
{"Tracking Error", "0.094"},
|
||||
{"Treynor Ratio", "-3.042"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$310000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-14.51"},
|
||||
{"Return Over Maximum Drawdown", "-17.213"},
|
||||
{"Portfolio Turnover", "0.299"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "3eb56c551f20e2ffa1c56c47c5ee6667"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,20 +30,22 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
private Symbol _spx;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
protected virtual Resolution Resolution => Resolution.Minute;
|
||||
protected virtual int StartDay => 4;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2021, 1, 4);
|
||||
SetStartDate(2021, 1, StartDay);
|
||||
SetEndDate(2021, 2, 1);
|
||||
SetCash(1000000);
|
||||
|
||||
// Use indicator for signal; but it cannot be traded.
|
||||
// We will instead trade on SPX options
|
||||
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
|
||||
var spxOptions = AddIndexOption(_spx, Resolution.Minute);
|
||||
_spx = AddIndex("SPX", Resolution).Symbol;
|
||||
var spxOptions = AddIndexOption(_spx, Resolution);
|
||||
spxOptions.SetFilter(filterFunc => filterFunc.CallsOnly());
|
||||
|
||||
_emaSlow = EMA(_spx, 80);
|
||||
@@ -122,17 +124,17 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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; } = false;
|
||||
public virtual bool CanRunLocally { get; } = false;
|
||||
|
||||
/// <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, Language.Python };
|
||||
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <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>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "8220"},
|
||||
{"Average Win", "0.00%"},
|
||||
|
||||
117
Algorithm.CSharp/BasicTemplateIndexOptionsDailyAlgorithm.cs
Normal file
117
Algorithm.CSharp/BasicTemplateIndexOptionsDailyAlgorithm.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an IndexOptions algorithm with Daily data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexOptionsDailyAlgorithm : BasicTemplateIndexOptionsAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Daily;
|
||||
protected override int StartDay => 1;
|
||||
|
||||
/// <summary>
|
||||
/// Index EMA Cross trading index options of the index.
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
foreach (var chain in slice.OptionChains.Values)
|
||||
{
|
||||
// Select the contract with the lowest AskPrice
|
||||
var contract = chain.Contracts.OrderBy(x => x.Value.AskPrice).FirstOrDefault().Value;
|
||||
|
||||
if (contract == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override 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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "9"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.01%"},
|
||||
{"Compounding Annual Return", "-0.091%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.008%"},
|
||||
{"Sharpe Ratio", "-4.033"},
|
||||
{"Probabilistic Sharpe Ratio", "0.013%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.001"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.447"},
|
||||
{"Tracking Error", "0.136"},
|
||||
{"Treynor Ratio", "-4.612"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-50718.291"},
|
||||
{"Return Over Maximum Drawdown", "-11.386"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "5f5df233d68d9115a0d81785de54e71d"}
|
||||
};
|
||||
}
|
||||
}
|
||||
87
Algorithm.CSharp/BasicTemplateIndexOptionsHourlyAlgorithm.cs
Normal file
87
Algorithm.CSharp/BasicTemplateIndexOptionsHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression for running an IndexOptions algorithm with Hourly data
|
||||
/// </summary>
|
||||
public class BasicTemplateIndexOptionsHourlyAlgorithm : BasicTemplateIndexOptionsDailyAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override 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 override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "70"},
|
||||
{"Average Win", "0.00%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0.000"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "36.504%"},
|
||||
{"Loss Rate", "97%"},
|
||||
{"Win Rate", "3%"},
|
||||
{"Profit-Loss Ratio", "34.00"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "-0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.449"},
|
||||
{"Tracking Error", "0.138"},
|
||||
{"Treynor Ratio", "-0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "f21910eb98ceaa39e02020de95354d86"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
@@ -26,20 +27,21 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
/// <meta name="tag" content="trading and orders" />
|
||||
public class BasicTemplateIndiaAlgorithm : QCAlgorithm
|
||||
public class BasicTemplateIndiaAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
/// <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(2003, 10, 07); //Set Start Date
|
||||
SetEndDate(2003, 10, 11); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
SetAccountCurrency("INR"); //Set Account Currency
|
||||
SetStartDate(2019, 1, 23); //Set Start Date
|
||||
SetEndDate(2019, 10, 31); //Set End Date
|
||||
SetCash(100000); //Set Strategy Cash
|
||||
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
// Equities Resolutions: Tick, Second, Minute, Hour, Daily.
|
||||
AddEquity("UNIONBANK", Resolution.Second, Market.India);
|
||||
AddEquity("YESBANK", Resolution.Minute, Market.India);
|
||||
|
||||
//Set Order Prperties as per the requirements for order placement
|
||||
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
|
||||
@@ -58,7 +60,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
var marketTicket = MarketOrder("UNIONBANK", 1);
|
||||
var marketTicket = MarketOrder("YESBANK", 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,60 +75,60 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <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; } = false;
|
||||
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 };
|
||||
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <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", "3"},
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-1.01%"},
|
||||
{"Compounding Annual Return", "261.134%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "1.655%"},
|
||||
{"Sharpe Ratio", "8.505"},
|
||||
{"Probabilistic Sharpe Ratio", "66.840%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-0.010%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.008%"},
|
||||
{"Sharpe Ratio", "-1.183"},
|
||||
{"Probabilistic Sharpe Ratio", "0.001%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.091"},
|
||||
{"Beta", "1.006"},
|
||||
{"Annual Standard Deviation", "0.224"},
|
||||
{"Annual Variance", "0.05"},
|
||||
{"Information Ratio", "-33.445"},
|
||||
{"Tracking Error", "0.002"},
|
||||
{"Treynor Ratio", "1.893"},
|
||||
{"Total Fees", "$10.32"},
|
||||
{"Estimated Strategy Capacity", "$27000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.747"},
|
||||
{"Kelly Criterion Estimate", "38.796"},
|
||||
{"Kelly Criterion Probability Value", "0.228"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "85.095"},
|
||||
{"Portfolio Turnover", "0.747"},
|
||||
{"Total Insights Generated", "100"},
|
||||
{"Total Insights Closed", "99"},
|
||||
{"Total Insights Analysis Completed", "99"},
|
||||
{"Long Insight Count", "100"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.183"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$6.00"},
|
||||
{"Estimated Strategy Capacity", "$61000000000.00"},
|
||||
{"Lowest Capacity Asset", "YESBANK UL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.247"},
|
||||
{"Return Over Maximum Drawdown", "-1.104"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$135639.1761"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$21852.9784"},
|
||||
{"Mean Population Estimated Insight Value", "$220.7372"},
|
||||
{"Mean Population Direction", "53.5354%"},
|
||||
{"Mean Population Magnitude", "53.5354%"},
|
||||
{"Rolling Averaged Population Direction", "58.2788%"},
|
||||
{"Rolling Averaged Population Magnitude", "58.2788%"},
|
||||
{"OrderListHash", "ad2216297c759d8e5aef48ff065f8919"}
|
||||
{"Estimated Monthly Alpha Value", "₹0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "₹0"},
|
||||
{"Mean Population Estimated Insight Value", "₹0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6cc69218edd7bd461678b9ee0c575db5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
158
Algorithm.CSharp/BasicTemplateIndiaIndexAlgorithm.cs
Normal file
158
Algorithm.CSharp/BasicTemplateIndiaIndexAlgorithm.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add index asset types.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="benchmarks" />
|
||||
/// <meta name="tag" content="indexes" />
|
||||
public class BasicTemplateIndiaIndexAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
protected Symbol Nifty;
|
||||
protected Symbol NiftyETF;
|
||||
private ExponentialMovingAverage _emaSlow;
|
||||
private ExponentialMovingAverage _emaFast;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize your algorithm and add desired assets.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetAccountCurrency("INR"); //Set Account Currency
|
||||
SetStartDate(2019, 1, 1); //Set End Date
|
||||
SetEndDate(2019, 1, 5); //Set End Date
|
||||
SetCash(1000000); //Set Strategy Cash
|
||||
|
||||
// Use indicator for signal; but it cannot be traded
|
||||
Nifty = AddIndex("NIFTY50", Resolution.Minute, Market.India).Symbol;
|
||||
|
||||
//Trade Index based ETF
|
||||
NiftyETF = AddEquity("JUNIORBEES", Resolution.Minute, Market.India).Symbol;
|
||||
|
||||
//Set Order Prperties as per the requirements for order placement
|
||||
DefaultOrderProperties = new IndiaOrderProperties(exchange: Exchange.NSE);
|
||||
|
||||
_emaSlow = EMA(Nifty, 80);
|
||||
_emaFast = EMA(Nifty, 200);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Index EMA Cross trading underlying.
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!slice.Bars.ContainsKey(Nifty) || !slice.Bars.ContainsKey(NiftyETF))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Warm up indicators
|
||||
if (!_emaSlow.IsReady)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_emaFast > _emaSlow)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
var marketTicket = MarketOrder(NiftyETF, 1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio[Nifty].TotalSaleVolume > 0)
|
||||
{
|
||||
throw new Exception("Index is not tradable.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0.00%"},
|
||||
{"Compounding Annual Return", "-0.395%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.004%"},
|
||||
{"Sharpe Ratio", "-23.595"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-23.595"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$36.00"},
|
||||
{"Estimated Strategy Capacity", "$74000.00"},
|
||||
{"Lowest Capacity Asset", "JUNIORBEES UL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-29.6"},
|
||||
{"Return Over Maximum Drawdown", "-123.624"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "₹0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "₹0"},
|
||||
{"Mean Population Estimated Insight Value", "₹0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "4637f26543287548b28a3c296db055d3"}
|
||||
};
|
||||
}
|
||||
}
|
||||
171
Algorithm.CSharp/BasicTemplateOptionsDailyAlgorithm.cs
Normal file
171
Algorithm.CSharp/BasicTemplateOptionsDailyAlgorithm.cs
Normal file
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add options for a given underlying equity security.
|
||||
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
|
||||
/// can inspect the option chain to pick a specific option contract to trade.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class BasicTemplateOptionsDailyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "GOOG";
|
||||
public Symbol OptionSymbol;
|
||||
private bool _optionExpired;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 23);
|
||||
SetEndDate(2016, 1, 20);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker, Resolution.Daily);
|
||||
var option = AddOption(UnderlyingTicker, Resolution.Daily);
|
||||
OptionSymbol = option.Symbol;
|
||||
|
||||
option.SetFilter(x => x.CallsOnly().Strikes(0, 1).Expiration(0, 30));
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
SetBenchmark(equity.Symbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
|
||||
{
|
||||
// Grab us the contract nearest expiry that is not today
|
||||
var contractsByExpiration = chain.Where(x => x.Expiry != Time.Date).OrderBy(x => x.Expiry);
|
||||
var contract = contractsByExpiration.FirstOrDefault();
|
||||
|
||||
if (contract != null && IsMarketOpen(contract.Symbol))
|
||||
{
|
||||
// if found, trade it
|
||||
MarketOrder(contract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
|
||||
// Check for our expected OTM option expiry
|
||||
if (orderEvent.Message == "OTM")
|
||||
{
|
||||
// Assert it is at midnight (5AM UTC)
|
||||
if (orderEvent.UtcTime != new DateTime(2016, 1, 16, 5, 0, 0))
|
||||
{
|
||||
throw new ArgumentException($"Expiry event was not at the correct time, {orderEvent.UtcTime}");
|
||||
}
|
||||
|
||||
_optionExpired = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
// Assert we had our option expire and fill a liquidation order
|
||||
if (_optionExpired != true)
|
||||
{
|
||||
throw new ArgumentException("Algorithm did not process the option expiration like expected");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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", "-1.31%"},
|
||||
{"Compounding Annual Return", "-15.304%"},
|
||||
{"Drawdown", "1.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-1.311%"},
|
||||
{"Sharpe Ratio", "-3.31"},
|
||||
{"Probabilistic Sharpe Ratio", "0.035%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.034"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-3.31"},
|
||||
{"Tracking Error", "0.034"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$18000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV W78ZFMML01JA|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.496"},
|
||||
{"Return Over Maximum Drawdown", "-11.673"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "c6d089f1fb86379c74a7413a9c2f8553"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 28);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker);
|
||||
@@ -104,14 +104,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Average Loss", "-0.40%"},
|
||||
{"Compounding Annual Return", "-21.622%"},
|
||||
{"Drawdown", "0.300%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.311%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
@@ -124,12 +124,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Fees", "$1.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Fitness Score", "0.188"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-73.268"},
|
||||
{"Portfolio Turnover", "0.376"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -143,7 +143,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "92d8a50efe230524512404dab66b19dd"}
|
||||
{"OrderListHash", "452e7a36e0a95e33d3457a908add3ead"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
UniverseSettings.Resolution = Resolution.Minute;
|
||||
|
||||
SetStartDate(2014, 06, 05);
|
||||
SetEndDate(2014, 06, 06);
|
||||
SetEndDate(2014, 06, 09);
|
||||
SetCash(100000);
|
||||
|
||||
// set framework models
|
||||
@@ -142,47 +142,47 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Average Win", "0.14%"},
|
||||
{"Average Loss", "-0.28%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Drawdown", "385.400%"},
|
||||
{"Expectancy", "-0.249"},
|
||||
{"Net Profit", "-386.489%"},
|
||||
{"Sharpe Ratio", "-0.033"},
|
||||
{"Probabilistic Sharpe Ratio", "1.235%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.50"},
|
||||
{"Alpha", "-95.983"},
|
||||
{"Beta", "263.726"},
|
||||
{"Annual Standard Deviation", "30.617"},
|
||||
{"Annual Variance", "937.371"},
|
||||
{"Information Ratio", "-0.044"},
|
||||
{"Tracking Error", "30.604"},
|
||||
{"Treynor Ratio", "-0.004"},
|
||||
{"Total Fees", "$3.00"},
|
||||
{"Estimated Strategy Capacity", "$74000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL 2ZQGWTSSZ0WLI|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.168"},
|
||||
{"Kelly Criterion Estimate", "0.327"},
|
||||
{"Kelly Criterion Probability Value", "1"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "26"},
|
||||
{"Return Over Maximum Drawdown", "0"},
|
||||
{"Portfolio Turnover", "0.224"},
|
||||
{"Total Insights Generated", "28"},
|
||||
{"Total Insights Closed", "24"},
|
||||
{"Total Insights Analysis Completed", "24"},
|
||||
{"Long Insight Count", "26"},
|
||||
{"Long Insight Count", "28"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$31.01809"},
|
||||
{"Estimated Monthly Alpha Value", "$13.64796"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$1.89555"},
|
||||
{"Mean Population Estimated Insight Value", "$0.07898125"},
|
||||
{"Mean Population Direction", "50%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "50.0482%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ce06ddfa4b2ffeb666a8910ac8836992"}
|
||||
{"OrderListHash", "87603bd45898dd9c456745fa51f989a5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
158
Algorithm.CSharp/BasicTemplateOptionsHourlyAlgorithm.cs
Normal file
158
Algorithm.CSharp/BasicTemplateOptionsHourlyAlgorithm.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This example demonstrates how to add options for a given underlying equity security.
|
||||
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
|
||||
/// can inspect the option chain to pick a specific option contract to trade.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="filter selection" />
|
||||
public class BasicTemplateOptionsHourlyAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string UnderlyingTicker = "AAPL";
|
||||
public Symbol OptionSymbol;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2014, 6, 6);
|
||||
SetEndDate(2014, 6, 9);
|
||||
SetCash(100000);
|
||||
|
||||
var equity = AddEquity(UnderlyingTicker, Resolution.Hour);
|
||||
var option = AddOption(UnderlyingTicker, Resolution.Hour);
|
||||
OptionSymbol = option.Symbol;
|
||||
|
||||
// set our strike/expiry filter for this option chain
|
||||
option.SetFilter(u => u.Strikes(-2, +2)
|
||||
// Expiration method accepts TimeSpan objects or integer for days.
|
||||
// The following statements yield the same filtering criteria
|
||||
.Expiration(0, 180));
|
||||
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
SetBenchmark(equity.Symbol);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
|
||||
{
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
|
||||
{
|
||||
// we find at the money (ATM) put contract with farthest expiration
|
||||
var atmContract = chain
|
||||
.OrderByDescending(x => x.Expiry)
|
||||
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
|
||||
.ThenByDescending(x => x.Right)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (atmContract != null && IsMarketOpen(atmContract.Symbol))
|
||||
{
|
||||
// if found, trade it
|
||||
MarketOrder(atmContract.Symbol, 1);
|
||||
MarketOnCloseOrder(atmContract.Symbol, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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", "4"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.07%"},
|
||||
{"Compounding Annual Return", "-12.496%"},
|
||||
{"Drawdown", "0.200%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.134%"},
|
||||
{"Sharpe Ratio", "-8.839"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.083"},
|
||||
{"Beta", "-0.054"},
|
||||
{"Annual Standard Deviation", "0.008"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-18.699"},
|
||||
{"Tracking Error", "0.155"},
|
||||
{"Treynor Ratio", "1.296"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Estimated Strategy Capacity", "$1000.00"},
|
||||
{"Lowest Capacity Asset", "AAPL 2ZTXYMUAHCIAU|AAPL R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.04"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-118.28"},
|
||||
{"Portfolio Turnover", "0.081"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "81e8a822d43de2165c1d3f52964ec312"}
|
||||
};
|
||||
}
|
||||
}
|
||||
85
Algorithm.CSharp/BinanceCashAccountFeeRegressionAlgorithm.cs
Normal file
85
Algorithm.CSharp/BinanceCashAccountFeeRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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 QuantConnect.Brokerages;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Binance cash account regression algorithm, reproduces issue https://github.com/QuantConnect/Lean/issues/6123
|
||||
/// </summary>
|
||||
public class BinanceCashAccountFeeRegressionAlgorithm : CryptoCashAccountFeeRegressionAlgorithm
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetAccountCurrency("USDT");
|
||||
SetStartDate(2018, 05, 02);
|
||||
SetEndDate(2018, 05, 03);
|
||||
BrokerageName = BrokerageName.Binance;
|
||||
Pair = "BTCUSDT";
|
||||
base.Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new()
|
||||
{
|
||||
{"Total Trades", "49"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$45.62"},
|
||||
{"Estimated Strategy Capacity", "$220000.00"},
|
||||
{"Lowest Capacity Asset", "BTCUSDT 18N"},
|
||||
{"Fitness Score", "0.208"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "26.189"},
|
||||
{"Portfolio Turnover", "0.208"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "USDT0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "USDT0"},
|
||||
{"Mean Population Estimated Insight Value", "USDT0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "7417649395922ff3791471b4f3b5c021"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 QuantConnect.Brokerages;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Bitfinex cash account regression algorithm, reproduces issue https://github.com/QuantConnect/Lean/issues/6123
|
||||
/// </summary>
|
||||
public class BitfinexCashAccountFeeRegressionAlgorithm : CryptoCashAccountFeeRegressionAlgorithm
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2013, 10, 02);
|
||||
SetEndDate(2013, 10, 03);
|
||||
BrokerageName = BrokerageName.Bitfinex;
|
||||
Pair = "BTCUSD";
|
||||
base.Initialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new()
|
||||
{
|
||||
{"Total Trades", "49"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.13"},
|
||||
{"Estimated Strategy Capacity", "$2000.00"},
|
||||
{"Lowest Capacity Asset", "BTCUSD E3"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.002"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "7f892f0c42d8826ff770ee602fe207a2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetEndDate(2019, 2, 21);
|
||||
SetCash("EUR", 100000);
|
||||
|
||||
_symbol = AddCfd("DE30EUR", Resolution.Minute, Market.Oanda).Symbol;
|
||||
_symbol = AddCfd("DE30EUR").Symbol;
|
||||
|
||||
SetBenchmark(_symbol);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Back Month Raw Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousBackMonthRawFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastDateLog;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.Raw,
|
||||
dataMappingMode: DataMappingMode.FirstDayMonth,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
}
|
||||
|
||||
/// <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 (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"SymbolChanged event: {changedEvent}");
|
||||
|
||||
var currentExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
// +4 months cause we are actually using the back month, es is quarterly contract
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1 + 4));
|
||||
|
||||
if (currentExpiration != frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
|
||||
$" @ {Time} it should be AT front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_lastDateLog.Month != Time.Month && _continuousContract.HasData)
|
||||
{
|
||||
_lastDateLog = Time;
|
||||
|
||||
Log($"{Time}- {Securities[_continuousContract.Symbol].GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1.16%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.311%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.159%"},
|
||||
{"Sharpe Ratio", "0.753"},
|
||||
{"Probabilistic Sharpe Ratio", "39.483%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.006"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.732"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.165"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$3900000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.007"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.563"},
|
||||
{"Return Over Maximum Drawdown", "1.87"},
|
||||
{"Portfolio Turnover", "0.01"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "8aa2ed1319e8bb5beb403476a5aebfef"}
|
||||
};
|
||||
}
|
||||
}
|
||||
197
Algorithm.CSharp/ContinuousFutureBackMonthRegressionAlgorithm.cs
Normal file
197
Algorithm.CSharp/ContinuousFutureBackMonthRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Back Month #1 Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureBackMonthRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastDateLog;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
try
|
||||
{
|
||||
AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsPanamaCanal,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 5
|
||||
);
|
||||
throw new Exception("Expected out of rage exception. We don't support that many back months");
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
// expected
|
||||
}
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsPanamaCanal,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
}
|
||||
|
||||
/// <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 (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"SymbolChanged event: {changedEvent}");
|
||||
|
||||
var backMonthExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
|
||||
if (backMonthExpiration <= frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {backMonthExpiration}" +
|
||||
$" @ {Time} it should be AFTER front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_lastDateLog.Month != Time.Month && _continuousContract.HasData)
|
||||
{
|
||||
_lastDateLog = Time;
|
||||
|
||||
Log($"{Time}- {Securities[_continuousContract.Symbol].GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "3"},
|
||||
{"Average Win", "1.16%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.229%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.118%"},
|
||||
{"Sharpe Ratio", "0.726"},
|
||||
{"Probabilistic Sharpe Ratio", "38.511%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.007"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.74"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.159"},
|
||||
{"Total Fees", "$5.55"},
|
||||
{"Estimated Strategy Capacity", "$290000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.009"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.498"},
|
||||
{"Return Over Maximum Drawdown", "1.803"},
|
||||
{"Portfolio Turnover", "0.014"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "e669103cc598f59d85f5e8d5f0b8df30"}
|
||||
};
|
||||
}
|
||||
}
|
||||
163
Algorithm.CSharp/ContinuousFutureHistoryRegressionAlgorithm.cs
Normal file
163
Algorithm.CSharp/ContinuousFutureHistoryRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures History Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureHistoryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Future _continuousContract;
|
||||
private bool _warmedUp;
|
||||
|
||||
/// <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, 10);
|
||||
SetEndDate(2013, 10, 11);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.OpenInterest,
|
||||
contractDepthOffset: 1
|
||||
);
|
||||
SetWarmup(10);
|
||||
}
|
||||
|
||||
/// <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 (IsWarmingUp)
|
||||
{
|
||||
// warm up data
|
||||
_warmedUp = true;
|
||||
|
||||
if (!_continuousContract.HasData)
|
||||
{
|
||||
throw new Exception($"ContinuousContract did not get any data during warmup!");
|
||||
}
|
||||
|
||||
var backMonthExpiration = data.Keys.Single().Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
if (backMonthExpiration <= frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {backMonthExpiration}" +
|
||||
$" @ {Time} it should be AFTER front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
if (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
Buy(_continuousContract.Symbol, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_warmedUp)
|
||||
{
|
||||
throw new Exception("Algorithm didn't warm up!");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
if (changes.AddedSecurities.Any(security => security.Symbol != _continuousContract.Symbol)
|
||||
|| changes.RemovedSecurities.Any(security => security.Symbol != _continuousContract.Symbol))
|
||||
{
|
||||
throw new Exception($"We got an unexpected security changes {changes}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$42000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 1S1"},
|
||||
{"Fitness Score", "0.76"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0.76"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "4de9344671d542e30066338e2bf9d400"}
|
||||
};
|
||||
}
|
||||
}
|
||||
212
Algorithm.CSharp/ContinuousFutureRegressionAlgorithm.cs
Normal file
212
Algorithm.CSharp/ContinuousFutureRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
using QuantConnect.Data.Market;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Securities.Future;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
|
||||
/// </summary>
|
||||
public class ContinuousFutureRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private List<SymbolChangedEvent> _mappings = new();
|
||||
private Symbol _currentMappedSymbol;
|
||||
private Future _continuousContract;
|
||||
private DateTime _lastMonth;
|
||||
|
||||
/// <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, 7, 1);
|
||||
SetEndDate(2014, 1, 1);
|
||||
|
||||
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode: DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset: 0
|
||||
);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
// we subtract a minute cause we can get data on the market close, from the previous minute
|
||||
if (!_continuousContract.Exchange.DateTimeIsOpen(Time.AddMinutes(-1)))
|
||||
{
|
||||
if (data.Bars.Count > 0 || data.QuoteBars.Count > 0)
|
||||
{
|
||||
throw new Exception($"We are getting data during closed market!");
|
||||
}
|
||||
}
|
||||
|
||||
var currentlyMappedSecurity = Securities[_continuousContract.Mapped];
|
||||
|
||||
if (data.Keys.Count != 1)
|
||||
{
|
||||
throw new Exception($"We are getting data for more than one symbols! {string.Join(",", data.Keys.Select(symbol => symbol))}");
|
||||
}
|
||||
|
||||
foreach (var changedEvent in data.SymbolChangedEvents.Values)
|
||||
{
|
||||
if (changedEvent.Symbol == _continuousContract.Symbol)
|
||||
{
|
||||
_mappings.Add(changedEvent);
|
||||
Log($"{Time} - SymbolChanged event: {changedEvent}");
|
||||
|
||||
if (_currentMappedSymbol == _continuousContract.Mapped)
|
||||
{
|
||||
throw new Exception($"Continuous contract current symbol did not change! {_continuousContract.Mapped}");
|
||||
}
|
||||
|
||||
var currentExpiration = changedEvent.Symbol.Underlying.ID.Date;
|
||||
var frontMonthExpiration = FuturesExpiryFunctions.FuturesExpiryFunction(_continuousContract.Symbol)(Time.AddMonths(1));
|
||||
|
||||
if (currentExpiration != frontMonthExpiration.Date)
|
||||
{
|
||||
throw new Exception($"Unexpected current mapped contract expiration {currentExpiration}" +
|
||||
$" @ {Time} it should be AT front month expiration {frontMonthExpiration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_lastMonth.Month != Time.Month && currentlyMappedSecurity.HasData)
|
||||
{
|
||||
_lastMonth = Time;
|
||||
|
||||
Log($"{Time}- {currentlyMappedSecurity.GetLastData()}");
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
else
|
||||
{
|
||||
// This works because we set this contract as tradable, even if it's a canonical security
|
||||
Buy(currentlyMappedSecurity.Symbol, 1);
|
||||
}
|
||||
|
||||
if(Time.Month == 1 && Time.Year == 2013)
|
||||
{
|
||||
var response = History(new[] { _continuousContract.Symbol }, 60 * 24 * 90);
|
||||
if (!response.Any())
|
||||
{
|
||||
throw new Exception("Unexpected empty history response");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_currentMappedSymbol = _continuousContract.Mapped;
|
||||
}
|
||||
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
if (orderEvent.Status == OrderStatus.Filled)
|
||||
{
|
||||
Log($"{orderEvent}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
Debug($"{Time}-{changes}");
|
||||
if (changes.AddedSecurities.Any(security => security.Symbol != _continuousContract.Symbol)
|
||||
|| changes.RemovedSecurities.Any(security => security.Symbol != _continuousContract.Symbol))
|
||||
{
|
||||
throw new Exception($"We got an unexpected security changes {changes}");
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
var expectedMappingCounts = 2;
|
||||
if (_mappings.Count != expectedMappingCounts)
|
||||
{
|
||||
throw new Exception($"Unexpected symbol changed events: {_mappings.Count}, was expecting {expectedMappingCounts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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", "3"},
|
||||
{"Average Win", "1.21%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "2.392%"},
|
||||
{"Drawdown", "1.600%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.199%"},
|
||||
{"Sharpe Ratio", "0.775"},
|
||||
{"Probabilistic Sharpe Ratio", "40.287%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.006"},
|
||||
{"Beta", "0.099"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.726"},
|
||||
{"Tracking Error", "0.076"},
|
||||
{"Treynor Ratio", "0.169"},
|
||||
{"Total Fees", "$5.55"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.01"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "0.516"},
|
||||
{"Return Over Maximum Drawdown", "1.935"},
|
||||
{"Portfolio Turnover", "0.016"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "8ad040c62ad255e4f9cd423364147e85"}
|
||||
};
|
||||
}
|
||||
}
|
||||
105
Algorithm.CSharp/CryptoCashAccountFeeRegressionAlgorithm.cs
Normal file
105
Algorithm.CSharp/CryptoCashAccountFeeRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Util;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Brokerages;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Base crypto cash account regression algorithm trading in and out
|
||||
/// </summary>
|
||||
public abstract class CryptoCashAccountFeeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _symbol;
|
||||
|
||||
/// <summary>
|
||||
/// The target brokerage model name
|
||||
/// </summary>
|
||||
protected BrokerageName BrokerageName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The pair to add and trade
|
||||
/// </summary>
|
||||
protected string Pair { get; set; }
|
||||
|
||||
/// <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()
|
||||
{
|
||||
SetBrokerageModel(BrokerageName, AccountType.Cash);
|
||||
_symbol = AddCrypto(Pair, Resolution.Hour).Symbol;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
CurrencyPairUtil.DecomposeCurrencyPair(_symbol, out var baseCurrency, out var quoteCurrency);
|
||||
|
||||
var initialQuoteCurrency = Portfolio.CashBook[quoteCurrency].Amount;
|
||||
var ticket = Buy(_symbol, 0.1m);
|
||||
var filledEvent = ticket.OrderEvents.Single(orderEvent => orderEvent.Status == OrderStatus.Filled);
|
||||
|
||||
if (Portfolio.CashBook[baseCurrency].Amount != ticket.QuantityFilled
|
||||
|| filledEvent.FillQuantity != ticket.QuantityFilled
|
||||
|| (0.1m - filledEvent.OrderFee.Value.Amount) != ticket.QuantityFilled)
|
||||
{
|
||||
throw new Exception($"Unexpected BaseCurrency porfoltio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
|
||||
}
|
||||
|
||||
if (Portfolio.CashBook[quoteCurrency].Amount != (initialQuoteCurrency - 0.1m * filledEvent.FillPrice))
|
||||
{
|
||||
throw new Exception($"Unexpected QuoteCurrency porfoltio status. Event {filledEvent}. CashBook: {Portfolio.CashBook}. ");
|
||||
}
|
||||
|
||||
if (Securities[_symbol].Holdings.Quantity != (0.1m - filledEvent.OrderFee.Value.Amount))
|
||||
{
|
||||
throw new Exception($"Unexpected Holdings: {Securities[_symbol].Holdings}. Event {filledEvent}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 abstract Dictionary<string, string> ExpectedStatistics { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -14,16 +14,17 @@
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Globalization;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Util;
|
||||
using QuantConnect.Indicators;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// The algorithm creates new indicator value with the existing indicator method by Indicator Extensions
|
||||
/// Demonstration of using the external custom datasource Quandl to request the VIX and VXV daily data
|
||||
/// Demonstration of using local custom datasource CustomData to request the IBM and SPY daily data
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
@@ -34,10 +35,10 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="charting" />
|
||||
public class CustomDataIndicatorExtensionsAlgorithm : QCAlgorithm
|
||||
{
|
||||
private const string _vix = "CBOE/VIX";
|
||||
private const string _vxv = "CBOE/VXV";
|
||||
private SimpleMovingAverage _smaVIX;
|
||||
private SimpleMovingAverage _smaVXV;
|
||||
private const string _ibm = "IBM";
|
||||
private const string _spy = "SPY";
|
||||
private SimpleMovingAverage _smaIBM;
|
||||
private SimpleMovingAverage _smaSPY;
|
||||
private IndicatorBase<IndicatorDataPoint> _ratio;
|
||||
|
||||
/// <summary>
|
||||
@@ -50,46 +51,82 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
SetCash(25000);
|
||||
|
||||
// Define the symbol and "type" of our generic data
|
||||
AddData<QuandlVix>(_vix, Resolution.Daily);
|
||||
AddData<Quandl>(_vxv, Resolution.Daily);
|
||||
AddData<CustomData>(_ibm, Resolution.Daily);
|
||||
AddData<CustomData>(_spy, Resolution.Daily);
|
||||
// Set up default Indicators, these are just 'identities' of the closing price
|
||||
_smaVIX = SMA(_vix, 1);
|
||||
_smaVXV = SMA(_vxv, 1);
|
||||
// This will create a new indicator whose value is smaVXV / smaVIX
|
||||
_ratio = _smaVXV.Over(_smaVIX);
|
||||
_smaIBM = SMA(_ibm, 1);
|
||||
_smaSPY = SMA(_spy, 1);
|
||||
// This will create a new indicator whose value is smaSPY / smaIBM
|
||||
_ratio = _smaSPY.Over(_smaIBM);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Custom data event handler:
|
||||
/// </summary>
|
||||
/// <param name="data">Quandl - dictionary Bars of Quandl Data</param>
|
||||
public void OnData(Quandl data)
|
||||
/// <param name="data">CustomData - dictionary Bars of custom data</param>
|
||||
public void OnData(CustomData data)
|
||||
{
|
||||
// Wait for all indicators to fully initialize
|
||||
if (_smaVIX.IsReady && _smaVXV.IsReady && _ratio.IsReady)
|
||||
if (_smaIBM.IsReady && _smaSPY.IsReady && _ratio.IsReady)
|
||||
{
|
||||
if (!Portfolio.Invested && _ratio > 1)
|
||||
{
|
||||
MarketOrder(_vix, 100);
|
||||
MarketOrder(_ibm, 100);
|
||||
}
|
||||
else if (_ratio < 1)
|
||||
{
|
||||
Liquidate();
|
||||
}
|
||||
// plot all indicators
|
||||
PlotIndicator("SMA", _smaVIX, _smaVXV);
|
||||
PlotIndicator("SMA", _smaIBM, _smaSPY);
|
||||
PlotIndicator("Ratio", _ratio);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In CBOE/VIX data, there is a "vix close" column instead of "close" which is the
|
||||
/// default column namein LEAN Quandl custom data implementation.
|
||||
/// This class assigns new column name to match the the external datasource setting.
|
||||
/// Custom data from local LEAN data
|
||||
/// </summary>
|
||||
public class QuandlVix : Quandl
|
||||
public class CustomData : BaseData
|
||||
{
|
||||
public QuandlVix() : base(valueColumnName: "vix close") { }
|
||||
public decimal Open;
|
||||
public decimal High;
|
||||
public decimal Low;
|
||||
public decimal Close;
|
||||
|
||||
public override DateTime EndTime
|
||||
{
|
||||
get { return Time + Period; }
|
||||
set { Time = value - Period; }
|
||||
}
|
||||
|
||||
public TimeSpan Period
|
||||
{
|
||||
get { return QuantConnect.Time.OneDay; }
|
||||
}
|
||||
|
||||
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
|
||||
{
|
||||
var source = Path.Combine(Globals.DataFolder, "equity", "usa", config.Resolution.ToString().ToLower(), LeanData.GenerateZipFileName(config.Symbol, date, config.Resolution, config.TickType));
|
||||
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
|
||||
}
|
||||
|
||||
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
|
||||
{
|
||||
var csv = line.ToCsv(6);
|
||||
var _scaleFactor = 1 / 10000m;
|
||||
|
||||
var custom = new CustomData
|
||||
{
|
||||
Symbol = config.Symbol,
|
||||
Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture),
|
||||
Open = csv[1].ToDecimal() * _scaleFactor,
|
||||
High = csv[2].ToDecimal() * _scaleFactor,
|
||||
Low = csv[3].ToDecimal() * _scaleFactor,
|
||||
Close = csv[4].ToDecimal() * _scaleFactor,
|
||||
Value = csv[4].ToDecimal() * _scaleFactor
|
||||
};
|
||||
return custom;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
@@ -31,12 +33,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="regression test" />
|
||||
public class CustomDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private bool _warmedUpChecked = false;
|
||||
|
||||
/// <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(2011, 9, 13);
|
||||
SetStartDate(2011, 9, 14);
|
||||
SetEndDate(2015, 12, 01);
|
||||
|
||||
//Set the cash for the strategy:
|
||||
@@ -45,6 +49,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
//Define the symbol and "type" of our generic data:
|
||||
var resolution = LiveMode ? Resolution.Second : Resolution.Daily;
|
||||
AddData<Bitcoin>("BTC", resolution);
|
||||
|
||||
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
|
||||
SetSecurityInitializer(security => seeder.SeedSecurity(security));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,6 +73,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnSecuritiesChanged(SecurityChanges changes)
|
||||
{
|
||||
changes.FilterCustomSecurities = false;
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
if (addedSecurity.Symbol.Value == "BTC")
|
||||
{
|
||||
_warmedUpChecked = true;
|
||||
}
|
||||
if (!addedSecurity.HasData)
|
||||
{
|
||||
throw new Exception($"Security {addedSecurity.Symbol} was not warmed up!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (!_warmedUpChecked)
|
||||
{
|
||||
throw new Exception($"Security was not warmed up!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
@@ -84,30 +115,30 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "157.497%"},
|
||||
{"Compounding Annual Return", "157.655%"},
|
||||
{"Drawdown", "84.800%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "5319.007%"},
|
||||
{"Sharpe Ratio", "2.086"},
|
||||
{"Probabilistic Sharpe Ratio", "69.456%"},
|
||||
{"Sharpe Ratio", "2.123"},
|
||||
{"Probabilistic Sharpe Ratio", "70.581%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.747"},
|
||||
{"Beta", "0.047"},
|
||||
{"Alpha", "1.776"},
|
||||
{"Beta", "0.059"},
|
||||
{"Annual Standard Deviation", "0.84"},
|
||||
{"Annual Variance", "0.706"},
|
||||
{"Information Ratio", "1.922"},
|
||||
{"Tracking Error", "0.848"},
|
||||
{"Treynor Ratio", "37.473"},
|
||||
{"Information Ratio", "1.962"},
|
||||
{"Tracking Error", "0.847"},
|
||||
{"Treynor Ratio", "30.455"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "BTC.Bitcoin 2S"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "2.269"},
|
||||
{"Return Over Maximum Drawdown", "1.858"},
|
||||
{"Sortino Ratio", "2.271"},
|
||||
{"Return Over Maximum Drawdown", "1.86"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
|
||||
@@ -94,14 +94,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "1.63%"},
|
||||
{"Average Win", "1.64%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "7.292%"},
|
||||
{"Compounding Annual Return", "7.329%"},
|
||||
{"Drawdown", "1.300%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.634%"},
|
||||
{"Sharpe Ratio", "2.351"},
|
||||
{"Probabilistic Sharpe Ratio", "94.365%"},
|
||||
{"Net Profit", "1.642%"},
|
||||
{"Sharpe Ratio", "2.36"},
|
||||
{"Probabilistic Sharpe Ratio", "94.555%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
@@ -109,17 +109,17 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0.158"},
|
||||
{"Annual Standard Deviation", "0.03"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-4.444"},
|
||||
{"Information Ratio", "-4.44"},
|
||||
{"Tracking Error", "0.075"},
|
||||
{"Treynor Ratio", "0.439"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Treynor Ratio", "0.441"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$170000000.00"},
|
||||
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
|
||||
{"Fitness Score", "0.019"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "1.362"},
|
||||
{"Return Over Maximum Drawdown", "9.699"},
|
||||
{"Sortino Ratio", "1.369"},
|
||||
{"Return Over Maximum Drawdown", "9.749"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -134,7 +134,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "00d6dc8775da38f7f79defad06de240a"}
|
||||
{"OrderListHash", "4c5e32aedcd5bb67642d1629628fe615"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,13 +137,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.592"},
|
||||
{"Beta", "-0.737"},
|
||||
{"Alpha", "-0.559"},
|
||||
{"Beta", "-0.807"},
|
||||
{"Annual Standard Deviation", "1.582"},
|
||||
{"Annual Variance", "2.502"},
|
||||
{"Information Ratio", "-0.905"},
|
||||
{"Tracking Error", "1.592"},
|
||||
{"Treynor Ratio", "1.292"},
|
||||
{"Tracking Error", "1.593"},
|
||||
{"Treynor Ratio", "1.181"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$1000000.00"},
|
||||
{"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"},
|
||||
@@ -166,7 +166,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "4ae4c1d8e4054c41908fd36e893699a6"}
|
||||
{"OrderListHash", "721fddfd1327f7adcc2883d1412708c9"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,34 +140,34 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-3.23%"},
|
||||
{"Compounding Annual Return", "-79.990%"},
|
||||
{"Drawdown", "4.300%"},
|
||||
{"Average Loss", "-5.58%"},
|
||||
{"Compounding Annual Return", "-87.694%"},
|
||||
{"Drawdown", "5.600%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-4.312%"},
|
||||
{"Sharpe Ratio", "-5.637"},
|
||||
{"Probabilistic Sharpe Ratio", "0.005%"},
|
||||
{"Net Profit", "-5.578%"},
|
||||
{"Sharpe Ratio", "-4.683"},
|
||||
{"Probabilistic Sharpe Ratio", "0.008%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.5"},
|
||||
{"Beta", "-0.346"},
|
||||
{"Annual Standard Deviation", "0.092"},
|
||||
{"Annual Variance", "0.008"},
|
||||
{"Information Ratio", "-4.312"},
|
||||
{"Tracking Error", "0.131"},
|
||||
{"Treynor Ratio", "1.493"},
|
||||
{"Total Fees", "$55.05"},
|
||||
{"Estimated Strategy Capacity", "$43000.00"},
|
||||
{"Alpha", "-0.622"},
|
||||
{"Beta", "-0.877"},
|
||||
{"Annual Standard Deviation", "0.142"},
|
||||
{"Annual Variance", "0.02"},
|
||||
{"Information Ratio", "-3.844"},
|
||||
{"Tracking Error", "0.186"},
|
||||
{"Treynor Ratio", "0.759"},
|
||||
{"Total Fees", "$36.70"},
|
||||
{"Estimated Strategy Capacity", "$65000.00"},
|
||||
{"Lowest Capacity Asset", "AAA SEVKGI6HF885"},
|
||||
{"Fitness Score", "0.002"},
|
||||
{"Fitness Score", "0.003"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-15.687"},
|
||||
{"Return Over Maximum Drawdown", "-18.549"},
|
||||
{"Portfolio Turnover", "0.334"},
|
||||
{"Sortino Ratio", "-10.959"},
|
||||
{"Return Over Maximum Drawdown", "-15.72"},
|
||||
{"Portfolio Turnover", "0.224"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -181,7 +181,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "e357cfa77fd5e5b974c68d550fa66490"}
|
||||
{"OrderListHash", "2d66947eafcca81ba9a2cd3bb351eee2"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,9 +108,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Average Loss", "-0.02%"},
|
||||
{"Compounding Annual Return", "-0.111%"},
|
||||
{"Drawdown", "0.100%"},
|
||||
{"Expectancy", "-0.679"},
|
||||
{"Net Profit", "-0.112%"},
|
||||
{"Sharpe Ratio", "-0.966"},
|
||||
{"Expectancy", "-0.678"},
|
||||
{"Net Profit", "-0.111%"},
|
||||
{"Sharpe Ratio", "-0.967"},
|
||||
{"Probabilistic Sharpe Ratio", "0.000%"},
|
||||
{"Loss Rate", "80%"},
|
||||
{"Win Rate", "20%"},
|
||||
@@ -121,8 +121,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-1.075"},
|
||||
{"Tracking Error", "0.107"},
|
||||
{"Treynor Ratio", "1.354"},
|
||||
{"Total Fees", "$37.00"},
|
||||
{"Treynor Ratio", "1.353"},
|
||||
{"Total Fees", "$14.80"},
|
||||
{"Estimated Strategy Capacity", "$860000000.00"},
|
||||
{"Lowest Capacity Asset", "DC V5E8P9SH0U0X"},
|
||||
{"Fitness Score", "0"},
|
||||
@@ -144,7 +144,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "de309ab56d2fcd80ff03df2802d9feda"}
|
||||
{"OrderListHash", "d10e8665214344369e3e8f1c49dbdd67"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,32 +119,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "6"},
|
||||
{"Average Win", "2.93%"},
|
||||
{"Average Win", "2.94%"},
|
||||
{"Average Loss", "-4.15%"},
|
||||
{"Compounding Annual Return", "-5.673%"},
|
||||
{"Drawdown", "5.700%"},
|
||||
{"Expectancy", "-0.148"},
|
||||
{"Net Profit", "-2.802%"},
|
||||
{"Sharpe Ratio", "-0.456"},
|
||||
{"Probabilistic Sharpe Ratio", "9.156%"},
|
||||
{"Compounding Annual Return", "-5.589%"},
|
||||
{"Drawdown", "5.600%"},
|
||||
{"Expectancy", "-0.145"},
|
||||
{"Net Profit", "-2.760%"},
|
||||
{"Sharpe Ratio", "-0.45"},
|
||||
{"Probabilistic Sharpe Ratio", "9.306%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.70"},
|
||||
{"Profit-Loss Ratio", "0.71"},
|
||||
{"Alpha", "-0.036"},
|
||||
{"Beta", "-0.012"},
|
||||
{"Annual Standard Deviation", "0.08"},
|
||||
{"Annual Variance", "0.006"},
|
||||
{"Information Ratio", "-0.15"},
|
||||
{"Information Ratio", "-0.149"},
|
||||
{"Tracking Error", "0.387"},
|
||||
{"Treynor Ratio", "3.008"},
|
||||
{"Total Fees", "$14.80"},
|
||||
{"Estimated Strategy Capacity", "$180000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Treynor Ratio", "2.943"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$280000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.017"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.097"},
|
||||
{"Return Over Maximum Drawdown", "-1.002"},
|
||||
{"Sortino Ratio", "-0.096"},
|
||||
{"Return Over Maximum Drawdown", "-0.993"},
|
||||
{"Portfolio Turnover", "0.043"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -159,7 +159,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "fc9eb9b0a644e4890d5ec3d40367d0e1"}
|
||||
{"OrderListHash", "18f8a17034aa12be40581baecca96788"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 19, 20, 0, 0);
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 20, 4, 0, 0);
|
||||
|
||||
if (orderEvent.Direction == OrderDirection.Sell && future.Holdings.Quantity != 0)
|
||||
{
|
||||
@@ -203,13 +203,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "1.22%"},
|
||||
{"Average Loss", "-7.42%"},
|
||||
{"Compounding Annual Return", "-12.482%"},
|
||||
{"Average Win", "1.26%"},
|
||||
{"Average Loss", "-7.41%"},
|
||||
{"Compounding Annual Return", "-12.424%"},
|
||||
{"Drawdown", "6.300%"},
|
||||
{"Expectancy", "-0.417"},
|
||||
{"Net Profit", "-6.282%"},
|
||||
{"Sharpe Ratio", "-1.225"},
|
||||
{"Expectancy", "-0.415"},
|
||||
{"Net Profit", "-6.252%"},
|
||||
{"Sharpe Ratio", "-1.226"},
|
||||
{"Probabilistic Sharpe Ratio", "0.002%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
@@ -218,12 +218,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Beta", "0.004"},
|
||||
{"Annual Standard Deviation", "0.07"},
|
||||
{"Annual Variance", "0.005"},
|
||||
{"Information Ratio", "-0.284"},
|
||||
{"Information Ratio", "-0.283"},
|
||||
{"Tracking Error", "0.379"},
|
||||
{"Treynor Ratio", "-23.801"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$180000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Treynor Ratio", "-23.811"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$270000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
@@ -243,7 +243,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "c59d790b89d76f1ad3bb7738b28567c9"}
|
||||
{"OrderListHash", "b738fdaf1dae6849884df9e51eb6482b"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,32 +168,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "8.71%"},
|
||||
{"Average Loss", "-34.89%"},
|
||||
{"Compounding Annual Return", "-50.850%"},
|
||||
{"Drawdown", "29.200%"},
|
||||
{"Expectancy", "-0.375"},
|
||||
{"Net Profit", "-29.224%"},
|
||||
{"Sharpe Ratio", "-0.977"},
|
||||
{"Average Win", "8.93%"},
|
||||
{"Average Loss", "-34.88%"},
|
||||
{"Compounding Annual Return", "-50.632%"},
|
||||
{"Drawdown", "29.100%"},
|
||||
{"Expectancy", "-0.372"},
|
||||
{"Net Profit", "-29.072%"},
|
||||
{"Sharpe Ratio", "-0.978"},
|
||||
{"Probabilistic Sharpe Ratio", "0.012%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.25"},
|
||||
{"Alpha", "-0.341"},
|
||||
{"Profit-Loss Ratio", "0.26"},
|
||||
{"Alpha", "-0.339"},
|
||||
{"Beta", "0.017"},
|
||||
{"Annual Standard Deviation", "0.348"},
|
||||
{"Annual Variance", "0.121"},
|
||||
{"Information Ratio", "-0.715"},
|
||||
{"Tracking Error", "0.506"},
|
||||
{"Treynor Ratio", "-19.652"},
|
||||
{"Total Fees", "$37.00"},
|
||||
{"Estimated Strategy Capacity", "$33000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.056"},
|
||||
{"Annual Standard Deviation", "0.347"},
|
||||
{"Annual Variance", "0.12"},
|
||||
{"Information Ratio", "-0.714"},
|
||||
{"Tracking Error", "0.505"},
|
||||
{"Treynor Ratio", "-19.672"},
|
||||
{"Total Fees", "$9.25"},
|
||||
{"Estimated Strategy Capacity", "$50000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.055"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.155"},
|
||||
{"Return Over Maximum Drawdown", "-1.741"},
|
||||
{"Return Over Maximum Drawdown", "-1.743"},
|
||||
{"Portfolio Turnover", "0.152"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -208,7 +208,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "ca0898608da51d972723b1065a3f0d47"}
|
||||
{"OrderListHash", "ed0cbd8487dd45519e5d0225e51ba29c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,11 +179,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-4.03%"},
|
||||
{"Compounding Annual Return", "-8.103%"},
|
||||
{"Average Loss", "-4.02%"},
|
||||
{"Compounding Annual Return", "-8.099%"},
|
||||
{"Drawdown", "4.000%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-4.029%"},
|
||||
{"Net Profit", "-4.027%"},
|
||||
{"Sharpe Ratio", "-1.175"},
|
||||
{"Probabilistic Sharpe Ratio", "0.009%"},
|
||||
{"Loss Rate", "100%"},
|
||||
@@ -195,8 +195,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0.002"},
|
||||
{"Information Ratio", "-0.206"},
|
||||
{"Tracking Error", "0.376"},
|
||||
{"Treynor Ratio", "-23.48"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Treynor Ratio", "-23.481"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$200000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UPHGV9G|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0"},
|
||||
@@ -218,7 +218,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "5dc2591837f882d173d2d4852b3b0626"}
|
||||
{"OrderListHash", "cf1c12b839e49456dc2793f0e63c7803"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
169
Algorithm.CSharp/FutureOptionDailyRegressionAlgorithm.cs
Normal file
169
Algorithm.CSharp/FutureOptionDailyRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* 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;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests using FutureOptions daily resolution
|
||||
/// </summary>
|
||||
public class FutureOptionDailyRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
protected OrderTicket Ticket;
|
||||
protected Symbol DcOption;
|
||||
protected virtual Resolution Resolution => Resolution.Daily;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2012, 1, 3);
|
||||
SetEndDate(2012, 1, 4);
|
||||
|
||||
// Add our underlying future contract
|
||||
var dc = AddFutureContract(
|
||||
QuantConnect.Symbol.CreateFuture(
|
||||
Futures.Dairy.ClassIIIMilk,
|
||||
Market.CME,
|
||||
new DateTime(2012, 4, 1)),
|
||||
Resolution).Symbol;
|
||||
|
||||
// Attempt to fetch a specific future option contract
|
||||
DcOption = OptionChainProvider.GetOptionContractList(dc, Time)
|
||||
.Where(x => x.ID.StrikePrice == 17m && x.ID.OptionRight == OptionRight.Call)
|
||||
.Select(x => AddFutureOptionContract(x, Resolution).Symbol)
|
||||
.FirstOrDefault();
|
||||
|
||||
// Validate it is the expected contract
|
||||
var expectedContract = QuantConnect.Symbol.CreateOption(dc, Market.CME, OptionStyle.American,
|
||||
OptionRight.Call, 17m,
|
||||
new DateTime(2012, 4, 01));
|
||||
|
||||
if (DcOption != expectedContract)
|
||||
{
|
||||
throw new Exception($"Contract {DcOption} was not the expected contract {expectedContract}");
|
||||
}
|
||||
|
||||
ScheduleBuySell();
|
||||
}
|
||||
|
||||
protected virtual void ScheduleBuySell()
|
||||
{
|
||||
// Schedule a purchase of this contract tomorrow at 1AM
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.At(1,0,0), () =>
|
||||
{
|
||||
Ticket = MarketOrder(DcOption, 1);
|
||||
});
|
||||
|
||||
// Schedule liquidation tomorrow at 6PM
|
||||
Schedule.On(DateRules.Tomorrow, TimeRules.At(18,0,0), () =>
|
||||
{
|
||||
Liquidate();
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
// Assert we are only getting data at 7PM (12AM UTC)
|
||||
if (slice.Time.Hour != 19)
|
||||
{
|
||||
throw new ArgumentException($"Expected data at 7PM each day; instead was {slice.Time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
||||
/// </summary>
|
||||
/// <exception cref="Exception">The algorithm has holdings</exception>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (Portfolio.Invested)
|
||||
{
|
||||
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
||||
}
|
||||
|
||||
if (Ticket.Status != OrderStatus.Filled)
|
||||
{
|
||||
throw new Exception("Future option order failed to fill correctly");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 virtual bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public virtual Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-0.82%"},
|
||||
{"Compounding Annual Return", "-66.089%"},
|
||||
{"Drawdown", "0.800%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-0.824%"},
|
||||
{"Sharpe Ratio", "-6.993"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0.466"},
|
||||
{"Beta", "-7.501"},
|
||||
{"Annual Standard Deviation", "0.092"},
|
||||
{"Annual Variance", "0.009"},
|
||||
{"Information Ratio", "-7.586"},
|
||||
{"Tracking Error", "0.105"},
|
||||
{"Treynor Ratio", "0.086"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "DC V5E8P9VAH3IC|DC V5E8P9SH0U0X"},
|
||||
{"Fitness Score", "0.006"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-80.233"},
|
||||
{"Portfolio Turnover", "0.013"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "f00013930ab4c104a6177485d8090b31"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
118
Algorithm.CSharp/FutureOptionHourlyRegressionAlgorithm.cs
Normal file
118
Algorithm.CSharp/FutureOptionHourlyRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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;
|
||||
using System.Reflection;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using QuantConnect.Securities;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This regression algorithm tests using FutureOptions hourly resolution
|
||||
/// </summary>
|
||||
public class FutureOptionHourlyRegressionAlgorithm : FutureOptionDailyRegressionAlgorithm
|
||||
{
|
||||
protected override Resolution Resolution => Resolution.Hour;
|
||||
|
||||
protected override void ScheduleBuySell()
|
||||
{
|
||||
// Schedule a purchase of this contract at Noon
|
||||
Schedule.On(DateRules.Today, TimeRules.Noon, () =>
|
||||
{
|
||||
Ticket = MarketOrder(DcOption, 1);
|
||||
});
|
||||
|
||||
// Schedule liquidation at 6PM
|
||||
Schedule.On(DateRules.Today, TimeRules.At(18,0,0), () =>
|
||||
{
|
||||
Liquidate();
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
// Assert we are only getting data only hourly intervals
|
||||
if (slice.Time.Minute != 0)
|
||||
{
|
||||
throw new ArgumentException($"Expected data only on hourly intervals; instead was {slice.Time}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool CanRunLocally { get; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
||||
/// </summary>
|
||||
public override Language[] Languages { get; } = { Language.CSharp, Language.Python };
|
||||
|
||||
/// <summary>
|
||||
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
||||
/// </summary>
|
||||
public override Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "DC V5E8P9VAH3IC|DC V5E8P9SH0U0X"},
|
||||
{"Fitness Score", "0.01"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-101.911"},
|
||||
{"Portfolio Turnover", "0.02"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "665d06e4f758724b5b9576b14fd18743"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract)
|
||||
{
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 19, 20, 0, 0);
|
||||
var expectedLiquidationTimeUtc = new DateTime(2020, 6, 20, 4, 0, 0);
|
||||
|
||||
if (orderEvent.Direction == OrderDirection.Buy && future.Holdings.Quantity != 0)
|
||||
{
|
||||
@@ -204,31 +204,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "4.15%"},
|
||||
{"Average Loss", "-8.27%"},
|
||||
{"Compounding Annual Return", "-8.944%"},
|
||||
{"Drawdown", "4.500%"},
|
||||
{"Expectancy", "-0.249"},
|
||||
{"Net Profit", "-4.457%"},
|
||||
{"Sharpe Ratio", "-1.282"},
|
||||
{"Average Win", "4.18%"},
|
||||
{"Average Loss", "-8.26%"},
|
||||
{"Compounding Annual Return", "-8.884%"},
|
||||
{"Drawdown", "4.400%"},
|
||||
{"Expectancy", "-0.247"},
|
||||
{"Net Profit", "-4.427%"},
|
||||
{"Sharpe Ratio", "-1.283"},
|
||||
{"Probabilistic Sharpe Ratio", "0.001%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.50"},
|
||||
{"Alpha", "-0.062"},
|
||||
{"Beta", "0.003"},
|
||||
{"Profit-Loss Ratio", "0.51"},
|
||||
{"Alpha", "-0.061"},
|
||||
{"Beta", "0.002"},
|
||||
{"Annual Standard Deviation", "0.048"},
|
||||
{"Annual Variance", "0.002"},
|
||||
{"Information Ratio", "-0.222"},
|
||||
{"Information Ratio", "-0.221"},
|
||||
{"Tracking Error", "0.376"},
|
||||
{"Treynor Ratio", "-24.53"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$220000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Treynor Ratio", "-24.544"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$330000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 31EL5FAOOQON8|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-0.224"},
|
||||
{"Sortino Ratio", "-0.225"},
|
||||
{"Return Over Maximum Drawdown", "-2.009"},
|
||||
{"Portfolio Turnover", "0.023"},
|
||||
{"Total Insights Generated", "0"},
|
||||
@@ -244,7 +244,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "d3fa88c3acadb9345ceac76a2dd3b520"}
|
||||
{"OrderListHash", "99f96f433bc76c31cb25bcd9117a6bf1"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,11 +178,11 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "-5.12%"},
|
||||
{"Compounding Annual Return", "-10.230%"},
|
||||
{"Average Loss", "-5.11%"},
|
||||
{"Compounding Annual Return", "-10.226%"},
|
||||
{"Drawdown", "5.100%"},
|
||||
{"Expectancy", "-1"},
|
||||
{"Net Profit", "-5.116%"},
|
||||
{"Net Profit", "-5.114%"},
|
||||
{"Sharpe Ratio", "-1.164"},
|
||||
{"Probabilistic Sharpe Ratio", "0.009%"},
|
||||
{"Loss Rate", "100%"},
|
||||
@@ -195,7 +195,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "-0.243"},
|
||||
{"Tracking Error", "0.378"},
|
||||
{"Treynor Ratio", "-23.284"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$360000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 31EL5FBZBMXES|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0"},
|
||||
@@ -217,7 +217,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "a35054d03fd2caa0a96cbe12e427e928"}
|
||||
{"OrderListHash", "ec799886c15ac6c4b8fb3d873d7e6b14"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,31 +189,31 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "10.05%"},
|
||||
{"Average Loss", "-5.63%"},
|
||||
{"Compounding Annual Return", "8.083%"},
|
||||
{"Average Loss", "-5.60%"},
|
||||
{"Compounding Annual Return", "8.148%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "0.393"},
|
||||
{"Net Profit", "3.855%"},
|
||||
{"Sharpe Ratio", "1.087"},
|
||||
{"Probabilistic Sharpe Ratio", "53.360%"},
|
||||
{"Expectancy", "0.397"},
|
||||
{"Net Profit", "3.886%"},
|
||||
{"Sharpe Ratio", "1.088"},
|
||||
{"Probabilistic Sharpe Ratio", "53.421%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "1.79"},
|
||||
{"Alpha", "0.057"},
|
||||
{"Beta", "-0.002"},
|
||||
{"Annual Standard Deviation", "0.052"},
|
||||
{"Annual Standard Deviation", "0.053"},
|
||||
{"Annual Variance", "0.003"},
|
||||
{"Information Ratio", "0.093"},
|
||||
{"Information Ratio", "0.094"},
|
||||
{"Tracking Error", "0.379"},
|
||||
{"Treynor Ratio", "-23.26"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$200000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Treynor Ratio", "-23.276"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$300000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UP5K75W|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.02"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "17.201"},
|
||||
{"Return Over Maximum Drawdown", "17.34"},
|
||||
{"Portfolio Turnover", "0.02"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -228,7 +228,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "8e380e4d5c5e3e145ba388f7853829bb"}
|
||||
{"OrderListHash", "8a33f32b29bcc66d4dd779b36df9a010"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,12 +173,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "1.81%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "3.752%"},
|
||||
{"Compounding Annual Return", "3.756%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.809%"},
|
||||
{"Net Profit", "1.811%"},
|
||||
{"Sharpe Ratio", "1.183"},
|
||||
{"Probabilistic Sharpe Ratio", "60.809%"},
|
||||
{"Probabilistic Sharpe Ratio", "60.811%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
@@ -188,15 +188,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0.012"},
|
||||
{"Tracking Error", "0.375"},
|
||||
{"Treynor Ratio", "-24.051"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Treynor Ratio", "-24.052"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$78000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UPNF7B8|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "95.495"},
|
||||
{"Return Over Maximum Drawdown", "95.594"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -211,7 +211,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "35baadd70ec72c735eadbf55d702fe04"}
|
||||
{"OrderListHash", "8cb012d36057103bf26a897fe5fa54d6"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,32 +185,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "10.18%"},
|
||||
{"Average Loss", "-8.05%"},
|
||||
{"Compounding Annual Return", "2.726%"},
|
||||
{"Average Win", "10.19%"},
|
||||
{"Average Loss", "-8.02%"},
|
||||
{"Compounding Annual Return", "2.790%"},
|
||||
{"Drawdown", "0.500%"},
|
||||
{"Expectancy", "0.133"},
|
||||
{"Net Profit", "1.318%"},
|
||||
{"Sharpe Ratio", "0.855"},
|
||||
{"Probabilistic Sharpe Ratio", "42.696%"},
|
||||
{"Expectancy", "0.135"},
|
||||
{"Net Profit", "1.348%"},
|
||||
{"Sharpe Ratio", "0.862"},
|
||||
{"Probabilistic Sharpe Ratio", "42.945%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "1.27"},
|
||||
{"Alpha", "0.019"},
|
||||
{"Alpha", "0.02"},
|
||||
{"Beta", "-0.001"},
|
||||
{"Annual Standard Deviation", "0.022"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.007"},
|
||||
{"Annual Standard Deviation", "0.023"},
|
||||
{"Annual Variance", "0.001"},
|
||||
{"Information Ratio", "-0.006"},
|
||||
{"Tracking Error", "0.375"},
|
||||
{"Treynor Ratio", "-20.534"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Estimated Strategy Capacity", "$130000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Treynor Ratio", "-20.61"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$200000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 31EL5FAOUP0P0|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.021"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "5.725"},
|
||||
{"Return Over Maximum Drawdown", "5.859"},
|
||||
{"Portfolio Turnover", "0.022"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -225,7 +225,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "519cc7c39703b6e6913dbe98468da872"}
|
||||
{"OrderListHash", "eb37251ad1e32dd348af8a69e1888053"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,12 +170,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "2"},
|
||||
{"Average Win", "3.28%"},
|
||||
{"Average Win", "3.29%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "6.865%"},
|
||||
{"Compounding Annual Return", "6.869%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "3.284%"},
|
||||
{"Net Profit", "3.286%"},
|
||||
{"Sharpe Ratio", "1.205"},
|
||||
{"Probabilistic Sharpe Ratio", "61.483%"},
|
||||
{"Loss Rate", "0%"},
|
||||
@@ -188,14 +188,14 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "0.07"},
|
||||
{"Tracking Error", "0.377"},
|
||||
{"Treynor Ratio", "-24.401"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Total Fees", "$1.85"},
|
||||
{"Estimated Strategy Capacity", "$80000000.00"},
|
||||
{"Lowest Capacity Asset", "ES 31EL5FAJQ6SBO|ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "150.763"},
|
||||
{"Return Over Maximum Drawdown", "150.849"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -210,7 +210,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "5571280f1efb15dd3899896fb72385ff"}
|
||||
{"OrderListHash", "76ed4eaa5f6ed50aa6134aecfbbe9e29"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
private readonly DateTime _expectedExpiryWarningTime = new DateTime(2020, 6, 19);
|
||||
private readonly DateTime _expectedExpiryDelistingTime = new DateTime(2020, 6, 20);
|
||||
private readonly DateTime _expectedLiquidationTime = new DateTime(2020, 6, 19, 16, 0, 0);
|
||||
private readonly DateTime _expectedLiquidationTime = new DateTime(2020, 6, 20);
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
@@ -183,15 +183,15 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Total Trades", "3"},
|
||||
{"Average Win", "10.15%"},
|
||||
{"Average Loss", "-11.34%"},
|
||||
{"Compounding Annual Return", "-2.578%"},
|
||||
{"Compounding Annual Return", "-2.573%"},
|
||||
{"Drawdown", "2.300%"},
|
||||
{"Expectancy", "-0.053"},
|
||||
{"Net Profit", "-2.345%"},
|
||||
{"Expectancy", "-0.052"},
|
||||
{"Net Profit", "-2.341%"},
|
||||
{"Sharpe Ratio", "-0.867"},
|
||||
{"Probabilistic Sharpe Ratio", "0.001%"},
|
||||
{"Loss Rate", "50%"},
|
||||
{"Win Rate", "50%"},
|
||||
{"Profit-Loss Ratio", "0.89"},
|
||||
{"Profit-Loss Ratio", "0.90"},
|
||||
{"Alpha", "-0.014"},
|
||||
{"Beta", "0.001"},
|
||||
{"Annual Standard Deviation", "0.016"},
|
||||
@@ -199,7 +199,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Information Ratio", "-0.603"},
|
||||
{"Tracking Error", "0.291"},
|
||||
{"Treynor Ratio", "-13.292"},
|
||||
{"Total Fees", "$7.40"},
|
||||
{"Total Fees", "$3.70"},
|
||||
{"Estimated Strategy Capacity", "$45000000.00"},
|
||||
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
|
||||
{"Fitness Score", "0.005"},
|
||||
@@ -221,7 +221,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "0128b145984582f5eba7e95881d9b62d"}
|
||||
{"OrderListHash", "67d8ad460ff796937ee252c3e4340e62"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
*/
|
||||
|
||||
using System;
|
||||
using QuantConnect.Util;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Securities.Equity;
|
||||
@@ -36,7 +36,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public class HistoryAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private int _count;
|
||||
private SimpleMovingAverage _spyDailySma;
|
||||
private SimpleMovingAverage _dailySma;
|
||||
|
||||
/// <summary>
|
||||
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
|
||||
@@ -49,12 +49,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
// Find more symbols here: http://quantconnect.com/data
|
||||
var SPY = AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily).Symbol;
|
||||
var CME_SP1 = AddData<QuandlFuture>("CHRIS/CME_SP1", Resolution.Daily).Symbol;
|
||||
var IBM = AddData<CustomData>("IBM", Resolution.Daily).Symbol;
|
||||
// specifying the exchange will allow the history methods that accept a number of bars to return to work properly
|
||||
Securities["CHRIS/CME_SP1"].Exchange = new EquityExchange();
|
||||
Securities["IBM"].Exchange = new EquityExchange();
|
||||
|
||||
// we can get history in initialize to set up indicators and such
|
||||
_spyDailySma = new SimpleMovingAverage(14);
|
||||
_dailySma = new SimpleMovingAverage(14);
|
||||
|
||||
// get the last calendar year's worth of SPY data at the configured resolution (daily)
|
||||
var tradeBarHistory = History<TradeBar>("SPY", TimeSpan.FromDays(365));
|
||||
@@ -76,99 +76,97 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// we can use these TradeBars to initialize indicators or perform other math
|
||||
foreach (TradeBar tradeBar in tradeBarHistory)
|
||||
{
|
||||
_spyDailySma.Update(tradeBar.EndTime, tradeBar.Close);
|
||||
_dailySma.Update(tradeBar.EndTime, tradeBar.Close);
|
||||
}
|
||||
|
||||
// get the last calendar year's worth of quandl data at the configured resolution (daily)
|
||||
var quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", TimeSpan.FromDays(365))", quandlHistory, 250, CME_SP1);
|
||||
// get the last calendar year's worth of IBM data at the configured resolution (daily)
|
||||
var customDataHistory = History<CustomData>("IBM", TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<CustomData>(\"IBM\", TimeSpan.FromDays(365))", customDataHistory, 250, IBM);
|
||||
|
||||
// get the last 14 bars of SPY at the configured resolution (daily)
|
||||
quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", 14);
|
||||
AssertHistoryCount("History<Quandl>(\"CHRIS/CME_SP1\", 14)", quandlHistory, 14, CME_SP1);
|
||||
// get the last 14 bars of IBM at the configured resolution (daily)
|
||||
customDataHistory = History<CustomData>("IBM", 14);
|
||||
AssertHistoryCount("History<CustomData>(\"IBM\", 14)", customDataHistory, 14, IBM);
|
||||
|
||||
// get the last 14 minute bars of SPY
|
||||
|
||||
// we can loop over the return values from these functions and we'll get Quandl data
|
||||
// we can loop over the return values from these functions and we'll get custom data
|
||||
// this can be used in much the same way as the tradeBarHistory above
|
||||
_spyDailySma.Reset();
|
||||
foreach (QuandlFuture quandl in quandlHistory)
|
||||
_dailySma.Reset();
|
||||
foreach (CustomData customData in customDataHistory)
|
||||
{
|
||||
_spyDailySma.Update(quandl.EndTime, quandl.Value);
|
||||
_dailySma.Update(customData.EndTime, customData.Value);
|
||||
}
|
||||
|
||||
// get the last year's worth of all configured Quandl data at the configured resolution (daily)
|
||||
var allQuandlData = History<QuandlFuture>(TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<QuandlFuture>(TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1);
|
||||
// get the last year's worth of all configured custom data at the configured resolution (daily)
|
||||
var allCustomData = History<CustomData>(TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<CustomData>(TimeSpan.FromDays(365))", allCustomData, 250, IBM);
|
||||
|
||||
// get the last 14 bars worth of Quandl data for the specified symbols at the configured resolution (daily)
|
||||
allQuandlData = History<QuandlFuture>(Securities.Keys, 14);
|
||||
AssertHistoryCount("History<QuandlFuture>(Securities.Keys, 14)", allQuandlData, 14, CME_SP1);
|
||||
// get the last 14 bars worth of custom data for the specified symbols at the configured resolution (daily)
|
||||
allCustomData = History<CustomData>(Securities.Keys, 14);
|
||||
AssertHistoryCount("History<CustomData>(Securities.Keys, 14)", allCustomData, 14, IBM);
|
||||
|
||||
// NOTE: using different resolutions require that they are properly implemented in your data type, since
|
||||
// Quandl doesn't support minute data, this won't actually work, but if your custom data source has
|
||||
// different resolutions, it would need to be implemented in the GetSource and Reader methods properly
|
||||
//quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", TimeSpan.FromDays(7), Resolution.Minute);
|
||||
//quandlHistory = History<QuandlFuture>("CHRIS/CME_SP1", 14, Resolution.Minute);
|
||||
//allQuandlData = History<QuandlFuture>(TimeSpan.FromDays(365), Resolution.Minute);
|
||||
//allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute);
|
||||
//allQuandlData = History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
|
||||
//allQuandlData = History<QuandlFuture>(Securities.Keys, 14, Resolution.Minute);
|
||||
// NOTE: Using different resolutions require that they are properly implemented in your data type. If your
|
||||
// custom data source has different resolutions, it would need to be implemented in the GetSource and Reader
|
||||
// methods properly.
|
||||
//customDataHistory = History<CustomData>("IBM", TimeSpan.FromDays(7), Resolution.Minute);
|
||||
//customDataHistory = History<CustomData>("IBM", 14, Resolution.Minute);
|
||||
//allCustomData = History<CustomData>(TimeSpan.FromDays(365), Resolution.Minute);
|
||||
//allCustomData = History<CustomData>(Securities.Keys, 14, Resolution.Minute);
|
||||
//allCustomData = History<CustomData>(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
|
||||
//allCustomData = History<CustomData>(Securities.Keys, 14, Resolution.Minute);
|
||||
|
||||
// get the last calendar year's worth of all quandl data
|
||||
allQuandlData = History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<QuandlFuture>(Securities.Keys, TimeSpan.FromDays(365))", allQuandlData, 250, CME_SP1);
|
||||
// get the last calendar year's worth of all custom data
|
||||
allCustomData = History<CustomData>(Securities.Keys, TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History<CustomData>(Securities.Keys, TimeSpan.FromDays(365))", allCustomData, 250, IBM);
|
||||
|
||||
// the return is a series of dictionaries containing all quandl data at each time
|
||||
// the return is a series of dictionaries containing all custom data at each time
|
||||
// we can loop over it to get the individual dictionaries
|
||||
foreach (DataDictionary<QuandlFuture> quandlsDataDictionary in allQuandlData)
|
||||
foreach (DataDictionary<CustomData> customDataDictionary in allCustomData)
|
||||
{
|
||||
// we can access the dictionary to get the quandl data we want
|
||||
var quandl = quandlsDataDictionary["CHRIS/CME_SP1"];
|
||||
// we can access the dictionary to get the custom data we want
|
||||
var customData = customDataDictionary["IBM"];
|
||||
}
|
||||
|
||||
// we can also access the return value from the multiple symbol functions to request a single
|
||||
// symbol and then loop over it
|
||||
var singleSymbolQuandl = allQuandlData.Get("CHRIS/CME_SP1");
|
||||
AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\")", singleSymbolQuandl, 250, CME_SP1);
|
||||
foreach (QuandlFuture quandl in singleSymbolQuandl)
|
||||
var singleSymbolCustomData = allCustomData.Get("IBM");
|
||||
AssertHistoryCount("allCustomData.Get(\"IBM\")", singleSymbolCustomData, 250, IBM);
|
||||
foreach (CustomData customData in singleSymbolCustomData)
|
||||
{
|
||||
// do something with 'CHRIS/CME_SP1' quandl data
|
||||
// do something with 'IBM' custom data
|
||||
}
|
||||
|
||||
// we can also access individual properties on our data, this will
|
||||
// get the 'CHRIS/CME_SP1' quandls like above, but then only return the Low properties
|
||||
var quandlSpyLows = allQuandlData.Get("CHRIS/CME_SP1", "Low");
|
||||
AssertHistoryCount("allQuandlData.Get(\"CHRIS/CME_SP1\", \"Low\")", quandlSpyLows, 250);
|
||||
foreach (decimal low in quandlSpyLows)
|
||||
// get the 'IBM' CustomData objects like above, but then only return the Value properties
|
||||
var customDataIbmValues = allCustomData.Get("IBM", "Value");
|
||||
AssertHistoryCount("allCustomData.Get(\"IBM\", \"Value\")", customDataIbmValues, 250);
|
||||
foreach (decimal value in customDataIbmValues)
|
||||
{
|
||||
// do something with each low value
|
||||
// do something with each value
|
||||
}
|
||||
|
||||
// sometimes it's necessary to get the history for many configured symbols
|
||||
|
||||
// request the last year's worth of history for all configured symbols at their configured resolutions
|
||||
var allHistory = History(TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History(TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(TimeSpan.FromDays(365))", allHistory, 250, SPY, IBM);
|
||||
|
||||
// request the last days's worth of history at the minute resolution
|
||||
allHistory = History(TimeSpan.FromDays(1), Resolution.Minute);
|
||||
AssertHistoryCount("History(TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 390, SPY, IBM);
|
||||
|
||||
// request the last 100 bars for the specified securities at the configured resolution
|
||||
allHistory = History(Securities.Keys, 100);
|
||||
AssertHistoryCount("History(Securities.Keys, 100)", allHistory, 100, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(Securities.Keys, 100)", allHistory, 100, SPY, IBM);
|
||||
|
||||
// request the last 100 minute bars for the specified securities
|
||||
allHistory = History(Securities.Keys, 100, Resolution.Minute);
|
||||
AssertHistoryCount("History(Securities.Keys, 100, Resolution.Minute)", allHistory, 101, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(Securities.Keys, 100, Resolution.Minute)", allHistory, 100, SPY, IBM);
|
||||
|
||||
// request the last calendar years worth of history for the specified securities
|
||||
allHistory = History(Securities.Keys, TimeSpan.FromDays(365));
|
||||
AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(365))", allHistory, 250, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(365))", allHistory, 250, SPY, IBM);
|
||||
// we can also specify the resolution
|
||||
allHistory = History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute);
|
||||
AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 391, SPY, CME_SP1);
|
||||
AssertHistoryCount("History(Securities.Keys, TimeSpan.FromDays(1), Resolution.Minute)", allHistory, 390, SPY, IBM);
|
||||
|
||||
// if we loop over this allHistory, we get Slice objects
|
||||
foreach (Slice slice in allHistory)
|
||||
@@ -215,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
|
||||
if (_count > 5)
|
||||
{
|
||||
throw new Exception("Invalid number of bars arrived. Expected exactly 5");
|
||||
throw new Exception($"Invalid number of bars arrived. Expected exactly 5, but received {_count}");
|
||||
}
|
||||
|
||||
if (!Portfolio.Invested)
|
||||
@@ -245,9 +243,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
else if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(DataDictionary<>))
|
||||
{
|
||||
if (typeof(T).GetGenericArguments()[0] == typeof(QuandlFuture))
|
||||
if (typeof(T).GetGenericArguments()[0] == typeof(CustomData))
|
||||
{
|
||||
var dictionaries = (IEnumerable<DataDictionary<QuandlFuture>>) history;
|
||||
var dictionaries = (IEnumerable<DataDictionary<CustomData>>) history;
|
||||
unexpectedSymbols = dictionaries.SelectMany(dd => dd.Keys)
|
||||
.Distinct()
|
||||
.Where(sym => !expectedSymbols.Contains(sym))
|
||||
@@ -340,19 +338,5 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "33d01821923c397f999cfb2e5b5928ad"}
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.
|
||||
/// </summary>
|
||||
public class QuandlFuture : Quandl
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="QuandlFuture"/> class.
|
||||
/// </summary>
|
||||
public QuandlFuture()
|
||||
: base(valueColumnName: "Settle")
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,12 +195,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.836"},
|
||||
{"Beta", "-0.217"},
|
||||
{"Beta", "-0.228"},
|
||||
{"Annual Standard Deviation", "0.345"},
|
||||
{"Annual Variance", "0.119"},
|
||||
{"Information Ratio", "4.66"},
|
||||
{"Tracking Error", "0.382"},
|
||||
{"Treynor Ratio", "-8.405"},
|
||||
{"Information Ratio", "4.653"},
|
||||
{"Tracking Error", "0.383"},
|
||||
{"Treynor Ratio", "-8.001"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
@@ -223,7 +223,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6dda4f153b0be9fdf55026da439f90f6"}
|
||||
{"OrderListHash", "25cc4301125ffaa12dd8d8f4387adf06"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,13 +173,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "2.168"},
|
||||
{"Beta", "-0.226"},
|
||||
{"Alpha", "2.169"},
|
||||
{"Beta", "-0.238"},
|
||||
{"Annual Standard Deviation", "0.373"},
|
||||
{"Annual Variance", "0.139"},
|
||||
{"Information Ratio", "5.177"},
|
||||
{"Tracking Error", "0.408"},
|
||||
{"Treynor Ratio", "-9.544"},
|
||||
{"Information Ratio", "5.17"},
|
||||
{"Tracking Error", "0.409"},
|
||||
{"Treynor Ratio", "-9.071"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$44000000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
@@ -202,7 +202,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "3cccf8c2409ee8a9020ba79a6c45742a"}
|
||||
{"OrderListHash", "bd96db56c80107572e8fc13c8794279b"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.334"},
|
||||
{"Tracking Error", "0.138"},
|
||||
{"Treynor Ratio", "-3.273"},
|
||||
{"Treynor Ratio", "-9.47"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$22000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
@@ -213,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "177477b78d9264384a09f1607e8c7d11"}
|
||||
{"OrderListHash", "e971949fb0d1cc8d034ad7cba97d09cc"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,13 +199,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Loss Rate", "100%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.682"},
|
||||
{"Beta", "0.204"},
|
||||
{"Alpha", "-0.683"},
|
||||
{"Beta", "0.218"},
|
||||
{"Annual Standard Deviation", "0.356"},
|
||||
{"Annual Variance", "0.126"},
|
||||
{"Information Ratio", "-1.936"},
|
||||
{"Tracking Error", "0.371"},
|
||||
{"Treynor Ratio", "-3.293"},
|
||||
{"Information Ratio", "-1.94"},
|
||||
{"Tracking Error", "0.37"},
|
||||
{"Treynor Ratio", "-3.083"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX 31KC0UJHC75TA|SPX 31"},
|
||||
@@ -228,7 +228,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "f2d98f952cc0b54fb620795018682105"}
|
||||
{"OrderListHash", "6df8b200489a2f217cd514592ee98663"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.595"},
|
||||
{"Tracking Error", "0.137"},
|
||||
{"Treynor Ratio", "-5.196"},
|
||||
{"Treynor Ratio", "-5.349"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"},
|
||||
@@ -212,7 +212,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6faffe52c64c2148458af1d2deb68a6f"}
|
||||
{"OrderListHash", "b0c50080f0229facd065721f1f5d715e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,13 +185,13 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.67"},
|
||||
{"Beta", "0.197"},
|
||||
{"Alpha", "-0.671"},
|
||||
{"Beta", "0.211"},
|
||||
{"Annual Standard Deviation", "0.344"},
|
||||
{"Annual Variance", "0.118"},
|
||||
{"Information Ratio", "-1.96"},
|
||||
{"Tracking Error", "0.361"},
|
||||
{"Treynor Ratio", "-3.349"},
|
||||
{"Information Ratio", "-1.963"},
|
||||
{"Tracking Error", "0.36"},
|
||||
{"Treynor Ratio", "-3.133"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P3GHDZXQ|SPX 31"},
|
||||
@@ -214,7 +214,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "439042b39981ea246e50728cc57c31c7"}
|
||||
{"OrderListHash", "856448f4cbba4fc39af8dba369c054df"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.32"},
|
||||
{"Tracking Error", "0.138"},
|
||||
{"Treynor Ratio", "-3.277"},
|
||||
{"Treynor Ratio", "-9.479"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$22000.00"},
|
||||
{"Lowest Capacity Asset", "SPX XL80P59H5E6M|SPX 31"},
|
||||
@@ -206,7 +206,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "b55e2b2bd35bc3200e228b4e6e77dd90"}
|
||||
{"OrderListHash", "76ffdfc100ba7778009e35966bd92cfc"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,12 +190,12 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "1.938"},
|
||||
{"Beta", "-0.224"},
|
||||
{"Beta", "-0.235"},
|
||||
{"Annual Standard Deviation", "0.356"},
|
||||
{"Annual Variance", "0.127"},
|
||||
{"Information Ratio", "4.793"},
|
||||
{"Information Ratio", "4.787"},
|
||||
{"Tracking Error", "0.393"},
|
||||
{"Treynor Ratio", "-8.593"},
|
||||
{"Treynor Ratio", "-8.187"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX 31KC0UJHC75TA|SPX 31"},
|
||||
@@ -218,7 +218,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "f243341674cb1486d7cf009d74d4e6ff"}
|
||||
{"OrderListHash", "77d9040316634cb6b9e8cd2e4e192fd5"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-0.066"},
|
||||
{"Tracking Error", "0.139"},
|
||||
{"Treynor Ratio", "-4.611"},
|
||||
{"Treynor Ratio", "-4.733"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"},
|
||||
@@ -205,7 +205,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "636b79bb5bf3db20eeda02ccf1064d07"}
|
||||
{"OrderListHash", "12861ef440f68994997aeb24c8027748"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
202
Algorithm.CSharp/IndiaDataRegressionAlgorithm.cs
Normal file
202
Algorithm.CSharp/IndiaDataRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Regression algorithm demonstrating use of map files with India data
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="India data" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
/// <meta name="tag" content="rename event" />
|
||||
/// <meta name="tag" content="map" />
|
||||
/// <meta name="tag" content="mapping" />
|
||||
/// <meta name="tag" content="map files" />
|
||||
public class IndiaDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _mappingSymbol, _splitAndDividendSymbol;
|
||||
private bool _initialMapping;
|
||||
private bool _executionMapping;
|
||||
private bool _receivedWarningEvent;
|
||||
private bool _receivedOccurredEvent;
|
||||
|
||||
/// <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()
|
||||
{
|
||||
SetAccountCurrency("INR"); //Set Account Currency
|
||||
SetStartDate(2004, 5, 20); //Set Start Date
|
||||
SetEndDate(2016, 7, 26); //Set End Date
|
||||
_mappingSymbol = AddEquity("3MINDIA", Resolution.Daily, Market.India).Symbol;
|
||||
_splitAndDividendSymbol = AddEquity("CCCL", Resolution.Daily, Market.India).Symbol;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the data event.
|
||||
/// </summary>
|
||||
/// <param name="data">Data.</param>
|
||||
public void OnData(Dividends data)
|
||||
{
|
||||
if (data.ContainsKey(_splitAndDividendSymbol))
|
||||
{
|
||||
var dividend = data[_splitAndDividendSymbol];
|
||||
if (Time.Date == new DateTime(2010, 06, 15) &&
|
||||
(dividend.Price != 0.5m || dividend.ReferencePrice != 88.8m || dividend.Distribution != 0.5m))
|
||||
{
|
||||
throw new Exception("Did not receive expected dividend values");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises the data event.
|
||||
/// </summary>
|
||||
/// <param name="data">Data.</param>
|
||||
public void OnData(Splits data)
|
||||
{
|
||||
if (data.ContainsKey(_splitAndDividendSymbol))
|
||||
{
|
||||
var split = data[_splitAndDividendSymbol];
|
||||
if (split.Type == SplitType.Warning)
|
||||
{
|
||||
_receivedWarningEvent = true;
|
||||
}
|
||||
else if (split.Type == SplitType.SplitOccurred)
|
||||
{
|
||||
_receivedOccurredEvent = true;
|
||||
if (split.Price != 421m || split.ReferencePrice != 421m || split.SplitFactor != 0.2m)
|
||||
{
|
||||
throw new Exception("Did not receive expected split values");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks the symbol change event
|
||||
/// </summary>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
if (slice.SymbolChangedEvents.ContainsKey(_mappingSymbol))
|
||||
{
|
||||
var mappingEvent = slice.SymbolChangedEvents.Single(x => x.Key.SecurityType == SecurityType.Equity).Value;
|
||||
Log($"{Time} - Ticker changed from: {mappingEvent.OldSymbol} to {mappingEvent.NewSymbol}");
|
||||
if (Time.Date == new DateTime(1999, 01, 01))
|
||||
{
|
||||
_initialMapping = true;
|
||||
}
|
||||
else if (Time.Date == new DateTime(2004, 06, 15))
|
||||
{
|
||||
if (mappingEvent.NewSymbol == "3MINDIA"
|
||||
&& mappingEvent.OldSymbol == "BIRLA3M")
|
||||
{
|
||||
_executionMapping = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Final step of the algorithm
|
||||
/// </summary>
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
if (_initialMapping)
|
||||
{
|
||||
throw new Exception("The ticker generated the initial rename event");
|
||||
}
|
||||
if (!_executionMapping)
|
||||
{
|
||||
throw new Exception("The ticker did not rename throughout the course of its life even though it should have");
|
||||
}
|
||||
if (!_receivedOccurredEvent)
|
||||
{
|
||||
throw new Exception("Did not receive expected split event");
|
||||
}
|
||||
if (!_receivedWarningEvent)
|
||||
{
|
||||
throw new Exception("Did not receive expected split warning event");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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", "0"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$0.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", ""},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "79228162514264337593543950335"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "₹0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "₹0"},
|
||||
{"Mean Population Estimated Insight Value", "₹0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Custom;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
@@ -34,7 +33,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public class IndicatorSuiteAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private string _ticker = "SPY";
|
||||
private string _customTicker = "WIKI/FB";
|
||||
private string _customTicker = "IBM";
|
||||
|
||||
private Symbol _symbol;
|
||||
private Symbol _customSymbol;
|
||||
@@ -64,7 +63,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
_symbol = AddSecurity(SecurityType.Equity, _ticker, Resolution.Daily).Symbol;
|
||||
|
||||
//Add the Custom Data:
|
||||
_customSymbol = AddData<Quandl>(_customTicker, Resolution.Daily).Symbol;
|
||||
_customSymbol = AddData<CustomData>(_customTicker, Resolution.Daily).Symbol;
|
||||
|
||||
//Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
|
||||
_indicators = new Indicators
|
||||
@@ -118,9 +117,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
// these are indicators that require multiple inputs. the most common of which is a ratio.
|
||||
// suppose we seek the ratio of BTC to SPY, we could write the following:
|
||||
var spyClose = Identity(_symbol);
|
||||
var fbClose = Identity(_customSymbol);
|
||||
var ibmClose = Identity(_customSymbol);
|
||||
// this will create a new indicator whose value is FB/SPY
|
||||
_ratio = fbClose.Over(spyClose);
|
||||
_ratio = ibmClose.Over(spyClose);
|
||||
// we can also easily plot our indicators each time they update using th PlotIndicator function
|
||||
PlotIndicator("Ratio", _ratio);
|
||||
}
|
||||
@@ -128,8 +127,8 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <summary>
|
||||
/// Custom data event handler:
|
||||
/// </summary>
|
||||
/// <param name="data">Quandl - dictionary Bars of Quandl Data</param>
|
||||
public void OnData(Quandl data)
|
||||
/// <param name="data">CustomData - dictionary Bars of custom data</param>
|
||||
public void OnData(CustomData data)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -18,6 +18,7 @@ using QuantConnect.Indicators;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Storage;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
@@ -29,7 +30,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// history call. This pattern can be equally applied to a machine learning model being
|
||||
/// trained and then saving the model weights in the object store.
|
||||
/// </summary>
|
||||
public class ObjectStoreExampleAlgorithm : QCAlgorithm
|
||||
public class ObjectStoreExampleAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string SPY_Close_ObjectStore_Key = "spy_close";
|
||||
private Symbol SPY;
|
||||
@@ -127,5 +128,64 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, Language.Python };
|
||||
|
||||
/// <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", "1"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "271.453%"},
|
||||
{"Drawdown", "2.200%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "1.692%"},
|
||||
{"Sharpe Ratio", "8.888"},
|
||||
{"Probabilistic Sharpe Ratio", "67.609%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.005"},
|
||||
{"Beta", "0.996"},
|
||||
{"Annual Standard Deviation", "0.222"},
|
||||
{"Annual Variance", "0.049"},
|
||||
{"Information Ratio", "-14.565"},
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "1.978"},
|
||||
{"Total Fees", "$3.44"},
|
||||
{"Estimated Strategy Capacity", "$56000000.00"},
|
||||
{"Lowest Capacity Asset", "SPY R735QTJ8XC9X"},
|
||||
{"Fitness Score", "0.248"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "93.728"},
|
||||
{"Portfolio Turnover", "0.248"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "9e4bfd2eb0b81ee5bc1b197a87ccedbe"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2015, 12, 23);
|
||||
SetEndDate(2015, 12, 24);
|
||||
SetEndDate(2015, 12, 28);
|
||||
SetCash(100000);
|
||||
Stock = AddEquity("GOOG", Resolution.Minute);
|
||||
|
||||
@@ -78,33 +78,33 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "24"},
|
||||
{"Average Win", "0%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "0%"},
|
||||
{"Drawdown", "0%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "0%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
{"Average Win", "9.60%"},
|
||||
{"Average Loss", "-16.86%"},
|
||||
{"Compounding Annual Return", "-75.533%"},
|
||||
{"Drawdown", "2.300%"},
|
||||
{"Expectancy", "0.046"},
|
||||
{"Net Profit", "-2.162%"},
|
||||
{"Sharpe Ratio", "-6.761"},
|
||||
{"Probabilistic Sharpe Ratio", "1.125%"},
|
||||
{"Loss Rate", "33%"},
|
||||
{"Win Rate", "67%"},
|
||||
{"Profit-Loss Ratio", "0.57"},
|
||||
{"Alpha", "-0.01"},
|
||||
{"Beta", "0.455"},
|
||||
{"Annual Standard Deviation", "0.014"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "0"},
|
||||
{"Tracking Error", "0"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Information Ratio", "6.047"},
|
||||
{"Tracking Error", "0.015"},
|
||||
{"Treynor Ratio", "-0.207"},
|
||||
{"Total Fees", "$12.00"},
|
||||
{"Estimated Strategy Capacity", "$310000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.5"},
|
||||
{"Estimated Strategy Capacity", "$1100000.00"},
|
||||
{"Lowest Capacity Asset", "GOOCV 305RBQ20WHPNQ|GOOCV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.057"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "79228162514264337593543950335"},
|
||||
{"Return Over Maximum Drawdown", "-50.725"},
|
||||
{"Portfolio Turnover", "8.14"},
|
||||
{"Sortino Ratio", "-3.876"},
|
||||
{"Return Over Maximum Drawdown", "-35.706"},
|
||||
{"Portfolio Turnover", "3.258"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
@@ -118,7 +118,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "58557574cf0489dd38fb37768f509ca1"}
|
||||
{"OrderListHash", "a0e8eeee1c31968b773ebdf47bb996df"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "6f6d53762c0bb64467ee6215b2aa57c9"}
|
||||
{"OrderListHash", "b657be3f1b7f7f59cc7f260c99a89d00"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,16 +124,16 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0.30%"},
|
||||
{"Average Loss", "-0.33%"},
|
||||
{"Average Loss", "-0.32%"},
|
||||
{"Compounding Annual Return", "-24.104%"},
|
||||
{"Drawdown", "0.400%"},
|
||||
{"Expectancy", "-0.358"},
|
||||
{"Expectancy", "-0.359"},
|
||||
{"Net Profit", "-0.352%"},
|
||||
{"Sharpe Ratio", "0"},
|
||||
{"Probabilistic Sharpe Ratio", "0%"},
|
||||
{"Loss Rate", "67%"},
|
||||
{"Win Rate", "33%"},
|
||||
{"Profit-Loss Ratio", "0.93"},
|
||||
{"Profit-Loss Ratio", "0.92"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0"},
|
||||
@@ -163,7 +163,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "091c92055026a8323accb4508a68bf3f"}
|
||||
{"OrderListHash", "c764f59736091ece264bd2f959eae97c"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
202
Algorithm.CSharp/OptionRenameDailyRegressionAlgorithm.cs
Normal file
202
Algorithm.CSharp/OptionRenameDailyRegressionAlgorithm.cs
Normal file
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* 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;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Data.Market;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// This is an option split regression algorithm
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="options" />
|
||||
/// <meta name="tag" content="regression test" />
|
||||
public class OptionRenameDailyRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private Symbol _optionSymbol;
|
||||
private Symbol _contractSymbol;
|
||||
private Symbol _underlyingSymbol;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
// this test opens position in the first day of trading, lives through stock rename (NWSA->FOXA), dividends, and closes adjusted position on the third day
|
||||
SetStartDate(2013, 06, 27);
|
||||
SetEndDate(2013, 07, 02);
|
||||
SetCash(1000000);
|
||||
|
||||
var option = AddOption("NWSA", Resolution.Daily);
|
||||
_optionSymbol = option.Symbol;
|
||||
|
||||
// set our strike/expiry filter for this option chain
|
||||
option.SetFilter(-1, +1, TimeSpan.Zero, TimeSpan.MaxValue);
|
||||
|
||||
// use the underlying equity as the benchmark
|
||||
SetBenchmark("NWSA");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
|
||||
/// </summary>
|
||||
/// <param name="slice">The current slice of data keyed by symbol string</param>
|
||||
public override void OnData(Slice slice)
|
||||
{
|
||||
foreach (var dividend in slice.Dividends.Values)
|
||||
{
|
||||
if (dividend.ReferencePrice != 32.6m || dividend.Distribution != 3.82m)
|
||||
{
|
||||
throw new Exception($"{Time} - Invalid dividend {dividend}");
|
||||
}
|
||||
}
|
||||
if (!Portfolio.Invested)
|
||||
{
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
|
||||
{
|
||||
var contract =
|
||||
chain.OrderBy(x => x.Expiry)
|
||||
.Where(x => x.Right == OptionRight.Call && x.Strike == 33 && x.Expiry.Date == new DateTime(2013, 08, 17))
|
||||
.FirstOrDefault();
|
||||
|
||||
if (contract != null)
|
||||
{
|
||||
// Buying option
|
||||
_contractSymbol = contract.Symbol;
|
||||
Buy(_contractSymbol, 1);
|
||||
|
||||
// Buying the underlying stock
|
||||
_underlyingSymbol = contract.Symbol.Underlying;
|
||||
Buy(_underlyingSymbol, 100);
|
||||
|
||||
// Check
|
||||
if (slice.Time != new DateTime(2013, 6, 28))
|
||||
{
|
||||
throw new Exception(@"Received first contract at {slice.Time}; Expected at 6/28/2013 12AM.");
|
||||
}
|
||||
|
||||
if (contract.AskPrice != 1.15m)
|
||||
{
|
||||
throw new Exception("Current ask price was not loaded from NWSA backtest file and is not $1.1");
|
||||
}
|
||||
|
||||
if (contract.UnderlyingSymbol.Value != "NWSA")
|
||||
{
|
||||
throw new Exception("Contract underlying symbol was not NWSA as expected");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (slice.Time.Day == 3) // Final day
|
||||
{
|
||||
// selling positions
|
||||
Liquidate();
|
||||
|
||||
// checks
|
||||
OptionChain chain;
|
||||
if (slice.OptionChains.TryGetValue(_optionSymbol, out chain))
|
||||
{
|
||||
if (chain.Underlying.Symbol.Value != "FOXA")
|
||||
{
|
||||
throw new Exception("Chain underlying symbol was not FOXA as expected");
|
||||
}
|
||||
|
||||
var contract =
|
||||
chain.OrderBy(x => x.Expiry)
|
||||
.Where(x => x.Right == OptionRight.Call && x.Strike == 33 && x.Expiry.Date == new DateTime(2013, 08, 17))
|
||||
.FirstOrDefault();
|
||||
|
||||
if (contract.BidPrice != 0.05m)
|
||||
{
|
||||
throw new Exception("Current bid price was not loaded from FOXA file and is not $0.05");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
|
||||
/// </summary>
|
||||
/// <param name="orderEvent">Order event details containing details of the evemts</param>
|
||||
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
|
||||
public override void OnOrderEvent(OrderEvent orderEvent)
|
||||
{
|
||||
Log(orderEvent.ToString());
|
||||
}
|
||||
|
||||
/// <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%"},
|
||||
{"Compounding Annual Return", "-0.273%"},
|
||||
{"Drawdown", "0.000%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-0.004%"},
|
||||
{"Sharpe Ratio", "-2.264"},
|
||||
{"Probabilistic Sharpe Ratio", "32.662%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "0%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "0"},
|
||||
{"Beta", "0"},
|
||||
{"Annual Standard Deviation", "0.001"},
|
||||
{"Annual Variance", "0"},
|
||||
{"Information Ratio", "-2.264"},
|
||||
{"Tracking Error", "0.001"},
|
||||
{"Treynor Ratio", "0"},
|
||||
{"Total Fees", "$2.00"},
|
||||
{"Estimated Strategy Capacity", "$0"},
|
||||
{"Lowest Capacity Asset", "NWSA VJ5IKAXU7WBQ|NWSA T3MO1488O0H1"},
|
||||
{"Fitness Score", "0"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-1.168"},
|
||||
{"Return Over Maximum Drawdown", "-6.338"},
|
||||
{"Portfolio Turnover", "0"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
{"Total Insights Analysis Completed", "0"},
|
||||
{"Long Insight Count", "0"},
|
||||
{"Short Insight Count", "0"},
|
||||
{"Long/Short Ratio", "100%"},
|
||||
{"Estimated Monthly Alpha Value", "$0"},
|
||||
{"Total Accumulated Estimated Alpha Value", "$0"},
|
||||
{"Mean Population Estimated Insight Value", "$0"},
|
||||
{"Mean Population Direction", "0%"},
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "8b89135535d842f6df7b2849d6604fbd"}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ using System.Collections.Generic;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
using QuantConnect.Orders;
|
||||
using System.Linq;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
@@ -473,6 +474,62 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
return Time.Day == day && Time.Hour == hour && Time.Minute == minute;
|
||||
}
|
||||
|
||||
public override void OnEndOfAlgorithm()
|
||||
{
|
||||
Func<OrderTicket, bool> basicOrderTicketFilter = x => x.Symbol == symbol;
|
||||
|
||||
var filledOrders = Transactions.GetOrders(x => x.Status == OrderStatus.Filled);
|
||||
var orderTickets = Transactions.GetOrderTickets(basicOrderTicketFilter);
|
||||
var openOrders = Transactions.GetOpenOrders(x => x.Symbol == symbol);
|
||||
var openOrderTickets = Transactions.GetOpenOrderTickets(basicOrderTicketFilter);
|
||||
var remainingOpenOrders = Transactions.GetOpenOrdersRemainingQuantity(basicOrderTicketFilter);
|
||||
|
||||
if (filledOrders.Count() != 8 || orderTickets.Count() != 10)
|
||||
{
|
||||
throw new Exception($"There were expected 8 filled orders and 10 order tickets");
|
||||
}
|
||||
if (openOrders.Count != 0 || openOrderTickets.Any())
|
||||
{
|
||||
throw new Exception($"No open orders or tickets were expected");
|
||||
}
|
||||
if (remainingOpenOrders != 0m)
|
||||
{
|
||||
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
|
||||
}
|
||||
|
||||
var symbolOpenOrders = Transactions.GetOpenOrders(symbol).Count;
|
||||
var symbolOpenOrdersTickets = Transactions.GetOpenOrderTickets(symbol).Count();
|
||||
var symbolOpenOrdersRemainingQuantity = Transactions.GetOpenOrdersRemainingQuantity(symbol);
|
||||
|
||||
if (symbolOpenOrders != 0 || symbolOpenOrdersTickets != 0)
|
||||
{
|
||||
throw new Exception($"No open orders or tickets were expected");
|
||||
}
|
||||
if (symbolOpenOrdersRemainingQuantity != 0)
|
||||
{
|
||||
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
|
||||
}
|
||||
|
||||
var defaultOrders = Transactions.GetOrders();
|
||||
var defaultOrderTickets = Transactions.GetOrderTickets();
|
||||
var defaultOpenOrders = Transactions.GetOpenOrders();
|
||||
var defaultOpenOrderTickets = Transactions.GetOpenOrderTickets();
|
||||
var defaultOpenOrdersRemaining = Transactions.GetOpenOrdersRemainingQuantity();
|
||||
|
||||
if (defaultOrders.Count() != 10 || defaultOrderTickets.Count() != 10)
|
||||
{
|
||||
throw new Exception($"There were expected 10 orders and 10 order tickets");
|
||||
}
|
||||
if (defaultOpenOrders.Count != 0 || defaultOpenOrderTickets.Any())
|
||||
{
|
||||
throw new Exception($"No open orders or tickets were expected");
|
||||
}
|
||||
if (defaultOpenOrdersRemaining != 0m)
|
||||
{
|
||||
throw new Exception($"No remaining quantiy to be filled from open orders was expected");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
|
||||
@@ -28,9 +28,9 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
/// <meta name="tag" content="using quantconnect" />
|
||||
public class ParameterizedAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
// we place attributes on top of our fields or properties that should receive
|
||||
// We place attributes on top of our fields or properties that should receive
|
||||
// their values from the job. The values 100 and 200 are just default values that
|
||||
// or only used if the parameters do not exist
|
||||
// are only used if the parameters do not exist.
|
||||
[Parameter("ema-fast")]
|
||||
public int FastPeriod = 100;
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data.Custom;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Futures demonstration algorithm.
|
||||
/// QuantConnect allows importing generic data sources! This example demonstrates importing a futures
|
||||
/// data from the popular open data source Quandl. QuantConnect has a special deal with Quandl giving you access
|
||||
/// to Stevens Continuous Futurs (SCF) for free. If you'd like to download SCF for local backtesting, you can download it through Quandl.com.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="quandl" />
|
||||
/// <meta name="tag" content="custom data" />
|
||||
/// <meta name="tag" content="futures" />
|
||||
public class QCUQuandlFutures : QCAlgorithm
|
||||
{
|
||||
private string _crude = "SCF/CME_CL1_ON";
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the data and resolution you require for your strategy
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
SetStartDate(2000, 1, 1);
|
||||
SetEndDate(DateTime.Now.Date.AddDays(-1));
|
||||
SetCash(25000);
|
||||
AddData<QuandlFuture>(_crude, Resolution.Daily);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
|
||||
/// </summary>
|
||||
/// <param name="data">Data.</param>
|
||||
public void OnData(Quandl data)
|
||||
{
|
||||
if (!Portfolio.HoldStock)
|
||||
{
|
||||
SetHoldings(_crude, 1);
|
||||
Debug(Time.ToStringInvariant("u") + " Purchased Crude Oil: " + _crude);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.
|
||||
/// </summary>
|
||||
public class QuandlFuture : Quandl
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="QuandlFuture"/> class.
|
||||
/// </summary>
|
||||
public QuandlFuture()
|
||||
: base(valueColumnName: "Settle")
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* 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 QuantConnect.Data.Custom;
|
||||
using QuantConnect.Indicators;
|
||||
|
||||
namespace QuantConnect.Algorithm.CSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// Using the underlying dynamic data class "Quandl" QuantConnect take care of the data
|
||||
/// importing and definition for you. Simply point QuantConnect to the Quandl Short Code.
|
||||
/// The Quandl object has properties which match the spreadsheet headers.
|
||||
/// If you have multiple quandl streams look at data.Symbol to distinguish them.
|
||||
/// </summary>
|
||||
/// <meta name="tag" content="custom data" />
|
||||
/// <meta name="tag" content="using data" />
|
||||
/// <meta name="tag" content="quandl" />
|
||||
public class QuandlImporterAlgorithm : QCAlgorithm
|
||||
{
|
||||
private SimpleMovingAverage _sma;
|
||||
string _quandlCode = "WIKI/IBM";
|
||||
|
||||
/// Initialize the data and resolution you require for your strategy:
|
||||
public override void Initialize()
|
||||
{
|
||||
//Start and End Date range for the backtest:
|
||||
SetStartDate(2013, 1, 1);
|
||||
SetEndDate(DateTime.Now.Date.AddDays(-1));
|
||||
|
||||
//Cash allocation
|
||||
SetCash(25000);
|
||||
|
||||
// Optional argument - personal token necessary for restricted dataset
|
||||
// Quandl.SetAuthCode("your-quandl-token");
|
||||
|
||||
//Add Generic Quandl Data:
|
||||
AddData<Quandl>(_quandlCode, Resolution.Daily);
|
||||
|
||||
_sma = SMA(_quandlCode, 14);
|
||||
}
|
||||
|
||||
/// Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol
|
||||
public void OnData(Quandl data)
|
||||
{
|
||||
if (!Portfolio.HoldStock)
|
||||
{
|
||||
//Order function places trades: enter the string symbol and the quantity you want:
|
||||
SetHoldings(_quandlCode, 1);
|
||||
|
||||
//Debug sends messages to the user console: "Time" is the algorithm time keeper object
|
||||
Debug("Purchased " + _quandlCode + " >> " + Time.ToShortDateString());
|
||||
}
|
||||
|
||||
Plot("SPY", _sma);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@
|
||||
<DebugType>portable</DebugType>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.10" />
|
||||
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.11" />
|
||||
<PackageReference Include="Accord" Version="3.6.0" />
|
||||
<PackageReference Include="Accord.Fuzzy" Version="3.6.0" />
|
||||
<PackageReference Include="Accord.MachineLearning" Version="3.6.0" />
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public class RawDataRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
||||
{
|
||||
private const string Ticker = "GOOGL";
|
||||
private FactorFile _factorFile;
|
||||
private CorporateFactorProvider _factorFile;
|
||||
private readonly IEnumerator<decimal> _expectedRawPrices = new List<decimal> { 1157.93m, 1158.72m,
|
||||
1131.97m, 1114.28m, 1120.15m, 1114.51m, 1134.89m, 567.55m, 571.50m, 545.25m, 540.63m }.GetEnumerator();
|
||||
private Symbol _googl;
|
||||
@@ -56,7 +56,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
mapFileProvider.Initialize(dataProvider);
|
||||
var factorFileProvider = new LocalDiskFactorFileProvider();
|
||||
factorFileProvider.Initialize(mapFileProvider, dataProvider);
|
||||
_factorFile = factorFileProvider.Get(_googl);
|
||||
_factorFile = factorFileProvider.Get(_googl) as CorporateFactorProvider;
|
||||
|
||||
// Prime our expected values
|
||||
_expectedRawPrices.MoveNext();
|
||||
@@ -81,7 +81,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
if (_expectedRawPrices.Current != googlData.Close)
|
||||
{
|
||||
// Our values don't match lets try and give a reason why
|
||||
var dayFactor = _factorFile.GetPriceScaleFactor(googlData.Time);
|
||||
var dayFactor = _factorFile.GetPriceFactor(googlData.Time, DataNormalizationMode.Adjusted);
|
||||
var probableRawPrice = googlData.Close / dayFactor; // Undo adjustment
|
||||
|
||||
if (_expectedRawPrices.Current == probableRawPrice)
|
||||
|
||||
@@ -69,16 +69,6 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
throw new Exception("Was expecting resolution to be set to Hour");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
AddOption("AAPL", Resolution.Daily);
|
||||
throw new Exception("Was expecting an ArgumentException to be thrown");
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// expected, options only support minute resolution
|
||||
}
|
||||
|
||||
var option = AddOption("AAPL");
|
||||
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(option.Symbol)
|
||||
.Any(config => config.Resolution != Resolution.Minute))
|
||||
|
||||
@@ -173,32 +173,32 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
||||
{
|
||||
{"Total Trades", "4"},
|
||||
{"Average Win", "0.64%"},
|
||||
{"Average Win", "0.71%"},
|
||||
{"Average Loss", "0%"},
|
||||
{"Compounding Annual Return", "-56.617%"},
|
||||
{"Drawdown", "3.800%"},
|
||||
{"Compounding Annual Return", "-55.953%"},
|
||||
{"Drawdown", "3.700%"},
|
||||
{"Expectancy", "0"},
|
||||
{"Net Profit", "-3.815%"},
|
||||
{"Sharpe Ratio", "-2.708"},
|
||||
{"Probabilistic Sharpe Ratio", "13.091%"},
|
||||
{"Net Profit", "-3.747%"},
|
||||
{"Sharpe Ratio", "-2.668"},
|
||||
{"Probabilistic Sharpe Ratio", "13.421%"},
|
||||
{"Loss Rate", "0%"},
|
||||
{"Win Rate", "100%"},
|
||||
{"Profit-Loss Ratio", "0"},
|
||||
{"Alpha", "-0.275"},
|
||||
{"Beta", "1.237"},
|
||||
{"Alpha", "-0.268"},
|
||||
{"Beta", "1.241"},
|
||||
{"Annual Standard Deviation", "0.167"},
|
||||
{"Annual Variance", "0.028"},
|
||||
{"Information Ratio", "-2.491"},
|
||||
{"Information Ratio", "-2.443"},
|
||||
{"Tracking Error", "0.124"},
|
||||
{"Treynor Ratio", "-0.365"},
|
||||
{"Total Fees", "$4.00"},
|
||||
{"Treynor Ratio", "-0.358"},
|
||||
{"Total Fees", "$3.00"},
|
||||
{"Estimated Strategy Capacity", "$870000.00"},
|
||||
{"Lowest Capacity Asset", "GOOAV VP83T1ZUHROL"},
|
||||
{"Fitness Score", "0.008"},
|
||||
{"Kelly Criterion Estimate", "0"},
|
||||
{"Kelly Criterion Probability Value", "0"},
|
||||
{"Sortino Ratio", "-3.836"},
|
||||
{"Return Over Maximum Drawdown", "-14.841"},
|
||||
{"Sortino Ratio", "-3.793"},
|
||||
{"Return Over Maximum Drawdown", "-14.933"},
|
||||
{"Portfolio Turnover", "0.135"},
|
||||
{"Total Insights Generated", "0"},
|
||||
{"Total Insights Closed", "0"},
|
||||
@@ -213,7 +213,7 @@ namespace QuantConnect.Algorithm.CSharp
|
||||
{"Mean Population Magnitude", "0%"},
|
||||
{"Rolling Averaged Population Direction", "0%"},
|
||||
{"Rolling Averaged Population Magnitude", "0%"},
|
||||
{"OrderListHash", "bbc9f982183f74b34be4529acaa33fe8"}
|
||||
{"OrderListHash", "afde32cdef5e61707f85d62f62eece17"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
120
Algorithm.Framework/Alphas/AlphaStreamAlphaModule.cs
Normal file
120
Algorithm.Framework/Alphas/AlphaStreamAlphaModule.cs
Normal file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Data;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Data.Custom.AlphaStreams;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Alphas
|
||||
{
|
||||
/// <summary>
|
||||
/// Alpha model that will handle adding and removing securities from the algorithm based on the current portfolio of the different alphas
|
||||
/// </summary>
|
||||
public sealed class AlphaStreamAlphaModule : AlphaModel
|
||||
{
|
||||
private Dictionary<Symbol, HashSet<Symbol>> _symbolsPerAlpha = new Dictionary<Symbol, HashSet<Symbol>>();
|
||||
|
||||
/// <summary>
|
||||
/// Initialize new <see cref="AlphaStreamAlphaModule"/>
|
||||
/// </summary>
|
||||
public AlphaStreamAlphaModule(string name = null)
|
||||
{
|
||||
Name = name ?? "AlphaStreamAlphaModule";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates this alpha model with the latest data from the algorithm.
|
||||
/// This is called each time the algorithm receives data for subscribed securities
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="data">The new data available</param>
|
||||
/// <returns>The new insights generated</returns>
|
||||
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
|
||||
{
|
||||
foreach (var portfolioState in data.Get<AlphaStreamsPortfolioState>().Values)
|
||||
{
|
||||
ProcessPortfolioState(algorithm, portfolioState);
|
||||
}
|
||||
|
||||
return Enumerable.Empty<Insight>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
changes.FilterCustomSecurities = false;
|
||||
foreach (var addedSecurity in changes.AddedSecurities)
|
||||
{
|
||||
if (addedSecurity.Symbol.IsCustomDataType<AlphaStreamsPortfolioState>())
|
||||
{
|
||||
if (!_symbolsPerAlpha.ContainsKey(addedSecurity.Symbol))
|
||||
{
|
||||
_symbolsPerAlpha[addedSecurity.Symbol] = new HashSet<Symbol>();
|
||||
}
|
||||
// warmup alpha state, adding target securities
|
||||
ProcessPortfolioState(algorithm, addedSecurity.Cache.GetData<AlphaStreamsPortfolioState>());
|
||||
}
|
||||
}
|
||||
|
||||
algorithm.Log($"OnSecuritiesChanged: {changes}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Will handle adding and removing securities from the algorithm based on the current portfolio of the different alphas
|
||||
/// </summary>
|
||||
private void ProcessPortfolioState(QCAlgorithm algorithm, AlphaStreamsPortfolioState portfolioState)
|
||||
{
|
||||
if (portfolioState == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var alphaId = portfolioState.Symbol;
|
||||
if (!_symbolsPerAlpha.TryGetValue(alphaId, out var currentSymbols))
|
||||
{
|
||||
_symbolsPerAlpha[alphaId] = currentSymbols = new HashSet<Symbol>();
|
||||
}
|
||||
|
||||
var newSymbols = new HashSet<Symbol>(currentSymbols.Count);
|
||||
foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions).Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>())
|
||||
{
|
||||
// only add it if it's not used by any alpha (already added check)
|
||||
if (newSymbols.Add(symbol) && !UsedBySomeAlpha(symbol))
|
||||
{
|
||||
algorithm.AddSecurity(symbol,
|
||||
resolution: algorithm.UniverseSettings.Resolution,
|
||||
extendedMarketHours: algorithm.UniverseSettings.ExtendedMarketHours);
|
||||
}
|
||||
}
|
||||
_symbolsPerAlpha[alphaId] = newSymbols;
|
||||
|
||||
foreach (var symbol in currentSymbols.Where(symbol => !UsedBySomeAlpha(symbol)))
|
||||
{
|
||||
algorithm.RemoveSecurity(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
private bool UsedBySomeAlpha(Symbol asset)
|
||||
{
|
||||
return _symbolsPerAlpha.Any(pair => pair.Value.Contains(asset));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
||||
*
|
||||
@@ -35,7 +35,7 @@ namespace QuantConnect.Algorithm.Framework.Alphas
|
||||
private readonly MovingAverageType _movingAverageType;
|
||||
private readonly Resolution _resolution;
|
||||
private const decimal BounceThresholdPercent = 0.01m;
|
||||
private readonly Dictionary<Symbol, SymbolData> _symbolData;
|
||||
protected readonly Dictionary<Symbol, SymbolData> _symbolData;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MacdAlphaModel"/> class
|
||||
@@ -130,7 +130,7 @@ namespace QuantConnect.Algorithm.Framework.Alphas
|
||||
}
|
||||
}
|
||||
|
||||
class SymbolData
|
||||
public class SymbolData
|
||||
{
|
||||
public InsightDirection? PreviousDirection { get; set; }
|
||||
|
||||
@@ -147,6 +147,7 @@ namespace QuantConnect.Algorithm.Framework.Alphas
|
||||
MACD = new MovingAverageConvergenceDivergence(fastPeriod, slowPeriod, signalPeriod, movingAverageType);
|
||||
|
||||
algorithm.RegisterIndicator(security.Symbol, MACD, Consolidator);
|
||||
algorithm.WarmUpIndicator(security.Symbol, MACD, resolution);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
||||
# 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");
|
||||
@@ -98,5 +98,6 @@ class SymbolData:
|
||||
|
||||
self.Consolidator = algorithm.ResolveConsolidator(security.Symbol, resolution)
|
||||
algorithm.RegisterIndicator(security.Symbol, self.MACD, self.Consolidator)
|
||||
algorithm.WarmUpIndicator(security.Symbol, self.MACD, resolution)
|
||||
|
||||
self.PreviousDirection = None
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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.Linq;
|
||||
using QuantConnect.Logging;
|
||||
using System.Collections.Generic;
|
||||
using QuantConnect.Algorithm.Framework.Portfolio;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework
|
||||
{
|
||||
/// <summary>
|
||||
/// Custom weighting alpha streams portfolio construction model that will generate aggregated security targets taking into account all the alphas positions
|
||||
/// and a custom weighting factor for each alpha, which is also factored by the relation of the alphas portfolio value and the current algorithms portfolio value
|
||||
/// </summary>
|
||||
public class CustomWeightingAlphaStreamsPortfolioConstructionModel : EqualWeightingAlphaStreamsPortfolioConstructionModel
|
||||
{
|
||||
private Dictionary<string, decimal> _alphaWeights;
|
||||
|
||||
/// <summary>
|
||||
/// Specify a custom set of alpha portfolio weights to use
|
||||
/// </summary>
|
||||
/// <param name="alphaWeights">The alpha portfolio weights</param>
|
||||
public void SetAlphaWeights(Dictionary<string, decimal> alphaWeights)
|
||||
{
|
||||
Log.Trace($"CustomWeightingAlphaStreamsPortfolioConstructionModel.SetAlphaWeights(): new weights: [{string.Join(",", alphaWeights.Select(pair => $"{pair.Key}:{pair.Value}"))}]");
|
||||
_alphaWeights = alphaWeights;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get's the weight for an alpha
|
||||
/// </summary>
|
||||
/// <param name="alphaId">The algorithm instance that experienced the change in securities</param>
|
||||
/// <returns>The alphas weight</returns>
|
||||
public override decimal GetAlphaWeight(string alphaId)
|
||||
{
|
||||
return !_alphaWeights.TryGetValue(alphaId, out var alphaWeight) ? 0 : alphaWeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,6 @@ namespace QuantConnect.Algorithm.Framework
|
||||
|
||||
/// <summary>
|
||||
/// Invokes the provided <paramref name="add"/> and <paramref name="remove"/> functions for each
|
||||
/// <seealso cref="SecurityChanges.Added"/> and <seealso cref="SecurityChanges.Removed"/>, respectively
|
||||
/// </summary>
|
||||
/// <param name="changes">The security changes to process</param>
|
||||
/// <param name="add">Function called for each added security</param>
|
||||
@@ -126,4 +125,4 @@ namespace QuantConnect.Algorithm.Framework
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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.Collections.Generic;
|
||||
using QuantConnect.Data.UniverseSelection;
|
||||
using QuantConnect.Algorithm.Framework.Alphas;
|
||||
|
||||
namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
{
|
||||
/// <summary>
|
||||
/// Base alpha streams portfolio construction model
|
||||
/// </summary>
|
||||
public class AlphaStreamsPortfolioConstructionModel : IPortfolioConstructionModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Get's the weight for an alpha
|
||||
/// </summary>
|
||||
/// <param name="alphaId">The algorithm instance that experienced the change in securities</param>
|
||||
/// <returns>The alphas weight</returns>
|
||||
public virtual decimal GetAlphaWeight(string alphaId)
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public virtual void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create portfolio targets from the specified insights
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="insights">The insights to create portfolio targets from</param>
|
||||
/// <returns>An enumerable of portfolio targets to be sent to the execution model</returns>
|
||||
public virtual IEnumerable<IPortfolioTarget> CreateTargets(QCAlgorithm algorithm, Insight[] insights)
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
/// and an equal weighting factor for each alpha, which is also factored by the relation of the alphas portfolio value and the current algorithms portfolio value,
|
||||
/// overriding <see cref="GetAlphaWeight"/> allows custom weighting implementations
|
||||
/// </summary>
|
||||
public class EqualWeightingAlphaStreamsPortfolioConstructionModel : IPortfolioConstructionModel
|
||||
public class EqualWeightingAlphaStreamsPortfolioConstructionModel : AlphaStreamsPortfolioConstructionModel
|
||||
{
|
||||
private bool _rebalance;
|
||||
private Dictionary<Symbol, PortfolioTarget> _targetsPerSymbol;
|
||||
@@ -48,7 +48,7 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
/// <param name="algorithm">The algorithm instance</param>
|
||||
/// <param name="insights">The insights to create portfolio targets from</param>
|
||||
/// <returns>An enumerable of portfolio targets to be sent to the execution model</returns>
|
||||
public IEnumerable<IPortfolioTarget> CreateTargets(QCAlgorithm algorithm, Insight[] insights)
|
||||
public override IEnumerable<IPortfolioTarget> CreateTargets(QCAlgorithm algorithm, Insight[] insights)
|
||||
{
|
||||
if (_targetsPerSymbol == null)
|
||||
{
|
||||
@@ -104,12 +104,22 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get's the weight for an alpha
|
||||
/// </summary>
|
||||
/// <param name="alphaId">The algorithm instance that experienced the change in securities</param>
|
||||
/// <returns>The alphas weight</returns>
|
||||
public override decimal GetAlphaWeight(string alphaId)
|
||||
{
|
||||
return 1m / _targetsPerSymbolPerAlpha.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event fired each time the we add/remove securities from the data feed
|
||||
/// </summary>
|
||||
/// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
|
||||
/// <param name="changes">The security additions and removals from the algorithm</param>
|
||||
public void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
|
||||
{
|
||||
changes.FilterCustomSecurities = false;
|
||||
|
||||
@@ -153,10 +163,10 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
/// Determines the portfolio weight to give a specific alpha. Default implementation just returns equal weighting
|
||||
/// </summary>
|
||||
/// <param name="portfolioState">The alphas portfolio state to get the weight for</param>
|
||||
/// <param name="totalUsablePortfolioValue">This algorithms usable total portfolio value</param>
|
||||
/// <param name="totalUsablePortfolioValue">This algorithms usable total portfolio value, removing the free portfolio value</param>
|
||||
/// <param name="cashBook">This algorithms cash book</param>
|
||||
/// <returns>The weight to use on this alphas positions</returns>
|
||||
protected virtual decimal GetAlphaWeight(AlphaStreamsPortfolioState portfolioState,
|
||||
private decimal GetAlphaWeight(AlphaStreamsPortfolioState portfolioState,
|
||||
decimal totalUsablePortfolioValue,
|
||||
CashBook cashBook)
|
||||
{
|
||||
@@ -168,8 +178,7 @@ namespace QuantConnect.Algorithm.Framework.Portfolio
|
||||
return 0;
|
||||
}
|
||||
|
||||
var equalWeightFactor = 1m / _targetsPerSymbolPerAlpha.Count;
|
||||
return totalUsablePortfolioValue * equalWeightFactor / alphaPortfolioValueInOurAccountCurrency;
|
||||
return totalUsablePortfolioValue * GetAlphaWeight(portfolioState.AlphaId) / alphaPortfolioValueInOurAccountCurrency;
|
||||
}
|
||||
|
||||
private bool ProcessPortfolioState(AlphaStreamsPortfolioState portfolioState, QCAlgorithm algorithm)
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.10" />
|
||||
<PackageReference Include="QuantConnect.pythonnet" Version="2.0.11" />
|
||||
<PackageReference Include="Accord" Version="3.6.0" />
|
||||
<PackageReference Include="Accord.Math" Version="3.6.0" />
|
||||
<PackageReference Include="Accord.Statistics" Version="3.6.0" />
|
||||
|
||||
66
Algorithm.Python/BasicTemplateContinuousFutureAlgorithm.py
Normal file
66
Algorithm.Python/BasicTemplateContinuousFutureAlgorithm.py
Normal file
@@ -0,0 +1,66 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### Basic Continuous Futures Template Algorithm
|
||||
### </summary>
|
||||
class BasicTemplateContinuousFutureAlgorithm(QCAlgorithm):
|
||||
'''Basic template algorithm simply initializes the date range and cash'''
|
||||
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetStartDate(2013, 7, 1)
|
||||
self.SetEndDate(2014, 1, 1)
|
||||
|
||||
self._continuousContract = self.AddFuture(Futures.Indices.SP500EMini,
|
||||
dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
|
||||
dataMappingMode = DataMappingMode.LastTradingDay,
|
||||
contractDepthOffset= 0)
|
||||
|
||||
self._fast = self.SMA(self._continuousContract.Symbol, 3, Resolution.Daily)
|
||||
self._slow = self.SMA(self._continuousContract.Symbol, 10, Resolution.Daily)
|
||||
self._currentContract = None
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
|
||||
Arguments:
|
||||
data: Slice object keyed by symbol containing the stock data
|
||||
'''
|
||||
for changedEvent in data.SymbolChangedEvents.Values:
|
||||
if changedEvent.Symbol == self._continuousContract.Symbol:
|
||||
self.Log(f"SymbolChanged event: {changedEvent}")
|
||||
|
||||
if not self.Portfolio.Invested:
|
||||
if self._fast.Current.Value > self._slow.Current.Value:
|
||||
self._currentContract = self.Securities[self._continuousContract.Mapped]
|
||||
self.Buy(self._currentContract.Symbol, 1)
|
||||
elif self._fast.Current.Value < self._slow.Current.Value:
|
||||
self.Liquidate()
|
||||
|
||||
if self._currentContract is not None and self._currentContract.Symbol != self._continuousContract.Mapped:
|
||||
self.Log(f"{Time} - rolling position from {self._currentContract.Symbol} to {self._continuousContract.Mapped}")
|
||||
|
||||
currentPositionSize = self._currentContract.Holdings.Quantity
|
||||
self.Liquidate(self._currentContract.Symbol)
|
||||
self.Buy(self._continuousContract.Mapped, currentPositionSize)
|
||||
self._currentContract = self.Securities[self._continuousContract.Mapped]
|
||||
|
||||
def OnOrderEvent(self, orderEvent):
|
||||
self.Debug("Purchased Stock: {0}".format(orderEvent.Symbol))
|
||||
|
||||
def OnSecuritiesChanged(self, changes):
|
||||
self.Debug(f"{self.Time}-{changes}")
|
||||
@@ -43,6 +43,8 @@ class BasicTemplateFuturesAlgorithm(QCAlgorithm):
|
||||
benchmark = self.AddEquity("SPY")
|
||||
self.SetBenchmark(benchmark.Symbol)
|
||||
|
||||
seeder = FuncSecuritySeeder(self.GetLastKnownPrices)
|
||||
self.SetSecurityInitializer(lambda security: seeder.SeedSecurity(security))
|
||||
|
||||
def OnData(self,slice):
|
||||
if not self.Portfolio.Invested:
|
||||
@@ -70,3 +72,8 @@ class BasicTemplateFuturesAlgorithm(QCAlgorithm):
|
||||
maintenanceOvernight = buyingPowerModel.MaintenanceOvernightMarginRequirement
|
||||
initialIntraday = buyingPowerModel.InitialIntradayMarginRequirement
|
||||
maintenanceIntraday = buyingPowerModel.MaintenanceIntradayMarginRequirement
|
||||
|
||||
def OnSecuritiesChanged(self, changes):
|
||||
for addedSecurity in changes.AddedSecurities:
|
||||
if addedSecurity.Symbol.SecurityType == SecurityType.Future and not addedSecurity.Symbol.IsCanonical() and not addedSecurity.HasData:
|
||||
raise Exception(f"Future contracts did not work up as expected: {addedSecurity.Symbol}")
|
||||
|
||||
56
Algorithm.Python/BasicTemplateFuturesDailyAlgorithm.py
Normal file
56
Algorithm.Python/BasicTemplateFuturesDailyAlgorithm.py
Normal file
@@ -0,0 +1,56 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### This example demonstrates how to add futures with daily resolution.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="benchmarks" />
|
||||
### <meta name="tag" content="futures" />
|
||||
class BasicTemplateFuturesDailyAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2013, 10, 8)
|
||||
self.SetEndDate(2014, 10, 10)
|
||||
self.SetCash(1000000)
|
||||
|
||||
self.contractSymbol = None
|
||||
|
||||
# Subscribe and set our expiry filter for the futures chain
|
||||
futureSP500 = self.AddFuture(Futures.Indices.SP500EMini, Resolution.Daily)
|
||||
futureGold = self.AddFuture(Futures.Metals.Gold, Resolution.Daily)
|
||||
|
||||
# set our expiry filter for this futures chain
|
||||
# SetFilter method accepts timedelta objects or integer for days.
|
||||
# The following statements yield the same filtering criteria
|
||||
futureSP500.SetFilter(timedelta(0), timedelta(182))
|
||||
futureGold.SetFilter(0, 182)
|
||||
|
||||
|
||||
def OnData(self,slice):
|
||||
if not self.Portfolio.Invested:
|
||||
for chain in slice.FutureChains:
|
||||
# Get contracts expiring no earlier than in 90 days
|
||||
contracts = list(filter(lambda x: x.Expiry > self.Time + timedelta(90), chain.Value))
|
||||
|
||||
# if there is any contract, trade the front contract
|
||||
if len(contracts) == 0: continue
|
||||
front = sorted(contracts, key = lambda x: x.Expiry, reverse=True)[0]
|
||||
|
||||
self.contractSymbol = front.Symbol
|
||||
if self.IsMarketOpen(self.contractSymbol):
|
||||
self.MarketOrder(front.Symbol , 1)
|
||||
else:
|
||||
self.Liquidate()
|
||||
56
Algorithm.Python/BasicTemplateFuturesHourlyAlgorithm.py
Normal file
56
Algorithm.Python/BasicTemplateFuturesHourlyAlgorithm.py
Normal file
@@ -0,0 +1,56 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### This example demonstrates how to add futures with hourly resolution.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="benchmarks" />
|
||||
### <meta name="tag" content="futures" />
|
||||
class BasicTemplateFuturesHourlyAlgorithm(QCAlgorithm):
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2013, 10, 8)
|
||||
self.SetEndDate(2014, 10, 10)
|
||||
self.SetCash(1000000)
|
||||
|
||||
self.contractSymbol = None
|
||||
|
||||
# Subscribe and set our expiry filter for the futures chain
|
||||
futureSP500 = self.AddFuture(Futures.Indices.SP500EMini, Resolution.Hour)
|
||||
futureGold = self.AddFuture(Futures.Metals.Gold, Resolution.Hour)
|
||||
|
||||
# set our expiry filter for this futures chain
|
||||
# SetFilter method accepts timedelta objects or integer for days.
|
||||
# The following statements yield the same filtering criteria
|
||||
futureSP500.SetFilter(timedelta(0), timedelta(182))
|
||||
futureGold.SetFilter(0, 182)
|
||||
|
||||
|
||||
def OnData(self,slice):
|
||||
if not self.Portfolio.Invested:
|
||||
for chain in slice.FutureChains:
|
||||
# Get contracts expiring no earlier than in 90 days
|
||||
contracts = list(filter(lambda x: x.Expiry > self.Time + timedelta(90), chain.Value))
|
||||
|
||||
# if there is any contract, trade the front contract
|
||||
if len(contracts) == 0: continue
|
||||
front = sorted(contracts, key = lambda x: x.Expiry, reverse=True)[0]
|
||||
|
||||
self.contractSymbol = front.Symbol
|
||||
if self.IsMarketOpen(self.contractSymbol):
|
||||
self.MarketOrder(front.Symbol , 1)
|
||||
else:
|
||||
self.Liquidate()
|
||||
@@ -16,7 +16,7 @@ from AlgorithmImports import *
|
||||
class BasicTemplateIndexAlgorithm(QCAlgorithm):
|
||||
def Initialize(self) -> None:
|
||||
self.SetStartDate(2021, 1, 4)
|
||||
self.SetEndDate(2021, 1, 15)
|
||||
self.SetEndDate(2021, 1, 18)
|
||||
self.SetCash(1000000)
|
||||
|
||||
# Use indicator for signal; but it cannot be traded
|
||||
|
||||
50
Algorithm.Python/BasicTemplateIndiaAlgorithm.py
Normal file
50
Algorithm.Python/BasicTemplateIndiaAlgorithm.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### Basic template framework algorithm uses framework components to define the algorithm.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="using quantconnect" />
|
||||
### <meta name="tag" content="trading and orders" />
|
||||
class BasicTemplateIndiaAlgorithm(QCAlgorithm):
|
||||
'''Basic template framework algorithm uses framework components to define the algorithm.'''
|
||||
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetAccountCurrency("INR") #Set Account Currency
|
||||
self.SetStartDate(2019, 1, 23) #Set Start Date
|
||||
self.SetEndDate(2019, 10, 31) #Set End Date
|
||||
self.SetCash(100000) #Set Strategy Cash
|
||||
# Find more symbols here: http://quantconnect.com/data
|
||||
self.AddEquity("YESBANK", Resolution.Minute, Market.India)
|
||||
self.Debug("numpy test >>> print numpy.pi: " + str(np.pi))
|
||||
|
||||
# Set Order Prperties as per the requirements for order placement
|
||||
self.DefaultOrderProperties = IndiaOrderProperties(Exchange.NSE)
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
|
||||
Arguments:
|
||||
data: Slice object keyed by symbol containing the stock data
|
||||
'''
|
||||
if not self.Portfolio.Invested:
|
||||
self.MarketOrder("YESBANK", 1)
|
||||
|
||||
def OnOrderEvent(self, orderEvent):
|
||||
if orderEvent.Status == OrderStatus.Filled:
|
||||
self.Debug("Purchased Stock: {0}".format(orderEvent.Symbol))
|
||||
71
Algorithm.Python/BasicTemplateIndiaIndexAlgorithm.py
Normal file
71
Algorithm.Python/BasicTemplateIndiaIndexAlgorithm.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### Basic Template India Index Algorithm uses framework components to define the algorithm.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="using quantconnect" />
|
||||
### <meta name="tag" content="trading and orders" />
|
||||
class BasicTemplateIndiaIndexAlgorithm(QCAlgorithm):
|
||||
'''Basic template framework algorithm uses framework components to define the algorithm.'''
|
||||
|
||||
def Initialize(self):
|
||||
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
|
||||
|
||||
self.SetAccountCurrency("INR") #Set Account Currency
|
||||
self.SetStartDate(2019, 1, 1) #Set Start Date
|
||||
self.SetEndDate(2019, 1, 5) #Set End Date
|
||||
self.SetCash(1000000) #Set Strategy Cash
|
||||
|
||||
# Use indicator for signal; but it cannot be traded
|
||||
self.Nifty = self.AddIndex("NIFTY50", Resolution.Minute, Market.India).Symbol
|
||||
# Trade Index based ETF
|
||||
self.NiftyETF = self.AddEquity("JUNIORBEES", Resolution.Minute, Market.India).Symbol
|
||||
|
||||
# Set Order Prperties as per the requirements for order placement
|
||||
self.DefaultOrderProperties = IndiaOrderProperties(Exchange.NSE)
|
||||
|
||||
# Define indicator
|
||||
self._emaSlow = self.EMA(self.Nifty, 80);
|
||||
self._emaFast = self.EMA(self.Nifty, 200);
|
||||
|
||||
self.Debug("numpy test >>> print numpy.pi: " + str(np.pi))
|
||||
|
||||
|
||||
def OnData(self, data):
|
||||
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
||||
|
||||
Arguments:
|
||||
data: Slice object keyed by symbol containing the stock data
|
||||
'''
|
||||
|
||||
if not data.Bars.ContainsKey(self.Nifty) or not data.Bars.ContainsKey(self.NiftyETF):
|
||||
return
|
||||
|
||||
if not self._emaSlow.IsReady:
|
||||
return
|
||||
|
||||
if self._emaFast > self._emaSlow:
|
||||
if not self.Portfolio.Invested:
|
||||
self.marketTicket = self.MarketOrder(self.NiftyETF, 1)
|
||||
else:
|
||||
self.Liquidate()
|
||||
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
if self.Portfolio[self.Nifty].TotalSaleVolume > 0:
|
||||
raise Exception("Index is not tradable.")
|
||||
|
||||
73
Algorithm.Python/BasicTemplateOptionsDailyAlgorithm.py
Normal file
73
Algorithm.Python/BasicTemplateOptionsDailyAlgorithm.py
Normal file
@@ -0,0 +1,73 @@
|
||||
# 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 *
|
||||
|
||||
### <summary>
|
||||
### This example demonstrates how to add options for a given underlying equity security.
|
||||
### It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
|
||||
### can inspect the option chain to pick a specific option contract to trade.
|
||||
### </summary>
|
||||
### <meta name="tag" content="using data" />
|
||||
### <meta name="tag" content="options" />
|
||||
### <meta name="tag" content="filter selection" />
|
||||
class BasicTemplateOptionsDailyAlgorithm(QCAlgorithm):
|
||||
UnderlyingTicker = "GOOG"
|
||||
|
||||
def Initialize(self):
|
||||
self.SetStartDate(2015, 12, 23)
|
||||
self.SetEndDate(2016, 1, 20)
|
||||
self.SetCash(100000)
|
||||
self.optionExpired = False
|
||||
|
||||
equity = self.AddEquity(self.UnderlyingTicker, Resolution.Daily)
|
||||
option = self.AddOption(self.UnderlyingTicker, Resolution.Daily)
|
||||
self.option_symbol = option.Symbol
|
||||
|
||||
# set our strike/expiry filter for this option chain
|
||||
option.SetFilter(lambda u: (u.Strikes(0, 1).Expiration(0, 30)))
|
||||
|
||||
# use the underlying equity as the benchmark
|
||||
self.SetBenchmark(equity.Symbol)
|
||||
|
||||
def OnData(self,slice):
|
||||
if self.Portfolio.Invested: return
|
||||
|
||||
chain = slice.OptionChains.GetValue(self.option_symbol)
|
||||
if chain is None:
|
||||
return
|
||||
|
||||
# Grab us the contract nearest expiry
|
||||
contracts = sorted(chain, key = lambda x: x.Expiry)
|
||||
|
||||
# if found, trade it
|
||||
if len(contracts) == 0 or not self.IsMarketOpen(contracts[0].Symbol): return
|
||||
symbol = contracts[0].Symbol
|
||||
self.MarketOrder(symbol, 1)
|
||||
|
||||
def OnOrderEvent(self, orderEvent):
|
||||
self.Log(str(orderEvent))
|
||||
|
||||
# Check for our expected OTM option expiry
|
||||
if orderEvent.Message == "OTM":
|
||||
|
||||
# Assert it is at midnight 1/16 (5AM UTC)
|
||||
if orderEvent.UtcTime.month != 1 and orderEvent.UtcTime.day != 16 and orderEvent.UtcTime.hour != 5:
|
||||
raise AssertionError(f"Expiry event was not at the correct time, {orderEvent.UtcTime}")
|
||||
|
||||
self.optionExpired = True
|
||||
|
||||
def OnEndOfAlgorithm(self):
|
||||
# Assert we had our option expire and fill a liquidation order
|
||||
if not self.optionExpired:
|
||||
raise AssertionError("Algorithm did not process the option expiration like expected")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user