Converting algos from Quantopian

Hey, all. I have several live algos trading at Quantopian and am porting everything here. The conversion process is going slower than expected, so I am reaching out for help. I do not have a programming background, so these questions may seem naive. Many thanks!

The attached algo is simple. Buy SPY at 10am every day when the 1d MA >= 5d MA and exit if not. Questions:

1. How do I set a variable to equal the current price for SPY at 10am (when the scheduler calls the "Rebalance" function)?

2. How do I write a "for stock in" loop in the "Rebalance" function that (a) generates 1d MA and 5d MA for SPY and QQQ in "self.equities" (using "stock" rather than the hard coded SPY you see) and (b) places orders for SPY and QQQ if logic is met (again using "stock" rather than hard coded SPY)? 

3. How do you get comfortable that your trading logic is working when you cannot print the data like on Quantopian? For example, after someone (hopefully) shows me how to get the current price at 10am, how do I know that code is producing the right output. If I understand correctly, the data cannot be viewed in QC.

For Jared and Team QC, props on the platform! Very sophisticated. Would like to see more algo examples in Python (presumably with time via the community, but right now vast majority in C#) and a de-bugger for the IDE (I know this is on your priority list). Just being able to search for Python algos ONLY would also be a big help. I'm having trouble finding enough examples. Finally, looking forward to more order types on IB, esp the best efforts VWAP, in November.

Update Backtest

Dan, excellent work - crystal clear code. Thank you for the post. A follow up if I may...

I believe QC excludes the current price from self.History, unlike Quantopian. How would one call current prices for the symbol list, then merge with historical prices, and then calculate stdev including the current price (at the time of day when the function is scheduled)? The idea is to reflect current volatility conditions, rather than those of the prior day.

Second, I have only submitted orders by iterating through a preset security list or through pipeline on Quantopian. How would one submit orders from the pandas dataframe in QC? 

I made several attempts, but all ended in runtime errors, which I have struggled to comprehend on QC. Thanks in advance for your time.



You are correct that the QC 'History' method doesn't tack on the current data when requesting daily data. You can do that manually though. Just get the last minute data using 'History' with a minute resolution and then append that dataframe to the first.

# Get 21 previous days data plus the last minute data
history = self.History(self.symbols, 21, Resolution.Daily)
last_minute_data = self.History(self.symbols, 1, Resolution.Minute)

# Append the last minute data
history = history.append(last_minute_data)

Once the current data is appended, all the following logic remains the same.

There's a number of ways to submit orders on QC. I've mostly used the 'SetHoldings' method which is the same as the Quantopian 'order_target_percent'. Iterate through a list of symbols like this.

# Iterate through the self.symbols list to order
for stock in self.symbols:
# do whatever calculation to find weight
# here as an example it's just the ratio of std dev
weight = annl_stdev_series[stock] / annl_stdev_series.sum()
self.SetHoldings(stock, weight)

You could also iterate through the index of a dataframe (if you indexed it by symbols). Just remember to convert it to a list first (QC is particular about that).

# Iterate through a dataframe index
for stock in my_dataframe.index.tolist():
# do whatever you want here

Attached is your code with some of these changes. Take a look at the logs and you'll see the last minute data was appended correctly. Hope that helps...

Good luck.


Actually, the following DOES work to iterate through dataframe index. Just ensure the index is the 'symbol' (ie a string ticker symbol') and not a 'Security' object.

# Iterate through a dataframe index
for stock in my_dataframe.index:
# do whatever you want here like place an order
context.SetHoldings(stock, weight)

I like to use the name 'context' when referring to the algorithm object and 'self' if it's within some other class/situation. Just personal preference. Just a name. Didn't want to cause any confusion though.


Super helpful. Can't thank you enough.


Hello,  This algorithm is really helpful in getting started. Thanks 

One question: 

On the last line self.Log("{} {}".format(stock, weight))  the algorithm is logging what you have ordered. If we wanted to know how many stocks we actually bought how can we access the porfolio and get the log of securities owned ? 



Klaus, I run portfolio statistics on the close with the following function. It logs positions and overall portfolio leverage for a set list of securites in self.stocks. It doesn't list trades though.

    def PortfolioStats(self):
        port_val = self.Portfolio.TotalPortfolioValue
        for s in self.stocks:
            actual_weight = self.Portfolio[s].Quantity * self.Securities[s].Price / port_val 
            self.Log("{} {}".format(s, round(actual_weight, 3)))
        account_leverage = self.Portfolio.TotalAbsoluteHoldingsCost / port_val
        self.Log("{}%".format(round(account_leverage,3) * 100))


Hi Brett,

Would you mind sharing your justification for migrating from Quantopian to QuantConnect? My son-in-law is using Quantopian whereas I have briefly been exposed to QuantConnect. We would like to standardize on one of these two platforms before we get too far on developing algorithms. Any input from you that would help us reach a decision would be very appreciated.

All the best.


Update Backtest


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.


This discussion is closed