Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
import pandas as pd
import operator
import sys

class ParticleNadirsonInterceptor(QCAlgorithm):
  
    
    def Initialize(self): 
        
        self.SetStartDate(2021, 1, 1)  # Set Start Date
        self.SetEndDate(2021, 1, 22)    # Set End Date
        self.SetCash(50000)          # Set Strategy Cash

        self.current_month = -1
        self.coarse_count = 50
        self.fine_count = 10
        
        self.benchmark="SPY"
        self.resolution = Resolution.Daily  
        self.SetBenchmark(self.benchmark)
        self.AddEquity(self.benchmark,self.resolution).Symbol
        
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionRsBased)
        self.SetAlpha(ConstantAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(30)))
        self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.035))
        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel(lambda time:None))
    
    def CoarseSelectionFunction(self, coarse):
    
            if self.current_month == self.Time.month:
                return Universe.Unchanged
    
            self.current_month = self.Time.month
    
            sortedByDollarVolume = sorted([x for x in coarse if x.HasFundamentalData],
                key=lambda x: x.DollarVolume, reverse=True)[:self.coarse_count] 
    
            resultSet=[i.Symbol for i in sortedByDollarVolume]

            return resultSet 
    
    def FineSelectionRsBased(self, fine):
        
        resultSet={}    
        rsBenchmark=self.getRslFactor(self.benchmark)

        for x in fine:
                resultSet[x.Symbol]=self.getRslFactor(str(x.Symbol.Value))

        resultSet=sorted([x for x in resultSet.items() if x[1]>rsBenchmark], key=lambda x: x[1], reverse=True)[:self.fine_count] 
        resultSet= [x[0] for x in resultSet]
        self.Log(f"sorted {resultSet}")
        return resultSet
        
    def getRslFactor(self,symbol):
        self.AddEquity(symbol, Resolution.Daily)
        rsl=-1000 # missing data workaround

        # lookback days : weight 
        days = {40:0.5,80:0.25,160:0.25}
        result=[]

        df=pd.DataFrame(self.History(self.Symbol(symbol), 300, Resolution.Daily)) 
        df=df.iloc[::-1]
        df=df.reset_index(level=0, drop=True)
        for x in days:
            try:
                result.append([symbol, x, df.iloc[0]['close'], df.iloc[x-1]['close'],days[x]])
                pass
            except (RuntimeError, TypeError, NameError):
                return rsl

        df = pd.DataFrame(result,columns=['Symbol','Days','Ref_Price','Close_Price','Weight'],dtype=float)
        df = df.assign(Rsl=(df['Ref_Price'])/df['Close_Price']*df['Weight'])
        rsl= round(float((abs(df['Rsl']).sum()*1000)-1000),5)
        
        return rsl
# selection - RS based / Z-score?
    # risk - manual (hourly) or mean reverse
    # rebalance - weekly based on growth
    # cash - increase size monthly
    
         # Returns True if TradeBar data is present else False
        #if not data.Bars.ContainKey(symbol):
        #return

    #self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFundamental)
    #    def FineSelectionFundamental(self, fine):
    
     #       fine = [x for x in fine if x.EarningReports.TotalDividendPerShare.ThreeMonths
     #                              and x.ValuationRatios.PriceChange1M 
     #                              and x.ValuationRatios.BookValuePerShare
     #                              and x.ValuationRatios.FCFYield]
    
    #        sortedByfactor1 = sorted(fine, key=lambda x: x.EarningReports.TotalDividendPerShare.ThreeMonths, reverse=True)
    #        sortedByfactor2 = sorted(fine, key=lambda x: x.ValuationRatios.PriceChange1M, reverse=False)
    #        sortedByfactor3 = sorted(fine, key=lambda x: x.ValuationRatios.BookValuePerShare, reverse=True)
    #        sortedByfactor4 = sorted(fine, key=lambda x: x.ValuationRatios.FCFYield, reverse=True)
    
    #        stock_dict = {}
    
    #        for rank1, ele in enumerate(sortedByfactor1):
    #            rank2 = sortedByfactor2.index(ele)
    #            rank3 = sortedByfactor3.index(ele)
    #            rank4 = sortedByfactor4.index(ele)
    #            stock_dict[ele] = rank1 + rank2 + rank3 + rank4
    
    #        sorted_stock = sorted(stock_dict.items(),
    #            key=lambda d:d[1], reverse=True)[:self.fine_count]
    
    #        return [x[0].Symbol for x in sorted_stock]