using System;
using System.Linq;
using QuantConnect.Indicators;
using QuantConnect.Models;
namespace QuantConnect.Algorithm.Examples
{
/// <summary>
///
/// QuantConnect University: EMA + SMA Cross
///
/// In this example we look at the canonical 20/50 day moving average cross. This algorithm
/// will go long when the 20 crosses above the 50 and will liquidate when the 20 crosses
/// back below the 50.
// -------VATS CHANGES -----------
// 1) Intraday - Hourly
// 2) 1/50 period SMA cross
//
// -------VATS CHANGES -----------
/// </summary>
public class QCUMovingAverageCross : QCAlgorithm
{
private const string Symbol = "USO";
private SimpleMovingAverage fast;
private SimpleMovingAverage slow;
//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
SetStartDate(2013, 01, 01);
SetEndDate(2015, 07, 15);
SetCash(10000);
// request SPY data with minute resolution
AddSecurity(SecurityType.Equity, Symbol, Resolution.Minute);
// create a 15 day exponential moving average
fast = SMA(Symbol, 1, Resolution.Hour);
// create a 30 day exponential moving average
slow = SMA(Symbol, 50, Resolution.Hour);
//SetRunMode(RunMode.Series);
}
private DateTime previous;
public void OnData(TradeBars data)
{
// a couple things to notice in this method:
// 1. We never need to 'update' our indicators with the data, the engine takes care of this for us
// 2. We can use indicators directly in math expressions
// 3. We can easily plot many indicators at the same time
// wait for our slow ema to fully initialize
if (!slow.IsReady) return;
// only once per day
// Commented the following line to simulate intraday - Vats
//if (previous.Date == data.Time.Date) return;
// define a small tolerance on our checks to avoid bouncing
const decimal tolerance = 0.00010m;
var holdings = Portfolio[Symbol].Quantity;
// we only want to go long if we're currently short or flat
// if the fast is greater than the slow, we'll go long
if (fast > slow * (1 + tolerance))
{
if (holdings <= 0)
{
Log("L >> " + holdings + "@ price " + Securities[Symbol].Price);
SetHoldings(Symbol, 0.95);
Log("NET POSITION BEFORE NEXT TRANSACTION >> " + holdings);
}
}
// we only want to liquidate if we're currently long
// if the fast is less than the slow we'll liquidate our long
if (fast < slow)
{
if (holdings > 0)
{
Log("SELL >> " + holdings + "@ price " + Securities[Symbol].Price);
SetHoldings(Symbol, -0.95);
}
}
Plot(Symbol, "Price", data[Symbol].Price);
// easily plot indicators, the series name will be the name of the indicator
Plot(Symbol, fast, slow);
previous = data.Time;
}
}
}