| Overall Statistics |
|
Total Trades 45282 Average Win 0.01% Average Loss 0.00% Compounding Annual Return 0.013% Drawdown 12.700% Expectancy -0.011 Net Profit 0.118% Sharpe Ratio 0.015 Probabilistic Sharpe Ratio 0.018% Loss Rate 69% Win Rate 31% Profit-Loss Ratio 2.16 Alpha 0.003 Beta -0.035 Annual Standard Deviation 0.021 Annual Variance 0 Information Ratio -0.559 Tracking Error 0.155 Treynor Ratio -0.009 Total Fees $48708.25 Estimated Strategy Capacity $1100000.00 Lowest Capacity Asset BIL TT1EBZ21QWKL |
#region imports
from AlgorithmImports import *
from sklearn.ensemble import RandomForestRegressor
#endregion
class RandomForestRegressionDemo(QCAlgorithm):
def Initialize(self):
#1. Required: Five years of backtest history
self.SetStartDate(2014, 1, 1)
#2. Required: Alpha Streams Models:
self.SetBrokerageModel(BrokerageName.AlphaStreams)
#3. Required: Significant AUM Capacity
self.SetCash(1000000)
#4. Required: Benchmark to SPY
self.SetBenchmark("SPY")
self.SetPortfolioConstruction(MeanVarianceOptimizationPortfolioConstructionModel(portfolioBias = PortfolioBias.Long,
period=5))
self.SetExecution(ImmediateExecutionModel())
self.assets = ["SHY", "TLT", "IEI", "SHV", "TLH", "EDV", "BIL",
"SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT",
"VGLT", "SCHO", "SCHR", "SPTS", "GOVT"]
# Add Equity ------------------------------------------------
for i in range(len(self.assets)):
self.AddEquity(self.assets[i], Resolution.Minute)
# Initialize the timer to train the Machine Learning model
self.time = datetime.min
# Set Scheduled Event Method For Our Model
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.BeforeMarketClose("SHY", 5), self.EveryDayBeforeMarketClose)
def BuildModel(self):
# Initialize the Random Forest Regressor
self.regressor = RandomForestRegressor(n_estimators=100, min_samples_split=5, random_state = 1990)
# Get historical data
history = self.History(self.Securities.Keys, 360, Resolution.Daily)
# Select the close column and then call the unstack method.
df = history['close'].unstack(level=0)
# Feature engineer the data for input.
input_ = df.diff() * 0.5 + df * 0.5
input_ = input_.iloc[1:].ffill().fillna(0)
# Shift the data for 1-step backward as training output result.
output = df.shift(-1).iloc[:-1].ffill().fillna(0)
# Fit the regressor
self.regressor.fit(input_, output)
def EveryDayBeforeMarketClose(self):
# Retrain the regressor every week
if self.time < self.Time:
self.BuildModel()
self.time = Expiry.EndOfWeek(self.Time)
qb = self
# Fetch history on our universe
df = qb.History(qb.Securities.Keys, 2, Resolution.Daily)
if df.empty: return
# Make all of them into a single time index.
df = df.close.unstack(level=0)
# Feature engineer the data for input
input_ = df.diff() * 0.5 + df * 0.5
input_ = input_.iloc[-1].fillna(0).values.reshape(1, -1)
# Predict the expected price
predictions = self.regressor.predict(input_)
# Get the expected return
predictions = (predictions - df.iloc[-1].values) / df.iloc[-1].values
predictions = predictions.flatten()
# ==============================
insights = []
for i in range(len(predictions)):
insights.append( Insight.Price(self.assets[i], timedelta(days=1), InsightDirection.Up, predictions[i]) )
self.EmitInsights(insights)