chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* 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.Util;
|
||||
|
||||
namespace QuantConnect.Securities.Volatility
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a base model that computes the volatility of a security
|
||||
/// </summary>
|
||||
public class BaseVolatilityModel : IVolatilityModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides access to registered <see cref="SubscriptionDataConfig"/>
|
||||
/// </summary>
|
||||
protected ISubscriptionDataConfigProvider SubscriptionDataConfigProvider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the volatility of the security as a percentage
|
||||
/// </summary>
|
||||
public virtual decimal Volatility { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="ISubscriptionDataConfigProvider"/> instance to use.
|
||||
/// </summary>
|
||||
/// <param name="subscriptionDataConfigProvider">Provides access to registered <see cref="SubscriptionDataConfig"/></param>
|
||||
public virtual void SetSubscriptionDataConfigProvider(
|
||||
ISubscriptionDataConfigProvider subscriptionDataConfigProvider)
|
||||
{
|
||||
SubscriptionDataConfigProvider = subscriptionDataConfigProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates this model using the new price information in
|
||||
/// the specified security instance
|
||||
/// </summary>
|
||||
/// <param name="security">The security to calculate volatility for</param>
|
||||
/// <param name="data">The new data used to update the model</param>
|
||||
public virtual void Update(Security security, BaseData data)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns history requirements for the volatility model expressed in the form of history request
|
||||
/// </summary>
|
||||
/// <param name="security">The security of the request</param>
|
||||
/// <param name="utcTime">The date/time of the request</param>
|
||||
/// <returns>History request object list, or empty if no requirements</returns>
|
||||
public virtual IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime utcTime)
|
||||
{
|
||||
return Enumerable.Empty<HistoryRequest>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets history requests required for warming up the greeks with the provided resolution
|
||||
/// </summary>
|
||||
/// <param name="security">Security to get history for</param>
|
||||
/// <param name="utcTime">UTC time of the request (end time)</param>
|
||||
/// <param name="resolution">Resolution of the security</param>
|
||||
/// <param name="barCount">Number of bars to lookback for the start date</param>
|
||||
/// <returns>Enumerable of history requests</returns>
|
||||
/// <exception cref="InvalidOperationException">The <see cref="SubscriptionDataConfigProvider"/> has not been set</exception>
|
||||
public IEnumerable<HistoryRequest> GetHistoryRequirements(
|
||||
Security security,
|
||||
DateTime utcTime,
|
||||
Resolution? resolution,
|
||||
int barCount)
|
||||
{
|
||||
if (SubscriptionDataConfigProvider == null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"BaseVolatilityModel.GetHistoryRequirements(): " +
|
||||
"SubscriptionDataConfigProvider was not set."
|
||||
);
|
||||
}
|
||||
|
||||
var configurations = SubscriptionDataConfigProvider
|
||||
.GetSubscriptionDataConfigs(security.Symbol)
|
||||
.OrderBy(c => c.TickType)
|
||||
.ToList();
|
||||
var configuration = configurations.First();
|
||||
|
||||
var bar = configuration.Type.GetBaseDataInstance();
|
||||
bar.Symbol = security.Symbol;
|
||||
|
||||
var historyResolution = resolution ?? bar.SupportedResolutions().Max();
|
||||
|
||||
var periodSpan = historyResolution.ToTimeSpan();
|
||||
|
||||
// hour resolution does no have extended market hours data
|
||||
var extendedMarketHours = periodSpan != Time.OneHour && configurations.IsExtendedMarketHours();
|
||||
var localStartTime = Time.GetStartTimeForTradeBars(
|
||||
security.Exchange.Hours,
|
||||
utcTime.ConvertFromUtc(security.Exchange.TimeZone),
|
||||
periodSpan,
|
||||
barCount,
|
||||
extendedMarketHours,
|
||||
configuration.DataTimeZone, dailyPreciseEndTime: false);
|
||||
var utcStartTime = localStartTime.ConvertToUtc(security.Exchange.TimeZone);
|
||||
|
||||
return new[]
|
||||
{
|
||||
new HistoryRequest(utcStartTime,
|
||||
utcTime,
|
||||
configuration.Type,
|
||||
configuration.Symbol,
|
||||
historyResolution,
|
||||
security.Exchange.Hours,
|
||||
configuration.DataTimeZone,
|
||||
historyResolution,
|
||||
extendedMarketHours,
|
||||
configurations.IsCustomData(),
|
||||
configuration.DataNormalizationMode,
|
||||
LeanData.GetCommonTickTypeForCommonDataTypes(configuration.Type, security.Type))
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
using QuantConnect.Data;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Securities.Volatility;
|
||||
|
||||
namespace QuantConnect.Securities
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a model that computes the volatility of a security
|
||||
/// </summary>
|
||||
/// <remarks>Please use<see cref="BaseVolatilityModel"/> as the base class for
|
||||
/// any implementations of<see cref="IVolatilityModel"/></remarks>
|
||||
public interface IVolatilityModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the volatility of the security as a percentage
|
||||
/// </summary>
|
||||
decimal Volatility { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Updates this model using the new price information in
|
||||
/// the specified security instance
|
||||
/// </summary>
|
||||
/// <param name="security">The security to calculate volatility for</param>
|
||||
/// <param name="data">The new data used to update the model</param>
|
||||
void Update(Security security, BaseData data);
|
||||
|
||||
/// <summary>
|
||||
/// Returns history requirements for the volatility model expressed in the form of history request
|
||||
/// </summary>
|
||||
/// <param name="security">The security of the request</param>
|
||||
/// <param name="utcTime">The date/time of the request</param>
|
||||
/// <returns>History request object list, or empty if no requirements</returns>
|
||||
IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime utcTime);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to a null implementation for <see cref="IVolatilityModel"/>
|
||||
/// </summary>
|
||||
public static class VolatilityModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets an instance of <see cref="IVolatilityModel"/> that will always
|
||||
/// return 0 for its volatility and does nothing during Update.
|
||||
/// </summary>
|
||||
public static readonly IVolatilityModel Null = new NullVolatilityModel();
|
||||
|
||||
private sealed class NullVolatilityModel : IVolatilityModel
|
||||
{
|
||||
public decimal Volatility { get; private set; }
|
||||
|
||||
public void Update(Security security, BaseData data) { }
|
||||
|
||||
public IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime utcTime) { return Enumerable.Empty<HistoryRequest>(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 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.Indicators;
|
||||
using QuantConnect.Securities.Volatility;
|
||||
|
||||
namespace QuantConnect.Securities
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IVolatilityModel"/> that uses an indicator
|
||||
/// to compute its value
|
||||
/// </summary>
|
||||
public class IndicatorVolatilityModel : BaseVolatilityModel
|
||||
{
|
||||
private readonly IIndicator _indicator;
|
||||
private readonly Action<Security, BaseData, IIndicator> _indicatorUpdate;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the volatility of the security as a percentage
|
||||
/// </summary>
|
||||
public override decimal Volatility
|
||||
{
|
||||
get { return _indicator.Current.Value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="IVolatilityModel"/> using
|
||||
/// the specified <paramref name="indicator"/>. The <paramref name="indicator"/>
|
||||
/// is assumed to but updated externally from this model, such as being registered
|
||||
/// into the consolidator system.
|
||||
/// </summary>
|
||||
/// <param name="indicator">The auto-updating indicator</param>
|
||||
public IndicatorVolatilityModel(IIndicator indicator)
|
||||
{
|
||||
_indicator = indicator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="IVolatilityModel"/> using
|
||||
/// the specified <paramref name="indicator"/>. The <paramref name="indicator"/>
|
||||
/// is assumed to but updated externally from this model, such as being registered
|
||||
/// into the consolidator system.
|
||||
/// </summary>
|
||||
/// <param name="indicator">The auto-updating indicator</param>
|
||||
/// <param name="indicatorUpdate">Function delegate used to update the indicator on each call to <see cref="Update"/></param>
|
||||
public IndicatorVolatilityModel(IIndicator indicator, Action<Security, BaseData, IIndicator> indicatorUpdate)
|
||||
{
|
||||
_indicator = indicator;
|
||||
_indicatorUpdate = indicatorUpdate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates this model using the new price information in
|
||||
/// the specified security instance
|
||||
/// </summary>
|
||||
/// <param name="security">The security to calculate volatility for</param>
|
||||
/// <param name="data">The new piece of data for the security</param>
|
||||
public override void Update(Security security, BaseData data)
|
||||
{
|
||||
if (_indicatorUpdate != null)
|
||||
{
|
||||
_indicatorUpdate(security, data, _indicator);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
|
||||
/*
|
||||
* 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 MathNet.Numerics.Statistics;
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using QuantConnect.Securities.Volatility;
|
||||
using QuantConnect.Util;
|
||||
|
||||
namespace QuantConnect.Securities
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IVolatilityModel"/> that computes the
|
||||
/// relative standard deviation as the volatility of the security
|
||||
/// </summary>
|
||||
public class RelativeStandardDeviationVolatilityModel : BaseVolatilityModel
|
||||
{
|
||||
private bool _needsUpdate;
|
||||
private decimal _volatility;
|
||||
private DateTime _lastUpdate;
|
||||
private readonly TimeSpan _periodSpan;
|
||||
private readonly object _sync = new object();
|
||||
private readonly RollingWindow<double> _window;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the volatility of the security as a percentage
|
||||
/// </summary>
|
||||
public override decimal Volatility
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_window.Count < 2)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
if (_needsUpdate)
|
||||
{
|
||||
_needsUpdate = false;
|
||||
var mean = Math.Abs(_window.Mean().SafeDecimalCast());
|
||||
if (mean != 0m)
|
||||
{
|
||||
// volatility here is supposed to be a percentage
|
||||
var std = _window.StandardDeviation().SafeDecimalCast();
|
||||
_volatility = std / mean;
|
||||
}
|
||||
}
|
||||
}
|
||||
return _volatility;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RelativeStandardDeviationVolatilityModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="periodSpan">The time span representing one 'period' length</param>
|
||||
/// <param name="periods">The number of 'period' lengths to wait until updating the value</param>
|
||||
public RelativeStandardDeviationVolatilityModel(
|
||||
TimeSpan periodSpan,
|
||||
int periods)
|
||||
{
|
||||
if (periods < 2) throw new ArgumentOutOfRangeException(nameof(periods), "'periods' must be greater than or equal to 2.");
|
||||
_periodSpan = periodSpan;
|
||||
_window = new RollingWindow<double>(periods);
|
||||
_lastUpdate = GetLastUpdateInitialValue(periodSpan, periods);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates this model using the new price information in
|
||||
/// the specified security instance
|
||||
/// </summary>
|
||||
/// <param name="security">The security to calculate volatility for</param>
|
||||
/// <param name="data"></param>
|
||||
public override void Update(Security security, BaseData data)
|
||||
{
|
||||
var timeSinceLastUpdate = data.EndTime - _lastUpdate;
|
||||
if (timeSinceLastUpdate >= _periodSpan && data.Price > 0)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_needsUpdate = true;
|
||||
_window.Add((double)data.Price);
|
||||
}
|
||||
_lastUpdate = data.EndTime;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns history requirements for the volatility model expressed in the form of history request
|
||||
/// </summary>
|
||||
/// <param name="security">The security of the request</param>
|
||||
/// <param name="utcTime">The date/time of the request</param>
|
||||
/// <returns>History request object list, or empty if no requirements</returns>
|
||||
public override IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime utcTime)
|
||||
{
|
||||
if (SubscriptionDataConfigProvider == null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"RelativeStandardDeviationVolatilityModel.GetHistoryRequirements(): " +
|
||||
"SubscriptionDataConfigProvider was not set."
|
||||
);
|
||||
}
|
||||
|
||||
// Let's reset the model since it will get warmed up again using these history requirements
|
||||
Reset();
|
||||
|
||||
var configurations = SubscriptionDataConfigProvider
|
||||
.GetSubscriptionDataConfigs(security.Symbol)
|
||||
.OrderBy(c => c.TickType)
|
||||
.ToList();
|
||||
|
||||
return GetHistoryRequirements(
|
||||
security,
|
||||
utcTime,
|
||||
configurations.GetHighestResolution(),
|
||||
_window.Size + 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the model to its initial state
|
||||
/// </summary>
|
||||
private void Reset()
|
||||
{
|
||||
_needsUpdate = false;
|
||||
_volatility = 0m;
|
||||
_lastUpdate = GetLastUpdateInitialValue(_periodSpan, _window.Size);
|
||||
_window.Reset();
|
||||
}
|
||||
|
||||
private static DateTime GetLastUpdateInitialValue(TimeSpan periodSpan, int periods)
|
||||
{
|
||||
return DateTime.MinValue + TimeSpan.FromMilliseconds(periodSpan.TotalMilliseconds * periods);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* 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 MathNet.Numerics.Statistics;
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Indicators;
|
||||
using QuantConnect.Securities.Volatility;
|
||||
|
||||
namespace QuantConnect.Securities
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides an implementation of <see cref="IVolatilityModel"/> that computes the
|
||||
/// annualized sample standard deviation of daily returns as the volatility of the security
|
||||
/// </summary>
|
||||
public class StandardDeviationOfReturnsVolatilityModel : BaseVolatilityModel
|
||||
{
|
||||
private bool _needsUpdate;
|
||||
private decimal _volatility;
|
||||
private DateTime _lastUpdate = DateTime.MinValue;
|
||||
private decimal _lastPrice;
|
||||
private Resolution? _resolution;
|
||||
private TimeSpan _periodSpan;
|
||||
private readonly object _sync = new object();
|
||||
private RollingWindow<double> _window;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the volatility of the security as a percentage
|
||||
/// </summary>
|
||||
public override decimal Volatility
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_window.Count < 2)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
if (_needsUpdate)
|
||||
{
|
||||
_needsUpdate = false;
|
||||
var std = _window.StandardDeviation().SafeDecimalCast();
|
||||
_volatility = std * (decimal)Math.Sqrt(252.0);
|
||||
}
|
||||
}
|
||||
|
||||
return _volatility;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StandardDeviationOfReturnsVolatilityModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="periods">The max number of samples in the rolling window to be considered for calculating the standard deviation of returns</param>
|
||||
/// <param name="resolution">
|
||||
/// Resolution of the price data inserted into the rolling window series to calculate standard deviation.
|
||||
/// Will be used as the default value for update frequency if a value is not provided for <paramref name="updateFrequency"/>.
|
||||
/// This only has a material effect in live mode. For backtesting, this value does not cause any behavioral changes.
|
||||
/// </param>
|
||||
/// <param name="updateFrequency">Frequency at which we insert new values into the rolling window for the standard deviation calculation</param>
|
||||
/// <remarks>
|
||||
/// The volatility model will be updated with the most granular/highest resolution data that was added to your algorithm.
|
||||
/// That means that if I added <see cref="Resolution.Tick"/> data for my Futures strategy, that this model will be
|
||||
/// updated using <see cref="Resolution.Tick"/> data as the algorithm progresses in time.
|
||||
///
|
||||
/// Keep this in mind when setting the period and update frequency. The Resolution parameter is only used for live mode, or for
|
||||
/// the default value of the <paramref name="updateFrequency"/> if no value is provided.
|
||||
/// </remarks>
|
||||
public StandardDeviationOfReturnsVolatilityModel(
|
||||
int periods,
|
||||
Resolution? resolution = null,
|
||||
TimeSpan? updateFrequency = null
|
||||
)
|
||||
{
|
||||
if (periods < 2)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(periods), "'periods' must be greater than or equal to 2.");
|
||||
}
|
||||
|
||||
_window = new RollingWindow<double>(periods);
|
||||
_resolution = resolution;
|
||||
_periodSpan = updateFrequency ?? resolution?.ToTimeSpan() ?? TimeSpan.FromDays(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StandardDeviationOfReturnsVolatilityModel"/> class
|
||||
/// </summary>
|
||||
/// <param name="resolution">
|
||||
/// Resolution of the price data inserted into the rolling window series to calculate standard deviation.
|
||||
/// Will be used as the default value for update frequency if a value is not provided for <paramref name="updateFrequency"/>.
|
||||
/// This only has a material effect in live mode. For backtesting, this value does not cause any behavioral changes.
|
||||
/// </param>
|
||||
/// <param name="updateFrequency">Frequency at which we insert new values into the rolling window for the standard deviation calculation</param>
|
||||
/// <remarks>
|
||||
/// The volatility model will be updated with the most granular/highest resolution data that was added to your algorithm.
|
||||
/// That means that if I added <see cref="Resolution.Tick"/> data for my Futures strategy, that this model will be
|
||||
/// updated using <see cref="Resolution.Tick"/> data as the algorithm progresses in time.
|
||||
///
|
||||
/// Keep this in mind when setting the period and update frequency. The Resolution parameter is only used for live mode, or for
|
||||
/// the default value of the <paramref name="updateFrequency"/> if no value is provided.
|
||||
/// </remarks>
|
||||
public StandardDeviationOfReturnsVolatilityModel(
|
||||
Resolution resolution,
|
||||
TimeSpan? updateFrequency = null
|
||||
) : this(PeriodsInResolution(resolution), resolution, updateFrequency)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates this model using the new price information in
|
||||
/// the specified security instance
|
||||
/// </summary>
|
||||
/// <param name="security">The security to calculate volatility for</param>
|
||||
/// <param name="data">Data to update the volatility model with</param>
|
||||
public override void Update(Security security, BaseData data)
|
||||
{
|
||||
var timeSinceLastUpdate = data.EndTime - _lastUpdate;
|
||||
if (timeSinceLastUpdate >= _periodSpan && data.Price > 0)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_lastPrice > 0.0m)
|
||||
{
|
||||
_needsUpdate = true;
|
||||
_window.Add((double)(data.Price / _lastPrice) - 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
_lastUpdate = data.EndTime;
|
||||
_lastPrice = data.Price;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns history requirements for the volatility model expressed in the form of history request
|
||||
/// </summary>
|
||||
/// <param name="security">The security of the request</param>
|
||||
/// <param name="utcTime">The date of the request</param>
|
||||
/// <returns>History request object list, or empty if no requirements</returns>
|
||||
public override IEnumerable<HistoryRequest> GetHistoryRequirements(Security security, DateTime utcTime)
|
||||
{
|
||||
// Let's reset the model since it will get warmed up again using these history requirements
|
||||
Reset();
|
||||
|
||||
return GetHistoryRequirements(
|
||||
security,
|
||||
utcTime,
|
||||
_resolution,
|
||||
_window.Size + 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the model to its initial state
|
||||
/// </summary>
|
||||
private void Reset()
|
||||
{
|
||||
_needsUpdate = false;
|
||||
_volatility = 0m;
|
||||
_lastUpdate = DateTime.MinValue;
|
||||
_lastPrice = 0m;
|
||||
_window.Reset();
|
||||
}
|
||||
|
||||
private static int PeriodsInResolution(Resolution resolution)
|
||||
{
|
||||
int periods;
|
||||
switch (resolution)
|
||||
{
|
||||
case Resolution.Tick:
|
||||
case Resolution.Second:
|
||||
periods = 600;
|
||||
break;
|
||||
case Resolution.Minute:
|
||||
periods = 60 * 24;
|
||||
break;
|
||||
case Resolution.Hour:
|
||||
periods = 24 * 30;
|
||||
break;
|
||||
default:
|
||||
periods = 30;
|
||||
break;
|
||||
}
|
||||
|
||||
return periods;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
* 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 NodaTime;
|
||||
|
||||
using QuantConnect.Data;
|
||||
using QuantConnect.Interfaces;
|
||||
|
||||
namespace QuantConnect.Securities.Volatility
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides extension methods to volatility models
|
||||
/// </summary>
|
||||
public static class VolatilityModelExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Warms up the security's volatility model.
|
||||
/// This can happen either on initialization or after a split or dividend is processed.
|
||||
/// </summary>
|
||||
/// <param name="volatilityModel">The volatility model to be warmed up</param>
|
||||
/// <param name="historyProvider">The history provider to use to get historical data</param>
|
||||
/// <param name="subscriptionManager">The subscription manager to use</param>
|
||||
/// <param name="security">The security which volatility model is being warmed up</param>
|
||||
/// <param name="utcTime">The current UTC time</param>
|
||||
/// <param name="timeZone">The algorithm time zone</param>
|
||||
/// <param name="liveMode">Whether the algorithm is in live mode</param>
|
||||
/// <param name="dataNormalizationMode">The security subscribed data normalization mode</param>
|
||||
public static void WarmUp(
|
||||
this IVolatilityModel volatilityModel,
|
||||
IHistoryProvider historyProvider,
|
||||
SubscriptionManager subscriptionManager,
|
||||
Security security,
|
||||
DateTime utcTime,
|
||||
DateTimeZone timeZone,
|
||||
bool liveMode,
|
||||
DataNormalizationMode? dataNormalizationMode = null)
|
||||
{
|
||||
volatilityModel.WarmUp(
|
||||
historyProvider,
|
||||
subscriptionManager,
|
||||
security,
|
||||
timeZone,
|
||||
liveMode,
|
||||
dataNormalizationMode,
|
||||
() => volatilityModel.GetHistoryRequirements(security, utcTime));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Warms up the security's volatility model.
|
||||
/// This can happen either on initialization or after a split or dividend is processed.
|
||||
/// </summary>
|
||||
/// <param name="volatilityModel">The volatility model to be warmed up</param>
|
||||
/// <param name="historyProvider">The history provider to use to get historical data</param>
|
||||
/// <param name="subscriptionManager">The subscription manager to use</param>
|
||||
/// <param name="security">The security which volatility model is being warmed up</param>
|
||||
/// <param name="utcTime">The current UTC time</param>
|
||||
/// <param name="timeZone">The algorithm time zone</param>
|
||||
/// <param name="resolution">The data resolution required for the indicator</param>
|
||||
/// <param name="barCount">The bar count required to fully warm the indicator up</param>
|
||||
/// <param name="liveMode">Whether the algorithm is in live mode</param>
|
||||
/// <param name="dataNormalizationMode">The security subscribed data normalization mode</param>
|
||||
public static void WarmUp(
|
||||
this IndicatorVolatilityModel volatilityModel,
|
||||
IHistoryProvider historyProvider,
|
||||
SubscriptionManager subscriptionManager,
|
||||
Security security,
|
||||
DateTime utcTime,
|
||||
DateTimeZone timeZone,
|
||||
Resolution? resolution,
|
||||
int barCount,
|
||||
bool liveMode,
|
||||
DataNormalizationMode? dataNormalizationMode = null)
|
||||
{
|
||||
volatilityModel.WarmUp(
|
||||
historyProvider,
|
||||
subscriptionManager,
|
||||
security,
|
||||
timeZone,
|
||||
liveMode,
|
||||
dataNormalizationMode,
|
||||
() => volatilityModel.GetHistoryRequirements(security, utcTime, resolution, barCount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Warms up the security's volatility model.
|
||||
/// This can happen either on initialization or after a split or dividend is processed.
|
||||
/// </summary>
|
||||
/// <param name="volatilityModel">The volatility model to be warmed up</param>
|
||||
/// <param name="algorithm">The algorithm running</param>
|
||||
/// <param name="security">The security which volatility model is being warmed up</param>
|
||||
/// <param name="resolution">The data resolution required for the indicator</param>
|
||||
/// <param name="barCount">The bar count required to fully warm the indicator up</param>
|
||||
/// <param name="dataNormalizationMode">The security subscribed data normalization mode</param>
|
||||
public static void WarmUp(
|
||||
this IndicatorVolatilityModel volatilityModel,
|
||||
IAlgorithm algorithm,
|
||||
Security security,
|
||||
Resolution? resolution,
|
||||
int barCount,
|
||||
DataNormalizationMode? dataNormalizationMode = null)
|
||||
{
|
||||
volatilityModel.WarmUp(
|
||||
algorithm.HistoryProvider,
|
||||
algorithm.SubscriptionManager,
|
||||
security,
|
||||
algorithm.UtcTime,
|
||||
algorithm.TimeZone,
|
||||
resolution,
|
||||
barCount,
|
||||
algorithm.LiveMode,
|
||||
dataNormalizationMode);
|
||||
}
|
||||
|
||||
private static void WarmUp(
|
||||
this IVolatilityModel volatilityModel,
|
||||
IHistoryProvider historyProvider,
|
||||
SubscriptionManager subscriptionManager,
|
||||
Security security,
|
||||
DateTimeZone timeZone,
|
||||
bool liveMode,
|
||||
DataNormalizationMode? dataNormalizationMode,
|
||||
Func<IEnumerable<HistoryRequest>> getHistoryRequirementsFunc)
|
||||
{
|
||||
if (historyProvider == null || security == null || volatilityModel == VolatilityModel.Null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// start: this is a work around to maintain retro compatibility
|
||||
// did not want to add IVolatilityModel.SetSubscriptionDataConfigProvider
|
||||
// to prevent breaking existing user models.
|
||||
var baseTypeModel = volatilityModel as BaseVolatilityModel;
|
||||
baseTypeModel?.SetSubscriptionDataConfigProvider(subscriptionManager.SubscriptionDataConfigService);
|
||||
// end
|
||||
|
||||
// Warm up
|
||||
var historyRequests = getHistoryRequirementsFunc().ToList();
|
||||
if (liveMode || (dataNormalizationMode.HasValue && dataNormalizationMode == DataNormalizationMode.Raw))
|
||||
{
|
||||
// If we're in live mode or raw mode, we need to warm up the volatility model with scaled raw data
|
||||
// to avoid jumps in volatility values due to price discontinuities on splits and dividends
|
||||
foreach (var request in historyRequests)
|
||||
{
|
||||
request.DataNormalizationMode = DataNormalizationMode.ScaledRaw;
|
||||
}
|
||||
}
|
||||
|
||||
var history = historyProvider.GetHistory(historyRequests, timeZone);
|
||||
foreach (var slice in history)
|
||||
{
|
||||
foreach (var request in historyRequests)
|
||||
{
|
||||
if (slice.TryGet(request.DataType, security.Symbol, out var data))
|
||||
{
|
||||
volatilityModel.Update(security, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user