## Converting Portfolio Balancing Classic Algorithm to a Framework Algorithm

I have following Classic Algorithm that hourly rebalances the portfolio with setHoldings. I would like to convert this into a Framework algorithm so that I can benefit from the more advanced execution models (such as stdev, wvap) that are already available there for plugging into other portfolio balancing samples (uniform, mean-variance, black-litterman) within the framework. I would be more than glad if someone from the community can help me in achieving that.

import io, requests
import numpy as np
import pandas as pd
from datetime import timedelta

assets = ['AUDUSD', 'EURUSD', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY', 'USDNOK', 'USDSEK', 'USDSGD']
No_Channels = 10
Input_Size = 256

class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019,1,3)  #Set Start Date
self.SetEndDate(2019,3,8)    #Set End Date
self.SetCash(100000)           #Set Strategy Cash
self.SetBrokerageModel(BrokerageName.OandaBrokerage)
for asset in assets: self.AddForex(asset, Resolution.Hour, Market.Oanda, True, 1.0)
self.History(512, Resolution.Hour)

def OnData(self, data):
cc = None
for asset in assets:
df = self.History([asset], timedelta(14), Resolution.Hour).loc[asset]
df = df['close'].resample('1H').interpolate(method='cubic')
if asset[-3:] != 'USD': df = 1.0 / df
df = np.log((df/df.shift(1)).tail(Input_Size))
cc = df if cc is None else: cc = pd.concat([cc, df], axis=1)
X = np.swapaxes(cc.values, 0, 1)
data = {'arr': X.reshape(-1).tolist()}
response = requests.post('https://api.server/model', json=data)
weights = np.array(response.json()['arr'])
self.Debug(weights)
for i, asset in enumerate(assets):
howmuch = weights[i] if asset[-3:] == 'USD' else (-1.0*weights[i])
self.SetHoldings(asset, howmuch)

0

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.

Hi Kamer,

Great to hear that you're interested in building Framework Algorithms! I've attached a backtest below that does a rough implementation of the code you posted which uses a custom Alpha Model and custom Portfolio Construction Model as examples of how you might construct these. Have a look and hopefully this provides you with something to build on. Additionally, I would recommend thoroughly reading the Algorithm Framework documentation and viewing the different models for Alphas in GitHub.

0

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.

Dear Jack, this has been super helpful and I can't tell you how much I appreciated it. What I did not understood at all yet is what are Insights and what are their function. I would be glad if you can explain those further. I also guess the parts that are removing symbols are unnecessary, as I am always balancing the same FX assets.

0

Insights are an expected return prediction made for a security in the universe. Each insight is emitted for a specific Symbol and has a number of different attributes, all of which you can read about here. The best way to understand Insights is that they are the main packets of information generated by your algorithm, and they are used in constructing portfolios, executing trades, and managing portfolio risk.

You're correct, the changes.RemovedSymbols is unnecessary if you employ a ManualUniverseSelection() model and don't adjust the universe after initialization.

0

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.

What if I don't have expected returns, then can I get rid of those parts? (I have expected return for the whole portfolio decision not for each asset). Can you help me to simplify previous version of code that you shared?

0

As far as I checked the document, having Insights seems to be a vital part of licensing the model on Alpha Streams. I don't have those expectations on asset basis unfortunately. What is more important for a portfolio balancing model is accurately predicting the outcome of its decision (portfolio distribution) rather than returns of assets independently.

0

You can use individual asset movement projections to dictate to a Portfolio Construction model on how to allocate resources to each asset and determine how it wants to rebalance. Inisights are the foundation of Alpha Streams and the basis upon which funds will view and potentially license your algorithms. The predictions need not be perfect, but to figure out resource allocation for building a portfolio model, the algorithm needs to have some idea of which assets are likely to move in a given direction and when.

0

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.

Hi Kamer Ali Yüksel,

Could you please share your Flask server code for your external pytorch model (that API link) which is too heavy to run on Quantconnect? How did you set it up? Much appreciated it!! Please. Thanks.

0

0

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.