141 lines
6.0 KiB
Python
141 lines
6.0 KiB
Python
# 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 clr import AddReference
|
|
AddReference("System")
|
|
AddReference("QuantConnect.Algorithm")
|
|
AddReference("QuantConnect.Algorithm.Framework")
|
|
AddReference("QuantConnect.Common")
|
|
AddReference("QuantConnect.Indicators")
|
|
|
|
from System import *
|
|
from QuantConnect import *
|
|
from QuantConnect.Algorithm import *
|
|
from QuantConnect.Algorithm.Framework import QCAlgorithmFrameworkBridge
|
|
from QuantConnect.Algorithm.Framework.Alphas import *
|
|
from QuantConnect.Indicators import *
|
|
from QuantConnect.Orders.Fees import ConstantFeeModel
|
|
from QuantConnect.Data.Consolidators import *
|
|
from datetime import datetime, timedelta
|
|
|
|
#
|
|
# Reversal strategy that goes long when price crosses below SMA and Short when price crosses above SMA.
|
|
# The trading strategy is implemented only between 10AM - 3PM (NY time). Research suggests this is due to
|
|
# institutional trades during market hours which need hedging with the USD. Source paper:
|
|
# LeBaron, Zhao: Intraday Foreign Exchange Reversals
|
|
# http://people.brandeis.edu/~blebaron/wps/fxnyc.pdf
|
|
# http://www.fma.org/Reno/Papers/ForeignExchangeReversalsinNewYorkTime.pdf
|
|
#
|
|
class IntradayReversalCurrencyMarketsFrameworkAlgorithm(QCAlgorithmFramework):
|
|
|
|
def Initialize(self):
|
|
|
|
self.SetStartDate(2015, 1, 1)
|
|
self.SetCash(100000)
|
|
|
|
# Select resolution
|
|
resolution = Resolution.Hour
|
|
|
|
# Reversion on the USD.
|
|
symbols = [
|
|
Symbol.Create("EURUSD", SecurityType.Forex, Market.Oanda)
|
|
]
|
|
|
|
# Set requested data resolution
|
|
self.UniverseSettings.Resolution = resolution
|
|
self.SetUniverseSelection(ManualUniverseSelectionModel( symbols ))
|
|
self.SetAlpha(IntradayReversalAlphaModel(5, resolution))
|
|
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
|
|
self.SetExecution(ImmediateExecutionModel())
|
|
self.SetRiskManagement(NullRiskManagementModel())
|
|
|
|
#Set WarmUp for Indicators
|
|
self.SetWarmUp(20)
|
|
|
|
class IntradayReversalAlphaModel(AlphaModel):
|
|
'''Alpha model that uses a Price/SMA Crossover to create insights on Hourly Frequency.
|
|
Frequency: Hourly data with 5-hour simple moving average.
|
|
Strategy:
|
|
Reversal strategy that goes Long when price crosses below SMA and Short when price crosses above SMA.
|
|
The trading strategy is implemented only between 10AM - 3PM (NY time)'''
|
|
|
|
# Initialize variables
|
|
def __init__(self, period_sma = 5, resolution = Resolution.Hour):
|
|
self.period_sma = period_sma
|
|
self.resolution = resolution
|
|
self.cache = {} # Cache for SymbolData
|
|
self.Name = 'IntradayReversalAlphaModel'
|
|
|
|
def Update(self, algorithm, data):
|
|
# Set the time to close all positions at 3PM
|
|
self.timeToClose = datetime(algorithm.Time.year, algorithm.Time.month, algorithm.Time.day, 15, 1, 00, tzinfo = algorithm.Time.tzinfo)
|
|
|
|
insights = []
|
|
for security in algorithm.ActiveSecurities.Values:
|
|
|
|
if self.ShouldEmitInsight(algorithm, security.Symbol):
|
|
|
|
direction = InsightDirection.Down
|
|
|
|
if self.cache[security.Symbol].is_uptrend(algorithm.Securities[security.Symbol].Price):
|
|
direction = InsightDirection.Up
|
|
|
|
# Ignore signal for same direction as previous signal (when no crossover)
|
|
if direction == self.cache[security.Symbol].PreviousDirection:
|
|
continue
|
|
|
|
# Update the predictionInterval so insight goes Flat by timeToClose
|
|
predictionInterval = self.timeToClose - algorithm.Time
|
|
|
|
# Generate insight
|
|
insight = Insight.Price(security.Symbol, predictionInterval, direction)
|
|
|
|
# Save the current Insight Direction to check when the crossover happens
|
|
self.cache[security.Symbol].PreviousDirection = insight.Direction
|
|
insights.append(insight)
|
|
|
|
return insights
|
|
|
|
|
|
# Handle creation of the new security and its cache class.
|
|
# Simplified in this example as there is 1 asset.
|
|
def OnSecuritiesChanged(self, algorithm, changes):
|
|
for security in changes.AddedSecurities:
|
|
self.cache[security.Symbol] = SymbolData(algorithm, security.Symbol, self.period_sma, self.resolution)
|
|
|
|
|
|
# Time to control when to start and finish emitting (10AM to 3PM)
|
|
def ShouldEmitInsight(self, algorithm, symbol):
|
|
current = algorithm.Time
|
|
insightTimeStart = datetime(current.year, current.month, current.day, 10, 00, 00, tzinfo = current.tzinfo).time()
|
|
insightTimeEnd = datetime(current.year, current.month, current.day, 15, 00, 00, tzinfo = current.tzinfo).time()
|
|
currentTime = current.time()
|
|
|
|
if not algorithm.Securities[symbol].HasData or currentTime < insightTimeStart or currentTime > insightTimeEnd:
|
|
return False
|
|
else:
|
|
return True
|
|
|
|
|
|
class SymbolData:
|
|
|
|
def __init__(self, algorithm, symbol, period_sma, resolution):
|
|
self.PreviousDirection = None
|
|
self.priceSMA = algorithm.SMA(symbol, period_sma, resolution)
|
|
|
|
def is_uptrend(self, price):
|
|
if self.priceSMA.IsReady:
|
|
return price < self.priceSMA.Current.Value * 1.001
|
|
else:
|
|
return False
|