Overall Statistics
Total Trades
151
Average Win
0.03%
Average Loss
-0.03%
Compounding Annual Return
-15.543%
Drawdown
0.700%
Expectancy
-0.189
Net Profit
-0.400%
Sharpe Ratio
-2.816
Probabilistic Sharpe Ratio
30.086%
Loss Rate
59%
Win Rate
41%
Profit-Loss Ratio
0.97
Alpha
-0.148
Beta
-0.128
Annual Standard Deviation
0.06
Annual Variance
0.004
Information Ratio
-1.072
Tracking Error
0.297
Treynor Ratio
1.309
Total Fees
$456.09
Estimated Strategy Capacity
$690000.00
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

import requests
from QuantConnect import *
from QuantConnect.Indicators import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Alphas import *

from datetime import timedelta
from enum import Enum
import pandas as pd

class CryingYellowGreenSeahorse(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2015, 9, 2)
        self.SetEndDate(2015,9,10)# Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        
        self.SetWarmup(200)
        
        self.AddAlpha(MacdAlphaModel(resolution= Resolution.Minute))

        self.SetExecution(ImmediateExecutionModel())

        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())

        symbols = [ ]
        z=['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']
        for b in z:
            symbols.append(Symbol.Create(b, SecurityType.Equity, Market.USA))
        self.SetUniverseSelection( ManualUniverseSelectionModel(symbols) )


    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
            Arguments:
                data: Slice object keyed by symbol containing the stock data
        '''

        # if not self.Portfolio.Invested:
        #    self.SetHoldings("SPY", 1)
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.





class MacdAlphaModel(AlphaModel):
    

    def __init__(self,
    StochasticPeriod = 14,
    KPeriod = 3,
    DPeriod = 3,
                 
                 resolution = Resolution.Minute):
        ''' Initializes a new instance of the MacdAlphaModel class
        Args:
            fastPeriod: The MACD fast period
            slowPeriod: The MACD slow period</param>
            signalPeriod: The smoothing period for the MACD signal
            movingAverageType: The type of moving average to use in the MACD'''
        
        self.StochasticPeriod = 14
        self.KPeriod = 3
        self.DPeriod = 3
        
        self.resolution = resolution
        self.insightPeriod = Time.Multiply(Extensions.ToTimeSpan(resolution), DPeriod*4)
        
        self.symbolData = {}


    def Update(self, algorithm, data):
        if data.Time.minute % 5 != 0 or data.Time.hour != 13 or data.Time.minute < 20 or data.Time.minute > 50:
            return []
       
        stoch_history_by_symbol = pd.DataFrame()
       
        insights = []
        #if a stock has been in the top 5 by StochK but for 2 periods it's out of the top 5, send a Down insight
        for symbol, symbol_data in self.symbolData.items():
            if symbol_data.IsReady: # and symbol_data.window[0]==False and symbol_data.window[1]==False and symbol_data.window[2]==True:
                for i in range(3):
                    stoch_history_by_symbol.loc[symbol_data.Symbol, f'window[{i}]'] = symbol_data.window[i]
        
        top_5 = stoch_history_by_symbol.rank(ascending=False) <= 5
        selected = top_5[((top_5['window[0]'] == False) & (top_5['window[1]'] == False) & (top_5['window[2]']))]
        
        symbols = selected.index
        for symbol in symbols:
            insights.append(Insight.Price(symbol, self.insightPeriod, InsightDirection.Down))
        return insights
            
            

    def OnSecuritiesChanged(self, algorithm, changes):
        '''Event fired each time the we add/remove securities from the data feed.
        This initializes the MACD for each added security and cleans up the indicator for each removed security.
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            changes: The security additions and removals from the algorithm'''
        for added in changes.AddedSecurities:
            self.symbolData[added.Symbol] = SymbolData(algorithm, added, self.StochasticPeriod, self.KPeriod, self.DPeriod,  self.resolution)

        for removed in changes.RemovedSecurities:
            data = self.symbolData.pop(removed.Symbol, None)
            if data is not None:
                # clean up our consolidator
                data.dispose()
                algorithm.SubscriptionManager.RemoveConsolidator(removed.Symbol, data.Consolidator)

class SymbolData:
    def __init__(self, algorithm, security, StochasticPeriod, KPeriod, DPeriod,  resolution):
        self.algorithm = algorithm
        self.Symbol = security.Symbol
        self.Stochastic = Stochastic(algorithm.CreateIndicatorName(security.Symbol, "STO" + str(StochasticPeriod), Resolution.Minute), StochasticPeriod, KPeriod, DPeriod)
        self.window = RollingWindow[float](3)
        
        # Setup consolidator
        self.consolidator = TradeBarConsolidator(timedelta(minutes=5))
        self.consolidator.DataConsolidated += self.consolidation_handler
        algorithm.SubscriptionManager.AddConsolidator(self.Symbol, self.consolidator)
        
    def consolidation_handler(self, sender, consolidated):
        if self.Stochastic.Update(consolidated):
            self.window.Add(self.Stochastic.StochK.Current.Value)
       
    @property 
    def IsReady(self):
        return self.window.IsReady
        
        
    def dispose(self):
        self.algorithm.SubscriptionManager.RemoveConsolidator(self.Symbol, self.consolidator)