| Overall Statistics |
|
Total Trades 0 Average Win 0% Average Loss 0% Compounding Annual Return 0% Drawdown 0% Expectancy 0 Net Profit 0% Sharpe Ratio 0 Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio 0 Tracking Error 0 Treynor Ratio 0 Total Fees $0.00 |
/*
* 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.
*/
// Clone of: CustomUniverseTriggerTimesAlgorithm
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm simply initializes the date range and cash
/// </summary>
public class CustomUniverseTriggerTimesAlgorithm : QCAlgorithm
{
/// <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()
{
SetStartDate(2016, 7, 13); //Set Start Date
SetEndDate(2016, 7, 15); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
AddSecurity(SecurityType.Equity, "SPY", Resolution.Hour);
UniverseSettings.Resolution = Resolution.Second;
AddUniverse(new PreMarketDailyUsEquityUniverse(UniverseSettings, SecurityInitializer, TimeSpan.FromMinutes(60), dateTime =>
{
Debug("Universe selection trigger time: " + dateTime);
// here's where you can do your custom selection logic, such as call a web service
return new List<string> {"AIG", "CVX", "IBM"};
}));
}
// Variable to track the last date we were in the OnData method so we
// can limit how often we fill the SMA objects
private DateTime _lastOnDataDate = DateTime.MinValue;
// Variable to keep set of SMA on a daily basis;
private Dictionary<string, SimpleMovingAverage> smaCollection = new Dictionary<string, SimpleMovingAverage>();
//
bool debug1 = false;
bool debug2 = false;
bool debug3 = false;
string debugstr = string.Empty;
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public void OnData(TradeBars data)
{
debugstr = "OnData -> ";
if( _lastOnDataDate.Date != Time.Date)
{
debugstr += "1 -> ";
// Clear our collection of SMA's ... it's a new day, start a new collection
smaCollection.Clear();
foreach (var item in data.Values.Where(x=>!x.Symbol.Equals("SPY")))
//foreach (var item in data.Values)
{
string symbol = item.Symbol;
//symbol = symbol.Substring(0,3);
debugstr += "2[" + symbol + "] -> ";
//
// Load up the SMA indicators the
//
var sma = SMA(item.Symbol, 5, Resolution.Daily);
var history = History(item.Symbol, 5, Resolution.Daily);
foreach(var bar in history)
{
sma.Update(new IndicatorDataPoint(bar.Time, bar.Close));
}
smaCollection.Add(item.Symbol, sma);
Debug("DateTime: " + Time + " - Symbol: " + item.Symbol + " - Price: " + item.Price + " - SMA(5): " + sma);
}
}
//
// Evaluate SELL
//
//
// Evaluate BUY
//
debugstr += "3 -> ";
//foreach (var item in data.Values)
foreach (var item in data.Values.Where(x=>!x.Symbol.Equals("SPY")))
{
string symbol = item.Symbol;
//symbol = symbol.Substring(0,3);
debugstr += "4[" + symbol + "] -> ";
if(Portfolio[item.Symbol].Quantity <= 0)
{
debugstr += "5 -> ";
if(item.Price > smaCollection[item.Symbol])
{
debugstr += "6[" + symbol + "] -> ";
// //We want to buy if there's money available
// decimal minCash = Portfolio.TotalPortfolioValue * .05m;
// Debug("Portfolio.Cashbook['USD'].Amount: " + Portfolio.CashBook["USD"].Amount);
// if(Portfolio.CashBook["USD"].Amount > minCash)
// {
// // We have more than 5% of portfolio in cash
// decimal cashToUse = Math.Min(((Portfolio.TotalPortfolioValue - minCash) / 10), Portfolio.CashBook["USD"].Amount);
// int shareCount = (int)Math.Floor(cashToUse / item.Price);
// Debug("MarketOrder --> Symbol: " + item.Symbol + " - Shares: " + shareCount + " - Cost: " + cashToUse);
// MarketOrder(item.Symbol, shareCount);
// }
}
}
}
Debug(debugstr);
_lastOnDataDate = Time;
//debug1 = false;
//debug2 = false;
//debug3 = false;
}
}
/// <summary>
/// Specifies a universe which fires before us-equity market open each day
/// </summary>
public class PreMarketDailyUsEquityUniverse : UserDefinedUniverse
{
private readonly TimeSpan _timeBeforeMarketOpen;
public PreMarketDailyUsEquityUniverse(UniverseSettings universeSettings, ISecurityInitializer securityInitializer, TimeSpan timeBeforeMarketOpen, Func<DateTime, IEnumerable<string>> selector)
: base(CreateConfiguration(), universeSettings, securityInitializer, TimeSpan.MaxValue, selector)
{
_timeBeforeMarketOpen = timeBeforeMarketOpen;
}
// this configuration is used internally, so we'll create a us-equity configuration
private static SubscriptionDataConfig CreateConfiguration()
{
// use us-equity market hours for 'exchange is open' logic
var marketHoursDbEntry = MarketHoursDatabase.FromDataFolder().GetEntry(QuantConnect.Market.USA, null, SecurityType.Equity);
// this is the time zone the data is in, now in our case, our unvierse doesn't have 'data'
var dataTimeZone = marketHoursDbEntry.DataTimeZone;
var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone;
var symbol = Symbol.Create("pre-market-daily-us-equity-universe", SecurityType.Equity, QuantConnect.Market.USA);
return new SubscriptionDataConfig(typeof (Tick), symbol, Resolution.Daily, dataTimeZone, exchangeTimeZone, false, false, true);
}
/// <summary>
/// This funtion is used to determine at what times to fire the selection function
/// </summary>
/// <param name="startTimeUtc">The start of the interval (first date in backtest, launch time in live)</param>
/// <param name="endTimeUtc">The end of the interval (EOD last date in backtest, <see cref="Time.EndOfTime"/> in live</param>
/// <param name="marketHoursDatabase">A market hours database instance for resolving market hours</param>
/// <returns>The date time trigger times in UTC</returns>
public override IEnumerable<DateTime> GetTriggerTimes(DateTime startTimeUtc, DateTime endTimeUtc, MarketHoursDatabase marketHoursDatabase)
{
// convert times to local
var startTimeLocal = startTimeUtc.ConvertFromUtc(TimeZones.NewYork);
var endTimeLocal = endTimeUtc.ConvertFromUtc(TimeZones.NewYork);
// get the us-equity market hours
var exchangeHours = marketHoursDatabase.GetExchangeHours(QuantConnect.Market.USA, null, SecurityType.Equity);
// loop over each tradeable date in our time frame
foreach (var tradeableDate in Time.EachTradeableDay(exchangeHours, startTimeLocal, endTimeLocal))
{
// get the market open time for this date
var marketOpen = exchangeHours.GetNextMarketOpen(tradeableDate, false);
// subtract out how much time before market open we'd like to fire
yield return marketOpen - _timeBeforeMarketOpen;
}
}
}
}