Overall Statistics
Total Trades
1
Average Win
60.64%
Average Loss
0.00%
Annual Return
4.178%
Drawdown
26.300%
Expectancy
0.000
Net Profit
60.552%
Sharpe Ratio
0.5
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Trade Frequency
Weekly trades
///<summary>
/// QCU - S&P 500 Dollar Averaging Over Time.
/// Typical, simple investment strategy - invest a fixed amount each month regardless of market conditions.
/// How would this have performed over the last few years?
///</summary>
using System;
using System.Collections;
using System.Collections.Generic; 

namespace QuantConnect 
{
    using QuantConnect.Securities;
    using QuantConnect.Models; 

    // Dollar Cost Averaging Algorithm
    // Buy a little amount of SPY at regular time intervals.
    public class QCUDollarCostAverage : QCAlgorithm, IAlgorithm 
    { 
        private string symbol = "SPY";
        private DateTime startDate = new DateTime(2004, 03, 01);
        private DateTime endDate = new DateTime(2014, 03, 01);
        private decimal monthlyDollarValue = 1000;
        private DateTime nextTradeDate = DateTime.MinValue;
        
        //Initialize the Code
        public override void Initialize()
        {  
            //Dynamic start and end dates configured above.
            SetStartDate(startDate);
            SetEndDate(endDate);
            
            //Set the cash as a function of the number of months we're investing
            decimal investments = Convert.ToDecimal((endDate - startDate).TotalDays / 30);
            SetCash(investments * monthlyDollarValue);
            
            SetRunMode(RunMode.Series);
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute, true, false);
        }
        
        //Handle the Data Event:
        public override void OnTradeBar(Dictionary<string, TradeBar> data) 
        {       
            //Its good practise to wrap our code in "Try-Catch" to handle errors:
            try 
            {
                decimal price = data[symbol].Price;
                DateTime today = data[symbol].Time;
                int quantity = (int)(monthlyDollarValue / price);
                
                //Check we've past the required date of our next investment
                if (today.Date >= nextTradeDate.Date && Time.Hour >= 12)
                {   
                    //Now place the order to purchase more SPY stock.
                    Order(symbol, quantity); //symbol, quantity
                    
                    // Set the next date we'll place an order:
                    nextTradeDate = today.AddMonths(1);
                }
                return;   
            }
            catch (Exception err) 
            {
                //Errors will be logged to the console
                Error("Error in Data Event:" + err.Message);
            }
        }
    }
}