Running multiple algorithms on single account is supported by QC or Lean?
If yes, trading same instruments long/short by multiple algos is supported?
Running multiple algorithms on single account is supported by QC or Lean?
If yes, trading same instruments long/short by multiple algos is supported?
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Short answer: No, assuming you mean sub-account.
On e.g. Oanda (and I think also IB) you can have multiple sub-accounts and run algos individually.
Furthermore, on Oanda I suspect you might actually be able to connect multiple algos to the same account but the behavior is generally undefined and depending on what your algos are doing.
I know I can place trades in an algo account on Oanda manually, for instance, providing the algo isn't trying to do things that conflict with the trade. (Including use of margin, buying/selling/analyzing quantity of overlapping securities, and things like that.) However, I wouldn't bother trying to run two algos in crude fashion like this due to unforeseen potential problems.
As far as I know IB is probably more restrictive and you won't be able to make duplicate connections without interfering with the already open connection.
What you can do is to combine two different algos in the same QCAlgorithm, but this requires extra coding and may be especially complicated in the case they trade the same securities. Maybe you can also combine alphas trivially this way, haven't checked.
Petter is right, you have to code one algorithm properly to trade multiple strategies simultaniously. Alpha streams can do it too but you have to make a custom portfolio construction model based on the signals from each one.
It's nothing special really, it just takes the insights that dictate each allocation from each alpha and puts them in a table by symbol and source alpha model, then averages it, lastly it normalizes all the allocations to add up to 100%.
Example
Â
I'm sure the coding is awful but this is directly from my algorithm:
from clr import AddReference
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm.Framework")
from QuantConnect import Resolution, Extensions
from QuantConnect.Algorithm.Framework.Alphas import InsightCollection, InsightDirection
from QuantConnect.Algorithm.Framework.Portfolio import PortfolioConstructionModel, PortfolioTarget
from itertools import groupby
from datetime import datetime
from pytz import utc
UTCMIN = datetime.min.replace(tzinfo=utc)
import numpy as np
class Insight_Weighted_Portfolio(PortfolioConstructionModel):
def __init__(self, variables, resolution = Resolution.Daily, reserve = 0, leverage = 1.0, num_alphas = 1.0, normalize = False):
self.insightCollection = InsightCollection()
self.removedSymbols = []
self.addedSymbols = []
self.rebalancingTime = UTCMIN
self.rebalancingPeriod = Extensions.ToTimeSpan(resolution)
self.allocation = {}
self.reserved = reserve
self.max_leverage = leverage
self.normalize = normalize
self.num_alphas = num_alphas
self.var = variables
self.insight_list = []
self.symbol_list = []
def CreateTargets(self, algorithm, insights):
targets = []
self.insightCollection.AddRange(insights)
# Create Sell target for each security that was removed from the universe
if self.removedSymbols is not None:
universeDeselectionTargets = [ PortfolioTarget(symbol, 0) for symbol in self.removedSymbols ]
targets.extend(universeDeselectionTargets)
self.removedSymbols = None
if self.addedSymbols is not None:
for symbol in self.addedSymbols:
self.allocation[symbol] = {}
self.addedSymbols = None
#if algorithm.UtcTime <= self.rebalancingTime:
if not self.var.rebalance:
return targets
# Get insight that haven't expired of each symbol that is still in the universe
activeInsights = self.insightCollection.GetActiveInsights(algorithm.UtcTime)
# Get the last generated active insight for each symbol
lastActiveInsights = []
for symbol, g in groupby(activeInsights, lambda x: x.Symbol):
lastActiveInsights.append(sorted(g, key = lambda x: x.GeneratedTimeUtc)[-1])
#Gets Adjusted Portfolio value
port_value_adjusted = ((float(algorithm.Portfolio.TotalPortfolioValue)* self.max_leverage) - self.reserved)
if float(algorithm.Portfolio.TotalPortfolioValue) > 0.0:
max_leverage_adjusted = port_value_adjusted/float(algorithm.Portfolio.TotalPortfolioValue)
else:
max_leverage_adjusted = 0.0
for insight in lastActiveInsights:
if insight in self.insight_list:
#continue
pass
#self.insight_list.append(insight)
symbol = insight.Symbol
alpha = insight.SourceModel
if insight.Weight:
allocation = insight.Weight
else:
allocation = 0
#Calculate required rebalance amount for each allocation
if self.num_alphas == 0:
return targets
else:
goal_value = (port_value_adjusted * allocation / self.num_alphas)
#Adjusted % allocation
if float(algorithm.Portfolio.TotalPortfolioValue) == 0.0:
return targets
else:
try:
self.allocation[symbol][alpha] = goal_value/float(algorithm.Portfolio.TotalPortfolioValue)
except:
pass
#algorithm.Log(str(symbol) + " " + str(alpha))
combined_weight = {}
for symbol in self.allocation.keys():
wt = sum(list(self.allocation[symbol].values()))
combined_weight[symbol] = round(wt*200.0)/200.0
#option to normalize target_portfolio to fill all availible leverage
original_wt = sum(np.abs(list(combined_weight.values())))
if original_wt == 0.0:
factor = 0.0
else:
if self.normalize:
factor = max_leverage_adjusted/original_wt
elif original_wt > max_leverage_adjusted:
factor = max_leverage_adjusted/original_wt
else:
factor = 1.0
for symbol in combined_weight.keys():
combined_weight[symbol] = combined_weight[symbol]*factor
if algorithm.Securities[symbol].Price == 0.0:
continue
target = PortfolioTarget.Percent(algorithm, symbol, combined_weight[symbol])
if target != None:
targets.append(target)
#Log final desired allocation
if str(symbol) in self.var.assets_Leveraged:
continue
algorithm.Log(str(symbol) + " : " + str(round(combined_weight[symbol]*100,1)) + "% = " + str(int(target.Quantity)) + " shares.")
else:
pass
#algorithm.Debug("Target Error on " + str(symbol) + ". Should be " + str(round(combined_weight[symbol]*100,1)) + "%")
#self.rebalancingTime = algorithm.UtcTime + self.rebalancingPeriod
#algorithm.Debug("rebalance finished at " + str(algorithm.UtcTime))
self.var.rebalance = False
return targets
def OnSecuritiesChanged(self, algorithm, changes):
self.addedSymbols = [x.Symbol for x in changes.AddedSecurities]
# Get removed symbol and invalidate them in the insight collection
self.removedSymbols = [x.Symbol for x in changes.RemovedSecurities]
self.insightCollection.Clear(self.removedSymbols)
Â
Â
Â
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can
continue your Boot Camp training progress from the terminal. We
hope to see you in the community soon!