# 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.from AlgorithmImports import *from sklearn.linear_model import LinearRegressionclass ScikitLearnLinearRegressionAlgorithm(QCAlgorithm):def initialize(self):self.set_start_date(2013, 10, 7) # Set Start Dateself.set_end_date(2013, 10, 8) # Set End Dateself.lookback = 30 # number of previous days for trainingself.set_cash(100000) # Set Strategy Cashspy = self.add_equity("SPY", Resolution.MINUTE)self.symbols = [ spy.symbol ] # In the future, we can include more symbols to the list in this wayself.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 28), self.regression)self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 30), self.trade)def regression(self):# Daily historical data is used to train the machine learning modelhistory = self.history(self.symbols, self.lookback, Resolution.DAILY)# price dictionary: key: symbol; value: historical priceself.prices = {}# slope dictionary: key: symbol; value: slopeself.slopes = {}for symbol in self.symbols:if not history.empty:# get historical open priceself.prices[symbol] = list(history.loc[symbol.value]['open'])# A is the design matrixA = range(self.lookback + 1)for symbol in self.symbols:if symbol in self.prices:# responseY = self.prices[symbol]# featuresX = np.column_stack([np.ones(len(A)), A])# data preparationlength = min(len(X), len(Y))X = X[-length:]Y = Y[-length:]A = A[-length:]# fit the linear regressionreg = LinearRegression().fit(X, Y)# run linear regression y = ax + bb = reg.intercept_a = reg.coef_[1]# store slopes for symbolsself.slopes[symbol] = a/bdef trade(self):# if there is no open priceif not self.prices:returnthod_buy = 0.001 # threshold of slope to buythod_liquidate = -0.001 # threshold of slope to liquidatefor holding in self.portfolio.values():slope = self.slopes[holding.symbol]# liquidate when slope smaller than thod_liquidateif holding.invested and slope < thod_liquidate:self.liquidate(holding.symbol)for symbol in self.symbols:# buy when slope larger than thod_buyif self.slopes[symbol] > thod_buy:self.set_holdings(symbol, 1 / len(self.symbols))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。