/*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
///
/// Regression algorithm demonstrating use of map files with custom data
///
///
///
///
///
///
///
///
public class CustomDataUsingMapFileRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
private bool _initialMapping;
private bool _executionMapping;
///
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
///
public override void Initialize()
{
SetStartDate(2013, 06, 27);
SetEndDate(2013, 07, 02);
var foxa = QuantConnect.Symbol.Create("FOXA", SecurityType.Equity, Market.USA);
_symbol = AddData(foxa).Symbol;
foreach (var config in SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_symbol))
{
if (config.Resolution != Resolution.Minute)
{
throw new RegressionTestException("Expected resolution to be set to Minute");
}
}
}
///
/// Checks to see if the stock has been renamed, and places an order once the symbol has changed
///
public override void OnData(Slice slice)
{
if (slice.SymbolChangedEvents.ContainsKey(_symbol))
{
var mappingEvent = slice.SymbolChangedEvents.Single(x => x.Key.SecurityType == SecurityType.Base).Value;
Log($"{Time} - Ticker changed from: {mappingEvent.OldSymbol} to {mappingEvent.NewSymbol}");
if (Time.Date == new DateTime(2013, 06, 27))
{
// we should Not receive the initial mapping event
if (mappingEvent.NewSymbol != "NWSA"
|| mappingEvent.OldSymbol != "FOXA")
{
throw new RegressionTestException($"Unexpected mapping event {mappingEvent}");
}
_initialMapping = true;
}
else if (Time.Date == new DateTime(2013, 06, 29))
{
if (mappingEvent.NewSymbol != "FOXA"
|| mappingEvent.OldSymbol != "NWSA")
{
throw new RegressionTestException($"Unexpected mapping event {mappingEvent}");
}
_executionMapping = true;
SetHoldings(_symbol, 1);
}
}
}
///
/// Final step of the algorithm
///
public override void OnEndOfAlgorithm()
{
if (_initialMapping)
{
throw new RegressionTestException("The ticker generated the initial rename event");
}
if (!_executionMapping)
{
throw new RegressionTestException("The ticker did not rename throughout the course of its life even though it should have");
}
}
///
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
///
public bool CanRunLocally { get; } = true;
///
/// This is used by the regression test system to indicate which languages this algorithm is written in.
///
public List Languages { get; } = new() { Language.CSharp, Language.Python };
///
/// Data Points count of all timeslices of algorithm
///
public long DataPoints => 1667;
///
/// Data Points count of the algorithm history
///
public int AlgorithmHistoryDataPoints => 0;
///
/// Final status of the algorithm
///
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
///
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
///
public Dictionary ExpectedStatistics => new Dictionary
{
{"Total Orders", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "12.433%"},
{"Drawdown", "2.600%"},
{"Expectancy", "0"},
{"Start Equity", "100000"},
{"End Equity", "100183.6"},
{"Net Profit", "0.184%"},
{"Sharpe Ratio", "0.516"},
{"Sortino Ratio", "0"},
{"Probabilistic Sharpe Ratio", "47.412%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.101"},
{"Beta", "1.58"},
{"Annual Standard Deviation", "0.211"},
{"Annual Variance", "0.045"},
{"Information Ratio", "0.627"},
{"Tracking Error", "0.166"},
{"Treynor Ratio", "0.069"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$29000.00"},
{"Lowest Capacity Asset", "NWSA.CustomDataUsingMapping T3MO1488O0H0"},
{"Portfolio Turnover", "14.58%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "f5ad14d0317a5cbb81984dd92969423c"}
};
///
/// Test example custom data showing how to enable the use of mapping.
/// Implemented as a wrapper of existing NWSA->FOXA equity
///
private class CustomDataUsingMapping : TradeBar
{
///
/// Indicates if there is support for mapping
///
/// True indicates mapping should be done
public override bool RequiresMapping()
{
return true;
}
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
return base.GetSource(new SubscriptionDataConfig(config,
typeof(CustomDataUsingMapping),
// create a new symbol as equity so we find the existing data files
Symbol.Create(config.MappedSymbol, SecurityType.Equity, config.Market)),
date,
isLiveMode);
}
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
return ParseEquity(config, line, date);
}
///
/// Gets the default resolution for this data and security type
///
/// This is a method and not a property so that python
/// custom data types can override it
public override Resolution DefaultResolution()
{
return Resolution.Minute;
}
///
/// Gets the supported resolution for this data and security type
///
/// This is a method and not a property so that python
/// custom data types can override it
public override List SupportedResolutions()
{
return new List { Resolution.Minute };
}
}
}
}