Esempio n. 1
0
        static IList <IOptionDefinition> ResolveFlagOptionLabels(
            ICommandDefinition selectedCommand,
            string argument)
        {
            if (OptionSymbol.CanBeFullForm(argument))
            {
                return(selectedCommand.GetRegisteredOptions()
                       .Where(o => o.Type == OptionType.Flag && o.IsMatch(argument))
                       .ToArray());
            }

            if (OptionSymbol.CanBeAbbreviationForm(argument))
            {
                string[] flagArguments = SplitAbbrArgument(argument);
                if (flagArguments.HasDuplication(StringComparer.OrdinalIgnoreCase))
                {
                    throw new ArgParsingException(ArgsParsingErrorCode.DuplicateFlagsInArgs, argument);
                }

                IOptionDefinition[] resolvedDefinitions = selectedCommand.GetRegisteredOptions()
                                                          .Where(o => o.Type == OptionType.Flag && flagArguments.Any(o.IsMatch))
                                                          .ToArray();

                return(resolvedDefinitions.Length != flagArguments.Length
                    ? Array.Empty <IOptionDefinition>()
                    : resolvedDefinitions);
            }

            return(Array.Empty <IOptionDefinition>());
        }
        /// <summary>
        /// Check for delistings and emit them into the aux data queue
        /// </summary>
        private void CheckForDelisting(DateTime date)
        {
            DateTime delistingDate;

            switch (_config.Symbol.ID.SecurityType)
            {
            case SecurityType.Future:
                delistingDate = _config.Symbol.ID.Date;
                break;

            case SecurityType.Option:
                delistingDate = OptionSymbol.GetLastDayOfTrading(_config.Symbol);
                break;

            default:
                delistingDate = _mapFile.DelistingDate;
                break;
            }

            if (!_delistedWarning && date >= delistingDate)
            {
                _delistedWarning = true;
                var price = _previous != null ? _previous.Price : 0;
                _auxiliaryData.Enqueue(new Delisting(_config.Symbol, date, price, DelistingType.Warning));
            }
            else if (!_delisted && date > delistingDate)
            {
                _delisted = true;
                var price = _previous != null ? _previous.Price : 0;
                // delisted at EOD
                _auxiliaryData.Enqueue(new Delisting(_config.Symbol, delistingDate.AddDays(1), price, DelistingType.Delisted));
            }
        }
Esempio n. 3
0
        public void TestIfFridayLastTradingDayIsHolidaysThenMoveToPreviousThursday()
        {
            var saturdayAfterGoodFriday  = new DateTime(2014, 04, 19);
            var thursdayBeforeGoodFriday = saturdayAfterGoodFriday.AddDays(-2);
            var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, saturdayAfterGoodFriday);

            Assert.AreEqual(thursdayBeforeGoodFriday, OptionSymbol.GetLastDayOfTrading(symbol));
        }
        //
        //         Get ATM call and put
        //
        public virtual void get_contracts(Slice slice)
        {
            LogCust("called get contracts");
            foreach (var kvp in slice.OptionChains)
            {
                if (kvp.Key != this.option_symbol)
                {
                    continue;
                }
                var chain      = kvp.Value;
                var spot_price = chain.Underlying.Price;
                //   self.Log("spot_price {}" .format(spot_price))
                // prefer to do in steps, rather than a nested sorted
                // 1. get furthest expiry
                var contracts_by_T = chain.OrderByDescending(x => x.Expiry).ToList();
                if (!(contracts_by_T.Count > 0))
                {
                    return;
                }
                this.expiry = contracts_by_T[0].Expiry.Date;

                var weeklySymbol = QuantConnect.Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, this.expiry);
                //var monthlysymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 17));

                //Assert.True(OptionSymbol.IsWeekly(weeklySymbol));
                //Assert.False(OptionSymbol.IsWeekly(monthlysymbol));

                //Assert.AreEqual(new DateTime(2020, 04, 17)/*Friday*/, OptionSymbol.GetLastDayOfTrading(monthlysymbol));
                //Good Friday on 10th so should be 9th
                //Assert.AreEqual(new DateTime(2020, 04, 09)/*Thursday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));


                //this.last_trading_day = last_trading_day(this.expiry);
                this.last_trading_day = OptionSymbol.GetLastDayOfTrading(weeklySymbol);
                // get contracts with further expiry and sort them by strike
                var slice_T = (from i in chain
                               where i.Expiry.Date == this.expiry
                               select i).ToList();
                var sorted_contracts = slice_T.OrderBy(x => x.Strike).ToList();
                //   self.Log("Expiry used: {} and shortest {}" .format(self.expiry, contracts_by_T[-1].Expiry.date()) )
                // 2a. get the ATM closest CALL to short
                var calls = (from i in sorted_contracts
                             where i.Right == OptionRight.Call && i.Strike >= spot_price
                             select i).ToList();
                //this.call = calls ? calls[0] : null;
                this.call = calls.Count > 0 ? calls.First() : null;
                //   self.Log("delta call {}, self.call type {}" .format(self.call.Greeks.Delta, type(self.call)))
                //   self.Log("implied vol {} " .format(self.call.ImpliedVolatility))
                // 2b. get the ATM closest put to short
                var puts = (from i in sorted_contracts
                            where i.Right == OptionRight.Put && i.Strike <= spot_price
                            select i).ToList();
                this.put = puts.Count > 0 ? puts.Last() : null;
                //if (put == null) this.Quit("put == null");
            }
        }
