Hi friends,
I'm starting at Quantconnect and Python, and I would like to know if you can help me with a issue.
I like this strategy at
https://www.quantconnect.com/tutorials/strategy-library/capm-alpha-ranking-strategy-on-dow-30-companiesBut I would like to replace the manual stock list with a Universe. Any Idea o example thata can help me?
Thank you very much!
Aaron Janeiro Stone
Manual universe selection! In this example, merely add more symbols to the list. E.g.:
symbols = [ Symbol.Create("SPY", SecurityType.Equity, Market.USA), Symbol.Create("IEF", SecurityType.Equity, Market.USA) self.SetUniverseSelection(ManualUniverseSelectionModel(symbols)) ]
will give a universe with both SPY and IEF.
Saúl Rueda
Hi Aaron Janeiro Stone
thank you very much for your efforts, but it's not exactly what I was looking for. I'll try to be more concise.
In the following strategy I would like to substitute the tickers list with a Universe selection.
import numpy as np class BetaAlgorithm(QCAlgorithm): def Initialize(self): self.SetStartDate(2016, 1, 1) # Set Start Date self.SetEndDate(2017, 1, 1) # Set End Date self.SetCash(10000) # Set Strategy Cash # Dow 30 companies. self.symbols = [self.AddEquity(ticker).Symbol for ticker in ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM'] ] # Benchmark self.benchmark = Symbol.Create('SPY', SecurityType.Equity, Market.USA) # Set number days to trace back self.lookback = 21 # Schedule Event: trigger the event at the begining of each month. self.Schedule.On(self.DateRules.MonthStart(self.symbols[0]), self.TimeRules.AfterMarketOpen(self.symbols[0]), self.Rebalance) def Rebalance(self): # Fetch the historical data to perform the linear regression history = self.History( self.symbols + [self.benchmark], self.lookback, Resolution.Daily).close.unstack(level=0) symbols = self.SelectSymbols(history) # Liquidate positions that are not held by selected symbols for holdings in self.Portfolio.Values: symbol = holdings.Symbol if symbol not in symbols and holdings.Invested: self.Liquidate(symbol) # Invest 100% in the selected symbols for symbol in symbols: self.SetHoldings(symbol, 1) def SelectSymbols(self, history): '''Select symbols with the highest intercept/alpha to the benchmark ''' alphas = dict() # Get the benchmark returns benchmark = history[self.benchmark].pct_change().dropna() # Conducts linear regression for each symbol and save the intercept/alpha for symbol in self.symbols: # Get the security returns returns = history[symbol].pct_change().dropna() returns = np.vstack([returns, np.ones(len(returns))]).T # Simple linear regression function in Numpy result = np.linalg.lstsq(returns, benchmark) alphas[symbol] = result[0][1] # Select symbols with the highest intercept/alpha to the benchmark selected = sorted(alphas.items(), key=lambda x: x[1], reverse=True)[:2] return [x[0] for x in selected]
For example, I would like to substitute
# Dow 30 companies. self.symbols = [self.AddEquity(ticker).Symbol for ticker in ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM'] ]
And include a configured universe, for example:
# In Initialize: self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction) def CoarseSelectionFunction(self, coarse): sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True) filtered = [ x.Symbol for x in sortedByDollarVolume if x.HasFundamentalData ] return filtered[:50] def FineSelectionFunction(self, fine): sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=False) return [ x.Symbol for x in sortedByPeRatio[:10] ]
Solving this I can continue playing with code and refining stock selection.
Any help?
Thank you very much in advance!
Vncne
I'm also sort of new, but it looks like you already have the code, and the issue is how you can reconcile the universe selection code with your algorithm?
Just add this in Initialize:
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
And create the respective functions for the universe selection. How I do it is to then do this under OnData() in order to allocate to the securities within the Universe:
def OnData(self, data): if self.IsWarmingUp: return for security in self.changes.RemovedSecurities: if security.Invested: self.Liquidate(security.Symbol) for security in self.changes.AddedSecurities: if not security.Invested: self.SetHoldings(security.Symbol, 0.10)
Saúl Rueda
Hi Vncne and thank you!
I think I understand but it's even more difficult for me at this moment.
I would like to know if I could substitute the tickers static:
['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'V', 'VZ', 'WMT', 'XOM']
With a function or variable with the tickers from the defined Universe. I think it has to be easy but I can't find the key.
Thanks again!
Vncne
The securities in your universe are stored in self.ActiveSecurities so you could try:
(This allocates 10% of your portfolio to each security in the universe)
for security in self.ActiveSecurities.Values:
if not security.Invested:
self.SetHoldings(security.Symbol, 0.10)
Saúl Rueda
OK friend, thank you again.
I'm starting to understand this much better and with your help I'll try to fight with it.
However I hope could exist a simpler solution for me at this moment.
Kind regards!
Saúl Rueda
Hi friends, any help with this?
I'm fighting with it but I can't find a solution :'-(
Thanks in advance.
Jared Broad
Hey Saul! Please complete Boot Camp - it covers this in many of the interactive tutorial videos we've created for you. It will save your weeks of time from hacking away. I highly recommend investing 2 hours to walk through the tutorials.
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.
Saúl Rueda
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!