| Overall Statistics |
|
Total Trades 74 Average Win 4.88% Average Loss -0.73% Annual Return 18.849% Drawdown 37.100% Expectancy 1.398 Net Profit 104.865% Sharpe Ratio 0.7 Loss Rate 69% Win Rate 31% Profit-Loss Ratio 6.71 Trade Frequency Weekly trades |
-no value-
using System;
using System.Collections;
using System.Collections.Generic;
using QuantConnect.Securities;
using QuantConnect.Models;
namespace QuantConnect {
// HOW TO USE:
// 1. Create new instance of consolidator: 5 minutes / 5 bars joined.
// public Consolidator barConsolidator = new Consolidator(5);
//
// 2. Exit the dataHandler until it returns true:
// //Add this 1 min to the Consolidator.
// if (!barConsolidator.Update(data["MSFT"])) return;
//
// 3. Once we have 5 bars it returns true, and we fetch the bar here:
// TradeBar msft = barConsolidator.Bar;
//
public class Consolidator {
private int requestedCount = 0;
private int barCount = 0;
private Queue<TradeBar> barQueue;
//Accessor - Create the x-"Bar" when the Update returns true.
public TradeBar Bar {
get {
return this.Generate();
}
}
//Initialize the Consolidator
public Consolidator(int iBars) {
//Number of TradeBars we want to join together (e.g. 5 min bars = 5 x 1 min bars)
this.requestedCount = iBars;
this.barCount = 0;
// Queue to store the bars temporarily.
this.barQueue = new Queue<TradeBar>(barCount);
}
// Add a bar to the list, when it totals X bars return a new tradebar.
public bool Update(TradeBar bar) {
//Add this bar to the queue:
barQueue.Enqueue(bar);
//Use a counter to speed up the counting.
barCount++;
if (barCount == requestedCount) {
return true;
} else {
return false;
}
}
//Using the barQueue generate a new "consolidated bar" then return
private TradeBar Generate() {
string symbol = "";
long volume = 0;
DateTime barOpenTime = new DateTime();
decimal open = Decimal.Zero, high = Decimal.MinValue, low = Decimal.MaxValue, close = Decimal.Zero;
//Create the new bar:
while(barCount > 0) {
TradeBar bar = barQueue.Dequeue();
if (barOpenTime == new DateTime()) barOpenTime = bar.Time;
if (symbol == "") symbol = bar.Symbol;
if (open == Decimal.Zero) open = bar.Open;
if (high < bar.High) high = bar.High;
if (low > bar.Low) low = bar.Low;
close = bar.Close;
volume = bar.Volume;
barCount--;
}
//Reset ready for next bar:
barQueue.Clear();
//Create the new trade bar.
return new TradeBar(barOpenTime, symbol, open, high, low, close, volume);
}
}
}using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Text;
using System.Linq;
using QuantConnect.Models;
namespace QuantConnect {
/*
* SMA Indicator: Online calculator for faster backtesting.
*
* To use this indicator:
* 1. Create an instance of it in your algorithm:
* SMA sma10 = new SMA(10);
*
* 2. Push in data with AddSample:
* decimal sma = sma10.AddSample(data["spy"].Close);
*
* 3. If you're sensitive to the precise SMA values you push wait until the indicator is Ready.
*/
public class SimpleMovingAverage
{
//Class Variables:
private int period, samples;
private decimal sma, sum, divisor;
private FixedSizedQueue<decimal> sampleQueue;
// Initialise the Simple Moving Average
public SimpleMovingAverage(int period) {
this.period = period;
this.samples = 0;
this.sampleQueue = new FixedSizedQueue<decimal>(period);
}
//Public Result Access: Current value of the SMA.
public decimal SMA {
get{ return sma;}
}
//Public Result Access: Track the number of samples:
public int Samples {
get { return samples; }
}
//Public Result Access: We've got sufficient data samples to know its the SMA.
public bool Ready {
get { return samples >= period; }
}
// Online implementation of simple moving average
public decimal AddSample(decimal quote)
{
samples++;
sum += quote;
//Add this sample to the SMA, subtract the previous
sampleQueue.Enqueue(quote);
if (sampleQueue.Size == period) {
//"last" is a dequeued item: minus it from the SMA.
sum -= sampleQueue.LastDequeued;
}
//When less than period samples, only divide by the number of samples.
if (samples < period) {
divisor = samples;
} else {
divisor = period;
}
sma = sum / divisor;
return sma;
}
//Fixed length queue that dumps things off when no more space in queue.
private class FixedSizedQueue<T> : ConcurrentQueue<T> {
public int Size { get; private set; }
public T LastDequeued { get; private set; }
public FixedSizedQueue(int size) { Size = size; }
public new void Enqueue(T obj) {
base.Enqueue(obj);
lock (this) {
if (base.Count > Size) {
T outObj;
base.TryDequeue(out outObj);
LastDequeued = outObj;
}
}
}
}
}
}using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using QuantConnect.Models;
namespace QuantConnect {
public class ExponentialMovingAverage
{
private int _period;
private decimal _ema;
private int _samples;
private decimal _expConstant;
private bool flag;
private Queue<decimal> _data = new Queue<decimal>();
//Initialize the Algorithm
public ExponentialMovingAverage(int period) {
_period = period;
_ema = 0;
flag = false;
_expConstant = (decimal) (2 / (_period +1));
}
//Public Result Access: Current value of the EMA.
public decimal EMA {
get{ return _ema;}
}
//Public Result Access: Track the number of samples:
public int Samples {
get { return _samples; }
}
//Public Result Access: We've got sufficient data samples to know its the EMA.
public bool Ready {
get { return _data.Count >= _period; }
}
/// Calculate the exponential moving average
public decimal AddSample(decimal quote)
{
_data.Enqueue(quote);
_samples++;
if(_data.Count < _period)
{
return _data.Average();
}
else
{
if(!flag)
{
_ema = _data.Average();
flag = true;
}
else
{
_ema = (1-_expConstant) * _ema + _expConstant * quote;
}
}
return _ema;
}
}
}using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Indicator;
namespace QuantConnect
{
using QuantConnect.Securities;
using QuantConnect.Models;
public class BasicTemplateAlgorithm : QCAlgorithm, IAlgorithm
{
SimpleMovingAverage sma35100 = new SimpleMovingAverage(35100);
SimpleMovingAverage sma70200 = new SimpleMovingAverage(70200);
// 1. Create new instance of consolidator: 5 minutes / 5 bars joined.
//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
//Initialize the start, end dates for simulation; cash and data required.
SetStartDate(1999, 03, 01);
SetEndDate(2003, 01, 01);
SetCash(30000); //Starting Cash in USD.
AddSecurity(SecurityType.Equity, "QQQ", Resolution.Minute); //Minute, Second or Tick
SetRunMode(RunMode.Series); //Series or Parallel for intraday strategies.
}
//Handle TradeBar Events: a TradeBar occurs on every time-interval
public override void OnTradeBar(Dictionary<string, TradeBar> data)
{
sma35100.AddSample(Securities["QQQ"].Close);
sma70200.AddSample(Securities["QQQ"].Close);
if (sma35100.SMA > sma70200.SMA)
{
Order("QQQ", 50); //symbol, quantity
return;
}
else
{
Order("QQQ", -50); //symbol, quantity
return;
}
}
//Handle Tick Events
public override void OnTick(Dictionary<string, List<Tick>> ticks)
{
if (Portfolio["QQQ"].HoldStock == false)
{
Order("QQQ", 5);
}
}
}
}/*
Created July 2013 by Cheng Yan
*/
/**********************************************************
* USING NAMESPACES
**********************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using QuantConnect;
using QuantConnect.Models;
namespace QuantConnect.Indicator
{
/********************************************************
* CLASS DEFINITIONS
*********************************************************/
/// <summary>
/// An indicator shows the average value of secuitry's price
/// over a set period
/// </summary>
public class ExponentialMovingAverage : QCAlgorithm
{
/********************************************************
* CLASS VARIABLES
*********************************************************/
private int _period;
private decimal _ema;
private bool flag;
private Queue <decimal>_data = new Queue <decimal> ();
/********************************************************
* CLASS PUBLIC VARIABLES
*********************************************************/
public decimal EMA
{
get{ return _ema;}
}
public decimal GetExpConst
{
get{ return (decimal) 2/(_period +1);}
}
/********************************************************
* CLASS CONSTRUCTOR
*********************************************************/
/// <summary>
/// Initialise the Algorithm
/// </summary>
public ExponentialMovingAverage(int period)
{
_period = period;
_ema = 0;
flag = false;
}
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Calculate the exponential moving average
/// </summary>
public void Push(decimal quote)
{
_data.Enqueue(quote);
}
/// <summary>
/// Calculate the exponential moving average
/// </summary>
public void GetEMA(decimal quote)
{
Push(quote);
if(_data.Count < _period)
{
return;
}
else
{
if(!flag)
{
_ema = _data.Average();
flag = true;
}
else
{
_ema = (1-GetExpConst) * _ema +GetExpConst * quote;
}
}
}
}
}/// <summary>
/// Basic Template v0.1 :: Rolling Average
/// </summary>
using System;
using System.Collections;
using System.Collections.Generic;
namespace QuantConnect {
/// <summary>
/// Example Helper Class: Basic Math Routines.
/// Using the QCS you can create subfolders, classes.
/// All the code is compiled into your algorithm.
/// </summary>
public partial class MathAverage {
public int iSamplePeriod = 10;
public decimal dCurrentAverage = 0;
/// <summary>
/// Example helper class: Add a new sample to a rolling average.
/// </summary>
/// <param name="dNewSample">Decimal new sample value</param>
/// <returns>decimal current rolling average.</returns>
public static decimal RollingAverage(decimal dNewSample) {
Random cRand = new Random();
return dNewSample * ((decimal)cRand.NextDouble());
}
}
}