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.172
Tracking Error
0.175
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
#region imports
from AlgorithmImports import *
#endregion


class MeanReversion(AlphaModel):
    def __init__(self):
        self.symbolData = []

    def Update(self, algorithm, data):
        time = algorithm.Time
        insights = []

        #Near the market close of each day
        for symbol in self.symbolData:
            isClosingSoon = algorithm.Securities[symbol].Exchange.IsClosingSoon(1)
            if isClosingSoon == True:
                break
            else:
                return insights

        startdate = time-timedelta(days=1)
        enddate = time

        history = algorithm.History(self.symbolData, startdate, enddate, Resolution.Minute)

        #Hvis vi får nul data, så returnerer vi
        if history.empty: 
            return insights

        #Vi får vores tickers
        tickers = history.index.levels[0]

        #Looper over vores tickers, hvis nogle af dem har tomme data eller close ikke er der, så dropper vi dem
        for ticker in tickers:
            ticker_history = history.loc[ticker]
            if ticker_history.empty or "close" not in ticker_history:
                history.drop(ticker, level=0)

        history = history.close.unstack(level=0)

        returns = {}
        for i in range(len(history.columns)):
            dailyreturn = history.iloc[:,i][-2]-history.iloc[:,i][0]
            returns[self.symbolData[i]] = dailyreturn

        rj = sum(returns.values())/len(self.symbolData)

        weights = {}
        sum123 = 0
        for i in range(len(history.columns)):
            sum123 += abs(returns[self.symbolData[i]]-rj)

        for i in range(len(history.columns)):
            weight = -(returns[self.symbolData[i]]-rj)/sum123
            weights[self.symbolData[i]] = weight
        
        for key,value in weights.items():
            if value > 0:
                direction = InsightDirection.Up
            else: direction = InsightDirection.Down
            insights.append(Insight.Price(key, timedelta(minutes = 20), direction, weight = value))

        return insights


    def OnSecuritiesChanged(self, algorithm, changes):
        for added in changes.AddedSecurities:
            self.symbolData.append(added.Symbol)

        for removed in changes.RemovedSecurities:
            self.symbolData.remove(removed.Symbol)

# Your New Python File
# region imports
from AlgorithmImports import *
from MeanReversionAlpha import MeanReversion
# endregion

class EmotionalYellowGull(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2021, 7, 4)  # Set Start Date'
        self.SetCash(100000)  # Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Minute
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)

        seeder = FuncSecuritySeeder(self.GetLastKnownPrices)
        self.SetSecurityInitializer(lambda security: seeder.SeedSecurity(security))

        self.SetBenchmark('SPY')

        etf_symbol = "ITA"

        universe = self.Universe.ETF(etf_symbol, Market.USA, 
                   self.UniverseSettings, self.ETFConstituentsFilter)
        self.AddUniverse(universe)
        self.AddAlpha(MeanReversion())

        self.lastMonth = -1

    def ETFConstituentsFilter(self, constituents: List[ETFConstituentData]) -> List[Symbol]:
        if self.Time.month == self.lastMonth:
	        return Universe.Unchanged
        self.lastMonth = self.Time.month

        selected = [c.Symbol for c in constituents]

        return selected