| 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 Estimated Strategy Capacity $0 Lowest Capacity Asset |
#region imports
from AlgorithmImports import *
import math
#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]
symbol = SymbolCache.GetSymbol(ticker)
if ticker_history.empty or "close" not in ticker_history or ticker_history.close.isnull().values.any() == True or algorithm.Securities[symbol].HasData == False:
history.drop(ticker, level=0)
#algorithm.Securities[symbol].IsTradable
history = history.close.unstack(level=0)
test = []
returns = {}
for i in range(len(history.columns)):
dailyreturn = history.iloc[:,i][-2]-history.iloc[:,i][0]
#check if we get a nan
if math.isnan(dailyreturn) == True:
test.append(history.iloc[:,i].name)
self.symbolData.remove(history.iloc[:,i].name)
continue
returns[self.symbolData[i]] = dailyreturn
for name in test:
history.drop(name, axis=1, inplace =True)
#history.drop(history.iloc[:,i].name, axis=1, inplace = True)
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, 8, 13) # Set Start Date'
self.SetEndDate(2021, 8, 14)
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.SetPortfolioConstruction(InsightWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())
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