| Overall Statistics |
|
Total Trades 158 Average Win 0.03% Average Loss -0.03% Compounding Annual Return -18.572% Drawdown 0.700% Expectancy -0.255 Net Profit -0.487% Sharpe Ratio -3.334 Probabilistic Sharpe Ratio 27.827% Loss Rate 65% Win Rate 35% Profit-Loss Ratio 1.15 Alpha -0.161 Beta -0.101 Annual Standard Deviation 0.053 Annual Variance 0.003 Information Ratio -1.13 Tracking Error 0.289 Treynor Ratio 1.739 Total Fees $404.69 Estimated Strategy Capacity $930000.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
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):
insights = []
#try to update only every five minutes (this is where I need an alternative)
if algorithm.Time.minute%5!=0:
return insights
#reset rolling window every day
if algorithm.Time.hour==12 and algorithm.Time.minute==15:
for key, sd in self.symbolData.items():
sd.window.Reset()
algorithm.Log("fffffffff"+ str(sd.window.Count))
#only check between 13:00 and 13:50 each day
if algorithm.Time.hour!=13:
return insights
if algorithm.Time.minute//10>4:
return insights
alphas = dict()
#sort stocks by their current stochastic
for key, sd in self.symbolData.items():
if sd.Security.Price == 0:
continue
alphas[key]=sd.Stoc.StochK.Current.Value
selected = sorted(alphas.items(), key=lambda x: x[1], reverse=True)
algorithm.Log(len(selected))
#add True to the window of the top 5, false to the rest
for i in range(0,5):
self.symbolData[selected[i][0]].window.Add(True)
for i in range(5,29):
self.symbolData[selected[i][0]].window.Add(False)
#only start emitting insights after 13:20 to let the windows fill
if algorithm.Time.minute<16:
return 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 key, sd in self.symbolData.items():
if sd.window[0]==False and sd.window[1]==False and sd.window[2]==True:
insights.append(Insight.Price(sd.Security.Symbol, self.insightPeriod, InsightDirection.Down))
algorithm.Log(sd.window.Count)
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
algorithm.SubscriptionManager.RemoveConsolidator(removed.Symbol, data.Consolidator)
class SymbolData:
def __init__(self, algorithm, security, StochasticPeriod, KPeriod, DPeriod, resolution):
self.Security = security
self.Stoc= Stochastic(algorithm.CreateIndicatorName(security.Symbol, "STO" + str(StochasticPeriod), Resolution.Minute), StochasticPeriod, KPeriod, DPeriod)
self.Consolidator = algorithm.ResolveConsolidator(security.Symbol, timedelta(minutes=5))
algorithm.RegisterIndicator(security.Symbol, self.Stoc, self.Consolidator)
self.window = RollingWindow[bool](100)