Esempio n. 5
0
        public void RegisterOption(string fullForm, char?abbrForm, string description)
        {
            var symbol = new OptionSymbol(fullForm, abbrForm);

            if (Options.Any(e => e.SymbolMetadata.Equals(symbol)))
            {
                throw new ArgumentException("Duplicate option.");
            }

            Options.Add(new FlagOptionDefinition(symbol, description));
        }
Esempio n. 6
0
        public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsAfterFeb2015()
        {
            var symbol       = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 19));
            var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 05));

            Assert.True(OptionSymbol.IsStandardContract(symbol));
            Assert.False(OptionSymbol.IsStandardContract(weeklySymbol));

            Assert.AreEqual(new DateTime(2016, 02, 19) /*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol));
            Assert.AreEqual(new DateTime(2016, 02, 05) /*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
        }
Esempio n. 7
0
        public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsBeforeFeb2015()
        {
            var symbol       = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 22));
            var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 07));

            Assert.True(OptionSymbol.IsStandard(symbol));
            Assert.False(OptionSymbol.IsStandard(weeklySymbol));

            Assert.AreEqual(new DateTime(2012, 09, 21) /*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol));
            Assert.AreEqual(new DateTime(2012, 09, 07) /*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
        }
Esempio n. 8
0
        static IOptionDefinition ResolveKeyValueOptionLabel(
            ICommandDefinition selectedCommand,
            string argument)
        {
            if (!OptionSymbol.CanBeFullForm(argument) && !OptionSymbol.CanBeAbbreviationSingleForm(argument))
            {
                return(null);
            }

            return(selectedCommand.GetRegisteredOptions()
                   .FirstOrDefault(o => o.Type == OptionType.KeyValue && o.IsMatch(argument)));
        }
Esempio n. 9
0
        public void IsOptionContractExpiredReturnsFalseIfActiveContract()
        {
            var symbol = Symbol.CreateOption(
                "BHP",
                Market.USA,
                OptionStyle.American,
                OptionRight.Call,
                55m,
                new DateTime(2019, 9, 20));

            Assert.IsFalse(OptionSymbol.IsOptionContractExpired(symbol, new DateTime(2019, 1, 1)));
        }
Esempio n. 10
0
        public void IsOptionContractExpiredReturnsFalseIfTimeOfDayDiffer()
        {
            var symbol = Symbol.CreateOption(
                "BHP",
                Market.USA,
                OptionStyle.American,
                OptionRight.Call,
                55m,
                new DateTime(2022, 03, 11));

            Assert.IsFalse(OptionSymbol.IsOptionContractExpired(symbol, new DateTime(2022, 03, 11)));
        }
Esempio n. 11
0
        public void TestIfWeDetectCorrectlyWeeklies()
        {
            var weeklySymbol  = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 10));
            var monthlysymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 17));

            Assert.True(OptionSymbol.IsWeekly(weeklySymbol));
            Assert.False(OptionSymbol.IsWeekly(monthlysymbol));

            Assert.AreEqual(new DateTime(2020, 04, 17) /*Friday*/, OptionSymbol.GetLastDayOfTrading(monthlysymbol));
            //Good Friday on 10th so should be 9th
            Assert.AreEqual(new DateTime(2020, 04, 09) /*Thursday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol));
        }
Esempio n. 12
0
        public void IsOptionContractExpiredReturnsTrueIfExpiredContract()
        {
            var symbol = Symbol.CreateOption(
                "BHP",
                Market.USA,
                OptionStyle.American,
                OptionRight.Call,
                55m,
                new DateTime(2019, 9, 20));

            Assert.IsTrue(OptionSymbol.IsOptionContractExpired(symbol, DateTime.UtcNow));
        }
Esempio n. 13
0
        /// <summary>
        /// Determine if the given Option contract symbol is standard
        /// </summary>
        /// <returns>True if standard</returns>
        protected override bool IsStandard(Symbol symbol)
        {
            switch (symbol.SecurityType)
            {
            case SecurityType.FutureOption:
                return(FutureOptionSymbol.IsStandard(symbol));

            case SecurityType.IndexOption:
                return(IndexOptionSymbol.IsStandard(symbol));

            default:
                return(OptionSymbol.IsStandard(symbol));
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Returns universe, filtered by option type
        /// </summary>
        /// <returns></returns>
        internal OptionFilterUniverse ApplyOptionTypesFilter()
        {
            // memoization map for ApplyOptionTypesFilter()
            var memoizedMap = new Dictionary <DateTime, bool>();

            Func <Symbol, bool> memoizedIsStandardType = symbol =>
            {
                var dt = symbol.ID.Date;

                bool result;
                if (memoizedMap.TryGetValue(dt, out result))
                {
                    return(result);
                }
                var res = OptionSymbol.IsStandard(symbol);
                memoizedMap[dt] = res;

                return(res);
            };

            _allSymbols = _allSymbols.Where(x =>
            {
                switch (_type)
                {
                case Type.Weeklys:
                    return(!memoizedIsStandardType(x));

                case Type.Standard:
                    return(memoizedIsStandardType(x));

                case Type.Standard | Type.Weeklys:
                    return(true);

                default:
                    return(false);
                }
            }).ToList();

            return(this);
        }
        /// <summary>
        /// Returns universe, filtered by option type
        /// </summary>
        /// <returns></returns>
        internal OptionFilterUniverse ApplyOptionTypesFilter()
        {
            // memoization map for ApplyOptionTypesFilter()
            var memoizedMap = new Dictionary <DateTime, bool>();

            Func <Symbol, bool> memoizedIsStandardType = symbol =>
            {
                var dt = symbol.ID.Date;

                if (memoizedMap.ContainsKey(dt))
                {
                    return(memoizedMap[dt]);
                }
                var res = OptionSymbol.IsStandardContract(symbol);
                memoizedMap[dt] = res;

                return(res);
            };

            var filtered = _allSymbols.Where(x =>
            {
                switch (_type)
                {
                case Type.Weeklys:
                    return(!memoizedIsStandardType(x));

                case Type.Standard:
                    return(memoizedIsStandardType(x));

                case Type.Standard | Type.Weeklys:
                    return(true);

                default:
                    return(false);
                }
            });

            _allSymbols = filtered.ToList();
            return(this);
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes this instance
        /// </summary>
        /// <param name="config">The <see cref="SubscriptionDataConfig"/></param>
        /// <param name="factorFile">The factor file to use</param>
        /// <param name="mapFile">The <see cref="MapFile"/> to use</param>
        public void Initialize(
            SubscriptionDataConfig config,
            FactorFile factorFile,
            MapFile mapFile)
        {
            _config = config;
            // Estimate delisting date.
            switch (config.Symbol.ID.SecurityType)
            {
            case SecurityType.Future:
                _delistingDate = config.Symbol.ID.Date;
                break;

            case SecurityType.Option:
                _delistingDate = OptionSymbol.GetLastDayOfTrading(
                    config.Symbol);
                break;

            default:
                _delistingDate = mapFile.DelistingDate;
                break;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Get flag value.
        /// </summary>
        /// <param name="arg">
        /// The full form or abbreviation form flag name.
        /// </param>
        /// <returns>
        /// If the flag is specified, return true, otherwise false.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The flag argument is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// The flag argument is invalid or undefined.
        /// </exception>
        public bool GetFlagValue(string arg)
        {
            if (!IsSuccess)
            {
                throw new InvalidOperationException();
            }

            try
            {
                var symbol = new OptionSymbol(arg);
                var option = definition.Flags.FirstOrDefault(c => c.Option.SymbolMetadata.Equals(symbol));

                if (option == null)
                {
                    throw new ParsingException(ArgsParsingErrorCode.FreeValueNotSupported, arg);
                }

                return(option.Value);
            }
            catch (ParsingException e)
            {
                throw new ArgumentException(e.Message);
            }
        }
Esempio n. 18
0
 public void IsOptionContractExpiredReturnsFalseForNonOptionSymbol()
 {
     Assert.IsFalse(OptionSymbol.IsOptionContractExpired(Symbols.SPY, DateTime.UtcNow));
 }
 /// <summary>
 /// Determine if the given Option contract symbol is standard
 /// </summary>
 /// <returns>True if standard</returns>
 protected override bool IsStandard(Symbol symbol)
 {
     return(symbol.SecurityType == SecurityType.FutureOption
         ? FutureOptionSymbol.IsStandard(symbol)
         : OptionSymbol.IsStandard(symbol));
 }
Esempio n. 20
0
        /// <summary>
        /// Initializes the <see cref="SubscriptionDataReader"/> instance
        /// </summary>
        /// <remarks>Should be called after all consumers of <see cref="NewTradableDate"/> event are set,
        /// since it will produce events.</remarks>
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            //Save the type of data we'll be getting from the source.
            try
            {
                _dataFactory = _config.Type.GetBaseDataInstance();
            }
            catch (ArgumentException exception)
            {
                OnInvalidConfigurationDetected(new InvalidConfigurationDetectedEventArgs(exception.Message));
                _endOfStream = true;
                return;
            }

            //If its quandl set the access token in data factory:
            var quandl = _dataFactory as Quandl;

            if (quandl != null)
            {
                if (!Quandl.IsAuthCodeSet)
                {
                    Quandl.SetAuthCode(Config.Get("quandl-auth-token"));
                }
            }

            // If Tiingo data, set the access token in data factory
            var tiingo = _dataFactory as TiingoDailyData;

            if (tiingo != null)
            {
                if (!Tiingo.IsAuthCodeSet)
                {
                    Tiingo.SetAuthCode(Config.Get("tiingo-auth-token"));
                }
            }

            // If USEnergyInformation data, set the access token in data factory
            var energyInformation = _dataFactory as USEnergyInformation;

            if (energyInformation != null)
            {
                if (!USEnergyInformation.IsAuthCodeSet)
                {
                    USEnergyInformation.SetAuthCode(Config.Get("us-energy-information-auth-token"));
                }
            }

            _factorFile = new FactorFile(_config.Symbol.Value, new List <FactorFileRow>());
            _mapFile    = new MapFile(_config.Symbol.Value, new List <MapFileRow>());

            // load up the map files for equities, options, and custom data if it supports it.
            // Only load up factor files for equities
            if (_config.TickerShouldBeMapped())
            {
                try
                {
                    var mapFile = _mapFileResolver.ResolveMapFile(_config.Symbol, _config.Type);

                    // only take the resolved map file if it has data, otherwise we'll use the empty one we defined above
                    if (mapFile.Any())
                    {
                        _mapFile = mapFile;
                    }

                    if (!_config.IsCustomData && _config.SecurityType != SecurityType.Option)
                    {
                        var factorFile = _factorFileProvider.Get(_config.Symbol);
                        _hasScaleFactors = factorFile != null;
                        if (_hasScaleFactors)
                        {
                            _factorFile = factorFile;

                            // if factor file has minimum date, update start period if before minimum date
                            if (!_isLiveMode && _factorFile != null && _factorFile.FactorFileMinimumDate.HasValue)
                            {
                                if (_periodStart < _factorFile.FactorFileMinimumDate.Value)
                                {
                                    _periodStart = _factorFile.FactorFileMinimumDate.Value;

                                    OnNumericalPrecisionLimited(
                                        new NumericalPrecisionLimitedEventArgs(
                                            $"Data for symbol {_config.Symbol.Value} has been limited due to numerical precision issues in the factor file. " +
                                            $"The starting date has been set to {_factorFile.FactorFileMinimumDate.Value.ToShortDateString()}."));
                                }
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Fetching Price/Map Factors: " + _config.Symbol.ID + ": ");
                }
            }

            // Estimate delisting date.
            switch (_config.Symbol.ID.SecurityType)
            {
            case SecurityType.Future:
                _delistingDate = _config.Symbol.ID.Date;
                break;

            case SecurityType.Option:
                _delistingDate = OptionSymbol.GetLastDayOfTrading(_config.Symbol);
                break;

            default:
                _delistingDate = _mapFile.DelistingDate;
                break;
            }
            // adding a day so we stop at EOD
            _delistingDate = _delistingDate.AddDays(1);

            _subscriptionFactoryEnumerator = ResolveDataEnumerator(true);

            _initialized = true;
        }
Esempio n. 21
0
 /// <summary>
 /// Determine if the given Option contract symbol is standard
 /// </summary>
 /// <returns>True if standard</returns>
 protected override bool IsStandard(Symbol symbol)
 {
     return(OptionSymbol.IsStandard(symbol));
 }
Esempio n. 22
0
        /// <summary>
        /// Subscription data reader takes a subscription request, loads the type, accepts the data source and enumerate on the results.
        /// </summary>
        /// <param name="config">Subscription configuration object</param>
        /// <param name="periodStart">Start date for the data request/backtest</param>
        /// <param name="periodFinish">Finish date for the data request/backtest</param>
        /// <param name="resultHandler">Result handler used to push error messages and perform sampling on skipped days</param>
        /// <param name="mapFileResolver">Used for resolving the correct map files</param>
        /// <param name="factorFileProvider">Used for getting factor files</param>
        /// <param name="dataProvider">Used for getting files not present on disk</param>
        /// <param name="dataCacheProvider">Used for caching files</param>
        /// <param name="tradeableDates">Defines the dates for which we'll request data, in order, in the security's exchange time zone</param>
        /// <param name="isLiveMode">True if we're in live mode, false otherwise</param>
        /// <param name="includeAuxilliaryData">True if we want to emit aux data, false to only emit price data</param>
        public SubscriptionDataReader(SubscriptionDataConfig config,
                                      DateTime periodStart,
                                      DateTime periodFinish,
                                      IResultHandler resultHandler,
                                      MapFileResolver mapFileResolver,
                                      IFactorFileProvider factorFileProvider,
                                      IDataProvider dataProvider,
                                      IEnumerable <DateTime> tradeableDates,
                                      bool isLiveMode,
                                      IDataCacheProvider dataCacheProvider,
                                      bool includeAuxilliaryData = true)
        {
            //Save configuration of data-subscription:
            _config = config;

            _auxiliaryData = new Queue <BaseData>();

            //Save Start and End Dates:
            _periodStart       = periodStart;
            _periodFinish      = periodFinish;
            _dataProvider      = dataProvider;
            _dataCacheProvider = dataCacheProvider;

            //Save access to securities
            _isLiveMode            = isLiveMode;
            _includeAuxilliaryData = includeAuxilliaryData;

            //Save the type of data we'll be getting from the source.

            //Create the dynamic type-activators:
            var objectActivator = ObjectActivator.GetActivator(config.Type);

            _resultHandler  = resultHandler;
            _tradeableDates = tradeableDates.GetEnumerator();
            if (objectActivator == null)
            {
                _resultHandler.ErrorMessage("Custom data type '" + config.Type.Name + "' missing parameterless constructor E.g. public " + config.Type.Name + "() { }");
                _endOfStream = true;
                return;
            }

            //Create an instance of the "Type":
            var userObj = objectActivator.Invoke(new object[] { config.Type });

            _dataFactory = userObj as BaseData;

            //If its quandl set the access token in data factory:
            var quandl = _dataFactory as Quandl;

            if (quandl != null)
            {
                if (!Quandl.IsAuthCodeSet)
                {
                    Quandl.SetAuthCode(Config.Get("quandl-auth-token"));
                }
            }

            // If Tiingo data, set the access token in data factory
            var tiingo = _dataFactory as TiingoDailyData;

            if (tiingo != null)
            {
                if (!Tiingo.IsAuthCodeSet)
                {
                    Tiingo.SetAuthCode(Config.Get("tiingo-auth-token"));
                }
            }

            _factorFile = new FactorFile(config.Symbol.Value, new List <FactorFileRow>());
            _mapFile    = new MapFile(config.Symbol.Value, new List <MapFileRow>());

            // load up the map and factor files for equities
            if (!config.IsCustomData && config.SecurityType == SecurityType.Equity)
            {
                try
                {
                    var mapFile = mapFileResolver.ResolveMapFile(config.Symbol.ID.Symbol, config.Symbol.ID.Date);

                    // only take the resolved map file if it has data, otherwise we'll use the empty one we defined above
                    if (mapFile.Any())
                    {
                        _mapFile = mapFile;
                    }

                    var factorFile = factorFileProvider.Get(_config.Symbol);
                    _hasScaleFactors = factorFile != null;
                    if (_hasScaleFactors)
                    {
                        _factorFile = factorFile;

                        // if factor file has minimum date, update start period if before minimum date
                        if (!_isLiveMode && _factorFile != null && _factorFile.FactorFileMinimumDate.HasValue)
                        {
                            if (_periodStart < _factorFile.FactorFileMinimumDate.Value)
                            {
                                _periodStart = _factorFile.FactorFileMinimumDate.Value;

                                _resultHandler.DebugMessage(
                                    string.Format("Data for symbol {0} has been limited due to numerical precision issues in the factor file. The starting date has been set to {1}.",
                                                  config.Symbol.Value,
                                                  _factorFile.FactorFileMinimumDate.Value.ToShortDateString()));
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Fetching Price/Map Factors: " + config.Symbol.ID + ": ");
                }
            }

            // load up the map and factor files for underlying of equity option
            if (!config.IsCustomData && config.SecurityType == SecurityType.Option)
            {
                try
                {
                    var mapFile = mapFileResolver.ResolveMapFile(config.Symbol.Underlying.ID.Symbol, config.Symbol.Underlying.ID.Date);

                    // only take the resolved map file if it has data, otherwise we'll use the empty one we defined above
                    if (mapFile.Any())
                    {
                        _mapFile = mapFile;
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Map Factors: " + config.Symbol.ID + ": ");
                }
            }

            // Estimate delisting date.
            switch (_config.Symbol.ID.SecurityType)
            {
            case SecurityType.Future:
                _delistingDate = _config.Symbol.ID.Date;
                break;

            case SecurityType.Option:
                _delistingDate = OptionSymbol.GetLastDayOfTrading(_config.Symbol);
                break;

            default:
                _delistingDate = _mapFile.DelistingDate;
                break;
            }
            _subscriptionFactoryEnumerator = ResolveDataEnumerator(true);
        }
Esempio n. 23
0
        /// <summary>
        /// Initializes the <see cref="SubscriptionDataReader"/> instance
        /// </summary>
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            //Save the type of data we'll be getting from the source.

            //Create the dynamic type-activators:
            var objectActivator = ObjectActivator.GetActivator(_config.Type);

            if (objectActivator == null)
            {
                OnInvalidConfigurationDetected(
                    new InvalidConfigurationDetectedEventArgs(
                        $"Custom data type \'{_config.Type.Name}\' missing parameterless constructor " +
                        $"E.g. public {_config.Type.Name}() {{ }}"));

                _endOfStream = true;
                return;
            }

            //Create an instance of the "Type":
            var userObj = objectActivator.Invoke(new object[] { _config.Type });

            _dataFactory = userObj as BaseData;

            //If its quandl set the access token in data factory:
            var quandl = _dataFactory as Quandl;

            if (quandl != null)
            {
                if (!Quandl.IsAuthCodeSet)
                {
                    Quandl.SetAuthCode(Config.Get("quandl-auth-token"));
                }
            }

            // If Tiingo data, set the access token in data factory
            var tiingo = _dataFactory as TiingoDailyData;

            if (tiingo != null)
            {
                if (!Tiingo.IsAuthCodeSet)
                {
                    Tiingo.SetAuthCode(Config.Get("tiingo-auth-token"));
                }
            }

            _factorFile = new FactorFile(_config.Symbol.Value, new List <FactorFileRow>());
            _mapFile    = new MapFile(_config.Symbol.Value, new List <MapFileRow>());

            // load up the map and factor files for equities
            if (!_config.IsCustomData && _config.SecurityType == SecurityType.Equity)
            {
                try
                {
                    var mapFile = _mapFileResolver.ResolveMapFile(_config.Symbol.ID.Symbol, _config.Symbol.ID.Date);

                    // only take the resolved map file if it has data, otherwise we'll use the empty one we defined above
                    if (mapFile.Any())
                    {
                        _mapFile = mapFile;
                    }

                    var factorFile = _factorFileProvider.Get(_config.Symbol);
                    _hasScaleFactors = factorFile != null;
                    if (_hasScaleFactors)
                    {
                        _factorFile = factorFile;

                        // if factor file has minimum date, update start period if before minimum date
                        if (!_isLiveMode && _factorFile != null && _factorFile.FactorFileMinimumDate.HasValue)
                        {
                            if (_periodStart < _factorFile.FactorFileMinimumDate.Value)
                            {
                                _periodStart = _factorFile.FactorFileMinimumDate.Value;

                                OnNumericalPrecisionLimited(
                                    new NumericalPrecisionLimitedEventArgs(
                                        $"Data for symbol {_config.Symbol.Value} has been limited due to numerical precision issues in the factor file. " +
                                        $"The starting date has been set to {_factorFile.FactorFileMinimumDate.Value.ToShortDateString()}."));
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Fetching Price/Map Factors: " + _config.Symbol.ID + ": ");
                }
            }

            // load up the map and factor files for underlying of equity option
            if (!_config.IsCustomData && _config.SecurityType == SecurityType.Option)
            {
                try
                {
                    var mapFile = _mapFileResolver.ResolveMapFile(_config.Symbol.Underlying.ID.Symbol, _config.Symbol.Underlying.ID.Date);

                    // only take the resolved map file if it has data, otherwise we'll use the empty one we defined above
                    if (mapFile.Any())
                    {
                        _mapFile = mapFile;
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err, "Map Factors: " + _config.Symbol.ID + ": ");
                }
            }

            // Estimate delisting date.
            switch (_config.Symbol.ID.SecurityType)
            {
            case SecurityType.Future:
                _delistingDate = _config.Symbol.ID.Date;
                break;

            case SecurityType.Option:
                _delistingDate = OptionSymbol.GetLastDayOfTrading(_config.Symbol);
                break;

            default:
                _delistingDate = _mapFile.DelistingDate;
                break;
            }

            _subscriptionFactoryEnumerator = ResolveDataEnumerator(true);

            _initialized = true;
        }