Overall Statistics
# region imports
from AlgorithmImports import *
# endregion

class FatRedMosquito(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2022, 1, 1)
        self.set_cash(100000)
        self.universe_settings.resolution = Resolution.DAILY

        # Gold miners ETF constituents
        universe = self.add_universe(lambda fundamental: [x.symbol for x in sorted([x for x in fundamental if x.has_fundamental_data and x.price > 5], key=lambda x: x.dollar_volume)[:20]])
        # Alpha specifically for gold miners
        gold = self.add_equity("GLD", Resolution.DAILY).symbol
        self.add_alpha(GoldMinerAlphaModel(gold, universe))

        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_DAY))

    
class GoldMinerAlphaModel(AlphaModel):
    def __init__(self, gold, universe):
        '''Instantiate a new instance of GoldMinerAlphaModel
        Parameter
        ---------
        - gold: Symbol
            Symbol of gold asset
        - universe: Universe
            A gold miner security universe reference that adapt GoldMinerAlphaModel
        '''
        self.gold = gold
        self.universe = universe

    def update(self, algorithm, data):
        insights = []

        if data.bars.contains_key(self.gold):
            gold = algorithm.securities[self.gold]
            gold_ema50 = gold.ema50.current.value

            if data.bars[self.gold].close > gold_ema50:
                insights.extend([
                    Insight.Price(member.key, timedelta(1), InsightDirection.UP) for member in self.universe.members
                ])
            else:
                insights.extend([
                    Insight.Price(member.key, timedelta(1), InsightDirection.DOWN) for member in self.universe.members
                ])

        return insights

    def on_securities_changed(self, algorithm, changes):
        for added in changes.added_securities:
            if added.symbol == self.gold:
                added.ema50 = algorithm.EMA(added.symbol, 50, Resolution.DAILY)
                algorithm.warm_up_indicator(added.symbol, added.ema50)