public void FlatDirectionNotAccountedToAllocation(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // Modifying fee model for a constant one so numbers are simplified foreach (var security in _algorithm.Securities) { security.Value.FeeModel = new ConstantFeeModel(1); } // Equity, minus $1 for fees var amount = (_algorithm.Portfolio.TotalPortfolioValue - 1 * (_algorithm.Securities.Count - 1)) * (decimal)Weight; var expectedTargets = _algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since its insight will have flat direction var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount * (1 - _algorithm.Settings.FreePortfolioValuePercentage) / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); var insights = _algorithm.Securities.Keys.Select(x => { // SPY insight direction is flat var actualDirection = x.Value == "SPY" ? InsightDirection.Flat : direction; return(GetInsight(x, actualDirection, _algorithm.UtcTime)); }); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); AssertTargets(expectedTargets, actualTargets); }
public void FlatDirectionNotAccountedToAllocation(Language language, InsightDirection direction) { SetPortfolioConstruction(language); // Equity will be divided by all securities minus 1, since its insight will have flat direction var amount = _algorithm.Portfolio.TotalPortfolioValue / (_algorithm.Securities.Count - 1); var expectedTargets = _algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since its insight will have flat direction var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); var insights = _algorithm.Securities.Keys.Select(x => { // SPY insight direction is flat var actualDirection = x.Value == "SPY" ? InsightDirection.Flat : direction; return(GetInsight(x, actualDirection, _algorithm.UtcTime)); }); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); Assert.AreEqual(expectedTargets.Count(), actualTargets.Count()); foreach (var expected in expectedTargets) { var actual = actualTargets.FirstOrDefault(x => x.Symbol == expected.Symbol); Assert.IsNotNull(actual); Assert.AreEqual(expected.Quantity, actual.Quantity); } }
/// <summary> /// Private constructor used to keep track of how a user defined the insight period. /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="periodSpec">A specification defining how the insight's period was defined, via time span, via resolution/barcount, via close time</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percentage change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">An identifier defining the model that generated this insight</param> /// <param name="weight">The portfolio weight of this insight</param> private Insight(Symbol symbol, IPeriodSpecification periodSpec, InsightType type, InsightDirection direction, double?magnitude, double?confidence, string sourceModel = null, double?weight = null) { Id = Guid.NewGuid(); Score = new InsightScore(); SourceModel = sourceModel; Symbol = symbol; Type = type; Direction = direction; // Optional Magnitude = magnitude; Confidence = confidence; Weight = weight; _periodSpecification = periodSpec; // keep existing behavior of Insight.Price such that we set the period immediately var period = (periodSpec as TimeSpanPeriodSpecification)?.Period; if (period != null) { Period = period.Value; } }
/// <summary> /// Creates a new insight for predicting the percent change in price over the specified period /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="closeTimeLocal">The insight's closing time in the security's exchange time zone</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percent change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">The model generating this insight</param> /// <param name="weight">The portfolio weight of this insight</param> /// <returns>A new insight object for the specified parameters</returns> public static Insight Price(Symbol symbol, DateTime closeTimeLocal, InsightDirection direction, double?magnitude = null, double?confidence = null, string sourceModel = null, double?weight = null) { var spec = closeTimeLocal == Time.EndOfTime ? (IPeriodSpecification) new EndOfTimeCloseTimePeriodSpecification() : new CloseTimePeriodSpecification(closeTimeLocal); return(new Insight(symbol, spec, InsightType.Price, direction, magnitude, confidence, sourceModel, weight)); }
public void InsightExpirationUndoesAccumulation(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // First emit long term insight SetUtcTime(_algorithm.Time); var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromMinutes(10)), GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromMinutes(10)) }; var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); var expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * 2 * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // both insights should expire SetUtcTime(_algorithm.Time.AddMinutes(11)); targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new Insight[0]).ToList(); expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, 0) }; AssertTargets(expectedTargets, targets); // we expect no target targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new Insight[0]).ToList(); AssertTargets(new List <IPortfolioTarget>(), targets); }
public void FlatUndoesAccumulation(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // First emit long term insight var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime) }; var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); var expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // One minute later, emits insight to add to portfolio SetUtcTime(_algorithm.UtcTime.AddMinutes(1)); insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime) }; targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * 2 * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // One minute later, emits flat insight SetUtcTime(_algorithm.UtcTime.AddMinutes(1)); insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Flat, _algorithm.UtcTime) }; targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); }
public void AutomaticallyRemoveInvested(Language language, InsightDirection direction) { SetPortfolioConstruction(language); var spyHolding = _algorithm.Portfolio[Symbols.SPY]; spyHolding.SetHoldings(spyHolding.Price, 100); _algorithm.Portfolio.SetCash(_startingCash - spyHolding.HoldingsValue); // Equity will be divided by all securities minus 1, since SPY is already invested and we want to remove it var amount = _algorithm.Portfolio.TotalPortfolioValue / (_algorithm.Securities.Count - 1); var expectedTargets = _algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since it will be removed var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); // Do no include SPY in the insights var insights = _algorithm.Securities.Keys .Where(x => x.Value != "SPY") .Select(x => GetInsight(x, direction, _algorithm.UtcTime)); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); Assert.AreEqual(expectedTargets.Count(), actualTargets.Count()); foreach (var expected in expectedTargets) { var actual = actualTargets.FirstOrDefault(x => x.Symbol == expected.Symbol); Assert.IsNotNull(actual); Assert.AreEqual(expected.Quantity, actual.Quantity); } }
/// <summary> /// Initializes a new instance of the <see cref="ConstantAlphaModel"/> class /// </summary> /// <param name="type">The type of insight</param> /// <param name="direction">The direction of the insight</param> /// <param name="period">The period over which the insight with come to fruition</param> /// <param name="magnitude">The predicted change in magnitude as a +- percentage</param> /// <param name="confidence">The confidence in the insight</param> public ConstantAlphaModel(InsightType type, InsightDirection direction, TimeSpan period, double?magnitude, double?confidence) { _type = type; _direction = direction; _period = period; // Optional _magnitude = magnitude; _confidence = confidence; _securities = new HashSet <Security>(); _insightsTimeBySymbol = new Dictionary <Symbol, DateTime>(); Name = $"{nameof(ConstantAlphaModel)}({type},{direction},{period}"; if (magnitude.HasValue) { Name += $",{magnitude.Value}"; } if (confidence.HasValue) { Name += $",{confidence.Value}"; } Name += ")"; }
/// <summary> /// When a new insight comes in, close down anything that might be open. /// </summary> public override List <IPortfolioTarget> PossiblyCloseCurrentTargets(QCAlgorithmFramework algorithm, Symbol symbol, IEnumerable <OptionHolding> optionHoldings, Insight insight) { //check to see which direction our existing holdings are, // and filter out any insights that would duplicate that leg. InsightDirection direction = insight.Direction; foreach (var holding in optionHoldings) { if (holding.Symbol.ID.OptionRight == OptionRight.Put) { if (direction == InsightDirection.Up) { //abort -- don't duplicate leg!! return(null); } direction = InsightDirection.Down; } if (holding.Symbol.ID.OptionRight == OptionRight.Call) { if (direction == InsightDirection.Down) { //abort -- don't duplicate leg!! return(null); } direction = InsightDirection.Up; } } return(FindPotentialOptions(algorithm, symbol, direction)); }
public void LongTermInsightAccumulatesByNew(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // First emit long term insight var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime) }; var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); var expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // One minute later, emits short term insight to add long SetUtcTime(_algorithm.UtcTime.AddMinutes(1)); insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, Time.OneMinute) }; targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights).ToList(); expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * 2 * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // One minute later, emit empty insights array, should return to nomral after the long expires SetUtcTime(_algorithm.UtcTime.AddMinutes(1.1)); expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent) }; // Create target from an empty insights array var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new Insight[0]); AssertTargets(expectedTargets, actualTargets); }
public void AutomaticallyRemoveInvestedWithNewInsights(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // Let's create a position for SPY var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime) }; foreach (var target in _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights)) { var holding = _algorithm.Portfolio[target.Symbol]; holding.SetHoldings(holding.Price, target.Quantity); _algorithm.Portfolio.SetCash(_startingCash - holding.HoldingsValue); } SetUtcTime(_algorithm.UtcTime.AddDays(2)); var amount = _algorithm.Portfolio.TotalPortfolioValue * (decimal)Weight; var expectedTargets = _algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since it will be removed var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount * (1 - _algorithm.Settings.FreePortfolioValuePercentage) / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); // Do no include SPY in the insights insights = _algorithm.Securities.Keys.Where(x => x.Value != "SPY") .Select(x => GetInsight(x, direction, _algorithm.UtcTime)).ToArray(); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights); AssertTargets(expectedTargets, actualTargets); }
public override Insight GetInsight(Symbol symbol, InsightDirection direction, DateTime generatedTimeUtc, TimeSpan?period = null, double?weight = _weight) { period = period ?? TimeSpan.FromDays(1); var insight = Insight.Price(symbol, period.Value, direction, weight: Math.Max(_weight, Algorithm.Securities.Count)); insight.GeneratedTimeUtc = generatedTimeUtc; insight.CloseTimeUtc = generatedTimeUtc.Add(period.Value); return(insight); }
private Insight GetInsight(Symbol symbol, InsightDirection direction, DateTime generatedTimeUtc, TimeSpan?period = null, double?weight = Weight) { period = period ?? TimeSpan.FromDays(1); var insight = Insight.Price(symbol, period.Value, direction, weight: weight); insight.GeneratedTimeUtc = generatedTimeUtc; insight.CloseTimeUtc = generatedTimeUtc.Add(period.Value); return(insight); }
private Insight GetInsight(Symbol symbol, InsightDirection direction, DateTime generatedTimeUtc) { var period = TimeSpan.FromDays(1); var insight = Insight.Price(symbol, period, direction); insight.GeneratedTimeUtc = generatedTimeUtc; insight.CloseTimeUtc = generatedTimeUtc.Add(period); return(insight); }
/// <summary> /// Creates a new insight for predicting the percent change in price over the specified period /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="period">The period over which the prediction will come true</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percent change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">The model generating this insight</param> /// <returns>A new insight object for the specified parameters</returns> public static Insight Price(Symbol symbol, TimeSpan period, InsightDirection direction, double? magnitude = null, double? confidence = null, string sourceModel = null) { if (period < Time.OneSecond) { throw new ArgumentOutOfRangeException(nameof(period), "Insight period must be greater than or equal to 1 second."); } var spec = period == Time.EndOfTimeTimeSpan ? (IPeriodSpecification) new EndOfTimeCloseTimePeriodSpecification() : new TimeSpanPeriodSpecification(period); return new Insight(symbol, spec, InsightType.Price, direction, magnitude, confidence, sourceModel); }
/// <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 (_step == 0) { _expectedConfidence = 1; _expectedInsightDirection = InsightDirection.Up; _step++; SetHoldings(_spy, 0.75); } else if (_step == 1) { _step++; _expectedConfidence = 1; _expectedInsightDirection = InsightDirection.Up; SetHoldings(_spy, 0.80); } else if (_step == 2) { _step++; _expectedConfidence = 0.5; _expectedInsightDirection = InsightDirection.Up; SetHoldings(_spy, 0.40); } else if (_step == 3) { _step++; _expectedConfidence = 0.25; _expectedInsightDirection = InsightDirection.Up; SetHoldings(_spy, 0.20); } else if (_step == 4) { _step++; _expectedConfidence = 1; _expectedInsightDirection = InsightDirection.Flat; SetHoldings(_spy, 0); } else if (_step == 5) { _step++; _expectedConfidence = 1; _expectedInsightDirection = InsightDirection.Down; SetHoldings(_spy, -0.5); } else if (_step == 6) { _step++; _expectedConfidence = 1; _expectedInsightDirection = InsightDirection.Up; SetHoldings(_spy, 1); } }
/// <summary> /// Initializes a new instance of the <see cref="ConstantAlphaModel"/> class /// </summary> /// <param name="type">The type of insight</param> /// <param name="direction">The direction of the insight</param> /// <param name="period">The period over which the insight with come to fruition</param> /// <param name="magnitude">The predicted change in magnitude as a +- percentage</param> /// <param name="confidence">The confidence in the insight</param> public ConstantAlphaModel(InsightType type, InsightDirection direction, TimeSpan period, double?magnitude, double?confidence) { _type = type; _direction = direction; _period = period; // Optional _magnitude = magnitude; _confidence = confidence; _securities = new HashSet <Security>(); _insightsTimeBySymbol = new Dictionary <Symbol, DateTime>(); }
public void RespectsRebalancingPeriod(Language language, InsightDirection direction) { PortfolioConstructionModel model = new AccumulativeInsightPortfolioConstructionModel(Resolution.Daily); if (language == Language.Python) { using (Py.GIL()) { var name = nameof(AccumulativeInsightPortfolioConstructionModel); dynamic instance = Py.Import(name).GetAttr(name); model = new PortfolioConstructionModelPythonWrapper(instance(Resolution.Daily)); } } model.RebalanceOnSecurityChanges = false; model.RebalanceOnInsightChanges = false; SetUtcTime(new DateTime(2018, 7, 31)); // First emit long term insight var insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromDays(10)) }; AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights).ToList()); // One minute later, emits insight to add to portfolio SetUtcTime(_algorithm.Time.AddMinutes(1)); insights = new[] { GetInsight(Symbols.SPY, direction, _algorithm.UtcTime, TimeSpan.FromMinutes(10)) }; AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights)); // the second insight should expire SetUtcTime(_algorithm.Time.AddMinutes(1)); AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, insights)); // the rebalancing period is due and the first insight is still valid SetUtcTime(_algorithm.Time.AddDays(1)); var targets = model.CreateTargets(_algorithm, new Insight[0]); var expectedTargets = new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, (int)direction * 1m * (decimal)DefaultPercent) }; AssertTargets(expectedTargets, targets); // the rebalancing period is due and no insight is valid SetUtcTime(_algorithm.Time.AddDays(10)); AssertTargets( new List <IPortfolioTarget> { PortfolioTarget.Percent(_algorithm, Symbols.SPY, 0) }, model.CreateTargets(_algorithm, new Insight[0])); AssertTargets(new List <IPortfolioTarget>(), model.CreateTargets(_algorithm, new Insight[0])); }
public void InsightsReturnsTargetsConsistentWithDirection(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); var amount = _algorithm.Portfolio.TotalPortfolioValue * (decimal)DefaultPercent; var expectedTargets = _algorithm.Securities .Select(x => new PortfolioTarget(x.Key, (int)direction * Math.Floor(amount / x.Value.Price))); var insights = _algorithm.Securities.Keys.Select(x => GetInsight(x, direction, _algorithm.UtcTime)); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); AssertTargets(expectedTargets, actualTargets); }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> /// <param name="period">The period over which the prediction will come true</param> /// <param name="magnitude">The predicted magnitude as a percentage change</param> /// <param name="confidence">The confidence in this insight</param> public Insight(Symbol symbol, InsightType type, InsightDirection direction, TimeSpan period, double?magnitude, double?confidence) { Id = Guid.NewGuid(); Score = new InsightScore(); Symbol = symbol; Type = type; Direction = direction; Period = period; // Optional Magnitude = magnitude; Confidence = confidence; }
public void InsightsReturnsTargetsConsistentWithDirection(Language language, InsightDirection direction) { SetPortfolioConstruction(language, _algorithm); // Equity will be divided by all securities var amount = _algorithm.Portfolio.TotalPortfolioValue / _algorithm.Securities.Count; var expectedTargets = _algorithm.Securities .Select(x => new PortfolioTarget(x.Key, (int)direction * Math.Floor(amount * (1 - _algorithm.Settings.FreePortfolioValuePercentage) / x.Value.Price))); var insights = _algorithm.Securities.Keys.Select(x => GetInsight(x, direction, _algorithm.UtcTime)); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); AssertTargets(expectedTargets, actualTargets); }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="period">The period over which the prediction will come true</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percentage change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">An identifier defining the model that generated this insight</param> public Insight(Symbol symbol, TimeSpan period, InsightType type, InsightDirection direction, double? magnitude, double? confidence, string sourceModel = null) { Id = Guid.NewGuid(); Score = new InsightScore(); SourceModel = sourceModel; Symbol = symbol; Type = type; Direction = direction; Period = period; // Optional Magnitude = magnitude; Confidence = confidence; _periodSpecification = new TimeSpanPeriodSpecification(period); }
public void InsightsReturnsTargetsConsistentWithDirection(Language language, InsightDirection direction) { SetPortfolioConstruction(language); // Equity will be divided by all securities var amount = _algorithm.Portfolio.TotalPortfolioValue / _algorithm.Securities.Count; var expectedTargets = _algorithm.Securities .Select(x => new PortfolioTarget(x.Key, (int)direction * Math.Floor(amount / x.Value.Price))); var insights = _algorithm.Securities.Keys.Select(x => GetInsight(x, direction, _algorithm.UtcTime)); var actualTargets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, insights.ToArray()); Assert.AreEqual(expectedTargets.Count(), actualTargets.Count()); foreach (var expected in expectedTargets) { var actual = actualTargets.FirstOrDefault(x => x.Symbol == expected.Symbol); Assert.IsNotNull(actual); Assert.AreEqual(expected.Quantity, actual.Quantity); } }
/// <summary> /// Creates a new insight for predicting the percent change in price over the specified period /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="resolution">The resolution used to define the insight's period and also used to determine the insight's close time</param> /// <param name="barCount">The number of resolution time steps to make in market hours to compute the insight's closing time</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percent change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">The model generating this insight</param> /// <returns>A new insight object for the specified parameters</returns> public static Insight Price(Symbol symbol, Resolution resolution, int barCount, InsightDirection direction, double? magnitude = null, double? confidence = null, string sourceModel = null) { if (barCount < 1) { throw new ArgumentOutOfRangeException(nameof(barCount), $"Insight barCount must be greater than zero."); } var spec = new ResolutionBarCountPeriodSpecification(resolution, barCount); return new Insight(symbol, spec, InsightType.Price, direction, magnitude, confidence, sourceModel); }
public override void FlatDirectionNotAccountedToAllocation(Language language, InsightDirection direction) { SetPortfolioConstruction(language); // Equity, minus $1 for fees, will be divided by all securities minus 1, since its insight will have flat direction var amount = (Algorithm.Portfolio.TotalPortfolioValue - 1 * (Algorithm.Securities.Count - 1)) * 1 / (decimal)((1 / Weight) - 1) * (1 - Algorithm.Settings.FreePortfolioValuePercentage); var expectedTargets = Algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since its insight will have flat direction var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); var insights = Algorithm.Securities.Keys.Select(x => { // SPY insight direction is flat var actualDirection = x.Value == "SPY" ? InsightDirection.Flat : direction; return(GetInsight(x, actualDirection, Algorithm.UtcTime)); }); var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights.ToArray()); AssertTargets(expectedTargets, actualTargets); }
public override void DelistedSecurityEmitsFlatTargetWithNewInsights(Language language, InsightDirection direction) { SetPortfolioConstruction(language); var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) }; var targets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList(); Assert.AreEqual(1, targets.Count); // Removing SPY should clear the key in the insight collection var changes = SecurityChanges.Removed(Algorithm.Securities[Symbols.SPY]); Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes); // Equity will be divided by all securities minus 1, since SPY is already invested and we want to remove it var amount = Algorithm.Portfolio.TotalPortfolioValue / (decimal)(1 / Weight - 1) * (1 - Algorithm.Settings.FreePortfolioValuePercentage); var expectedTargets = Algorithm.Securities.Select(x => { // Expected target quantity for SPY is zero, since it will be removed var quantity = x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price); return(new PortfolioTarget(x.Key, quantity)); }); // Do no include SPY in the insights insights = Algorithm.Securities.Keys.Where(x => x.Value != "SPY") .Select(x => GetInsight(x, direction, Algorithm.UtcTime)).ToArray(); // Create target from an empty insights array var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights); AssertTargets(expectedTargets, actualTargets); }
public ConstantFutureContractAlphaModel(InsightType type, InsightDirection direction, TimeSpan period) : base(type, direction, period) { }
public override void AutomaticallyRemoveInvestedWithNewInsights(Language language, InsightDirection direction) { SetPortfolioConstruction(language); // Let's create a position for SPY var insights = new[] { GetInsight(Symbols.SPY, direction, Algorithm.UtcTime) }; foreach (var target in Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights)) { var holding = Algorithm.Portfolio[target.Symbol]; holding.SetHoldings(holding.Price, target.Quantity); Algorithm.Portfolio.SetCash(StartingCash - holding.HoldingsValue); } SetUtcTime(Algorithm.UtcTime.AddDays(2)); // Since we have 3 B, 2 T and 1 X, each security in each sector will get // B => .166%, T => .25, X => 0% (removed) var sectorCount = 2; var groupedBySector = Algorithm.Securities .Where(pair => pair.Value.Fundamentals?.CompanyReference?.IndustryTemplateCode != null) .GroupBy(pair => pair.Value.Fundamentals.CompanyReference.IndustryTemplateCode); var expectedTargets = new List <PortfolioTarget>(); foreach (var securities in groupedBySector) { var list = securities.ToList(); var amount = Algorithm.Portfolio.TotalPortfolioValue / list.Count / sectorCount * (1 - Algorithm.Settings.FreePortfolioValuePercentage); expectedTargets.AddRange(list .Select(x => new PortfolioTarget(x.Key, x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price)))); } // Do no include SPY in the insights insights = Algorithm.Securities.Keys.Where(x => x.Value != "SPY") .Select(x => GetInsight(x, direction, Algorithm.UtcTime)).ToArray(); var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights); Assert.Greater(Algorithm.Securities.Count, expectedTargets.Count); AssertTargets(expectedTargets, actualTargets); }
public override void FlatDirectionNotAccountedToAllocation(Language language, InsightDirection direction) { SetPortfolioConstruction(language); // Since we have 3 B, 2 T and 1 X, each security in each sector will get // B => .166%, T => .25, X => 0% (removed) var sectorCount = 2; var groupedBySector = Algorithm.Securities .Where(pair => pair.Value.Fundamentals?.CompanyReference?.IndustryTemplateCode != null) .GroupBy(pair => pair.Value.Fundamentals.CompanyReference.IndustryTemplateCode); var expectedTargets = new List <PortfolioTarget>(); foreach (var securities in groupedBySector) { var list = securities.ToList(); var amount = Algorithm.Portfolio.TotalPortfolioValue / list.Count / sectorCount * (1 - Algorithm.Settings.FreePortfolioValuePercentage); expectedTargets.AddRange(list .Select(x => new PortfolioTarget(x.Key, x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price)))); } var insights = Algorithm.Securities.Keys.Select(x => { // SPY insight direction is flat var actualDirection = x.Value == "SPY" ? InsightDirection.Flat : direction; return(GetInsight(x, actualDirection, Algorithm.UtcTime)); }); var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights.ToArray()); Assert.Greater(Algorithm.Securities.Count, expectedTargets.Count); AssertTargets(expectedTargets, actualTargets); }
public override void DelistedSecurityEmitsFlatTargetWithNewInsights(Language language, InsightDirection direction) { SetPortfolioConstruction(language); var insights = new[] { GetInsight(Symbols.SPY, InsightDirection.Down, Algorithm.UtcTime) }; var targets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights).ToList(); Assert.AreEqual(1, targets.Count); // Removing SPY should clear the key in the insight collection var changes = SecurityChanges.Removed(Algorithm.Securities[Symbols.SPY]); Algorithm.PortfolioConstruction.OnSecuritiesChanged(Algorithm, changes); // Since we have 3 B, 2 T and 1 X, each security in each sector will get // B => .166%, T => .25, X => 0% (removed) var sectorCount = 2; var groupedBySector = Algorithm.Securities .Where(pair => pair.Value.Fundamentals?.CompanyReference?.IndustryTemplateCode != null) .GroupBy(pair => pair.Value.Fundamentals.CompanyReference.IndustryTemplateCode); var expectedTargets = new List <PortfolioTarget>(); foreach (var securities in groupedBySector) { var list = securities.ToList(); var amount = Algorithm.Portfolio.TotalPortfolioValue / list.Count / sectorCount * (1 - Algorithm.Settings.FreePortfolioValuePercentage); expectedTargets.AddRange(list .Select(x => new PortfolioTarget(x.Key, x.Key.Value == "SPY" ? 0 : (int)direction * Math.Floor(amount / x.Value.Price)))); } // Do no include SPY in the insights insights = Algorithm.Securities.Keys.Where(x => x.Value != "SPY") .Select(x => GetInsight(x, direction, Algorithm.UtcTime)).ToArray(); // Create target from an empty insights array var actualTargets = Algorithm.PortfolioConstruction.CreateTargets(Algorithm, insights); Assert.Greater(Algorithm.Securities.Count, expectedTargets.Count); AssertTargets(expectedTargets, actualTargets); }