Overall Statistics
Total Trades
2
Average Win
0%
Average Loss
0%
Compounding Annual Return
3.532%
Drawdown
0.000%
Expectancy
0
Net Profit
0.076%
Sharpe Ratio
7.648
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0.023
Beta
0.005
Annual Standard Deviation
0.003
Annual Variance
0
Information Ratio
-5.055
Tracking Error
0.052
Treynor Ratio
5.168
Total Fees
$2.00
// MUD: Try moving average on % change. (sell what is in portfolio and has been over market for more than 2 weeks.)
// => And buy what is under market for more than 2 weeks
// Set to raw data for universe
// Try Dual Thrust algo on universe

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;


namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Tests different exit parameters from a list of trades entries
    /// </summary>
    public class TradeOptimization : QCAlgorithm
    {
        private SecurityChanges _changes = SecurityChanges.None;
        private readonly Dictionary<DateTime, List<string>> _backtestSymbolsPerDay = new Dictionary<DateTime, List<string>>();
        TradeBars _bars = new TradeBars();
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>


        public override void Initialize()
        {
            // this sets the resolution for data subscriptions added by our universe
            UniverseSettings.Resolution = Resolution.Daily;
            UniverseSettings.Leverage = 1m;

            // set our start and end for backtest mode
            SetStartDate(2017,10,26);
            SetEndDate(2017,11,02);
            SetBenchmark("SPY");

			// Getting List of Trades from file on Dropbox
            const string url = @"https://www.dropbox.com/s/hzcvez7zadktpwd/tradeoptimization.csv?dl=1";
            using (var client = new WebClient())
            {
                // backtest - first cache the entire file
                if (_backtestSymbolsPerDay.Count == 0)
                {
                    // fetch the file from dropbox only if we haven't cached the result already
                    var file = client.DownloadString(url);
					
                    // split the file into lines and add to our cache
                    foreach (var line in file.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                    	//All the values in the downloaded file are surrounded in quotes, the replace function strips out double quotes (") from the string.
                        var csv = line.Replace("\"","").Replace("/", "-").ToCsv();
                        Console.WriteLine("Date from csv: " + DateTime.ParseExact(csv[0], "M-d-yyyy", null));
                        Console.WriteLine("Symbol from csv: " + csv[1]);
                        DateTime date = DateTime.ParseExact(csv[0], "M-d-yyyy", CultureInfo.InvariantCulture);
                        var symbol = csv[1];
                        if (!_backtestSymbolsPerDay.ContainsKey(date)){
                        	_backtestSymbolsPerDay[date] = new List<string>();
                        }
                        _backtestSymbolsPerDay[date].Add(symbol);
                    }
                }
            }

            // define a new custom universe that will trigger each day at midnight
            AddUniverse("my-dropbox-universe", Resolution.Daily, dateTime =>
            {

                List<string> result;
	                if (_backtestSymbolsPerDay.TryGetValue(dateTime, out result))
	                {
						Console.WriteLine(Time.Date + " - Result (" + dateTime.Date +  "):" + result[0]);
						foreach (DateTime keys in _backtestSymbolsPerDay.Keys){
							Console.WriteLine("List of keys :" + keys.ToString("M-d-yyyy"));
						}
	                    return result;
	                }
                return new List<string>();
            });
            
        }

        public void OnData(TradeBars data)
        {
			Console.WriteLine(" Tradebar time: " + data.Time);

            // reset changes
            _changes = SecurityChanges.None;
        }

        // this event fires whenever we have changes to our universe
        public override void OnSecuritiesChanged(SecurityChanges changes)
        {
            _changes = changes;
			foreach (Security security in _changes.AddedSecurities)
			{
				if (security.Symbol.Value!="SPY"){
					//MarketOrder(security.Symbol, 10);
					MarketOnOpenOrder(security.Symbol, 10);
					Console.WriteLine(Time.Date + " - AddedSecurities OnData:" + security.Symbol.Value + " - Qty: 10");
				}
			}
			Console.WriteLine(Time.Date + " Security Change ");
        }


    }
}