Exemplo n.º 1
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            //mylog.Debug(transheader);
            mylog.Debug(ondataheader);

            //Initialize dates
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 07);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

            maxHigh = new Maximum("MaxHigh", _period);
            minLow = new Minimum("MinLow", _period);
            value1 = new RollingWindow<IndicatorDataPoint>(_period);
            fish = new RollingWindow<IndicatorDataPoint>(_period);
            //wma = new LinearWeightedMovingAverage(5);       // induces 2 bar lag
            //wwma = new RollingWindow<IndicatorDataPoint>(_period);
            //fishHigh = new Maximum("FishHigh", 400);
            //fishLow = new Minimum("FishLow", 400);
            fx = new FisherTransform(_symbol,_period);
            //fx = FT(_symbol, _period, Resolution.Minute);

            // Add a bars to initialize the RollingWindow
            value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m));
            fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m));
            //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
        }
Exemplo n.º 2
0
        public void ComputesCorrectly()
        {
            var max = new Maximum(3);

            var reference = DateTime.MinValue;

            max.Update(reference.AddDays(1), 1m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(0, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(2), -1m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(1, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(3), 0m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(2, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(4), -2m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(3, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(5), -2m);
            Assert.AreEqual(0m, max.Current.Value);
            Assert.AreEqual(2, max.PeriodsSinceMaximum);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MidPrice"/> class using the specified name and period.
 /// </summary> 
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The period of the MIDPRICE</param>
 public MidPrice(string name, int period) 
     : base(name)
 {
     _period = period;
     _maximum = new Maximum(period);
     _minimum = new Minimum(period);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a new Stochastics Indicator from the specified periods.
        /// </summary>
        /// <param name="name">The name of this indicator.</param>
        /// <param name="period">The period given to calculate the Fast %K</param>
        /// <param name="kPeriod">The K period given to calculated the Slow %K</param>
        /// <param name="dPeriod">The D period given to calculated the Slow %D</param>
        public Stochastic(string name, int period, int kPeriod, int dPeriod)
            : base(name)
        {
            Maximum = new Maximum(name + "_Max", period);
            Mininum = new Minimum(name + "_Min", period);
            SumFastK = new Sum(name + "_SumFastK", kPeriod);
            SumSlowK = new Sum(name + "_SumD", dPeriod);

            FastStoch = new FunctionalIndicator<TradeBar>(name + "_FastStoch",
                input => ComputeFastStoch(period, input),
                fastStoch => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochK = new FunctionalIndicator<TradeBar>(name + "_StochK",
                input => ComputeStochK(period, kPeriod, input),
                stochK => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochD = new FunctionalIndicator<TradeBar>(name + "_StochD",
                input => ComputeStochD(period, kPeriod, dPeriod),
                stochD => Maximum.IsReady,
                () => Maximum.Reset()
                );
        }
Exemplo n.º 5
0
        public void ComputesCorrectly2()
        {
            const int period = 5;
            var max = new Maximum(period);

            Assert.AreEqual(0m, max.Current.Value);

            // test an increasing stream of data
            for (int i = 0; i < period; i++)
            {
                max.Update(DateTime.Now.AddDays(1), i);
                Assert.AreEqual(i, max.Current.Value);
                Assert.AreEqual(0, max.PeriodsSinceMaximum);
            }

            // test a decreasing stream of data
            for (int i = 0; i <= period; i++)
            {
                max.Update(DateTime.Now.AddDays(period + i), period - i - 1);
                Assert.AreEqual(period - 1, max.Current.Value);
                Assert.AreEqual(i, max.PeriodsSinceMaximum);
            }

            Assert.AreEqual(max.Period, max.PeriodsSinceMaximum);
        }
Exemplo n.º 6
0
        /// <summary>
        /// A Fisher Transform of Prices
        /// </summary>
        /// <param name="name">string - the name of the indicator</param>
        /// <param name="period">The number of periods for the indicator</param>
        public FisherTransform(string name, int period)
            : base(name)
        {
            _alpha = .33;

            // Initialize the local variables
            _medianMax = new Maximum("MedianMax", period);
            _medianMin = new Minimum("MedianMin", period);
        }
Exemplo n.º 7
0
        public void ResetsProperly()
        {
            var max = new Maximum(3);
            max.Update(DateTime.Today, 1m);
            max.Update(DateTime.Today.AddSeconds(1), 2m);
            max.Update(DateTime.Today.AddSeconds(2), 1m);
            Assert.IsTrue(max.IsReady);

            max.Reset();
            Assert.AreEqual(0, max.PeriodsSinceMaximum);
            TestHelper.AssertIndicatorIsInDefaultState(max);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a new AroonOscillator from the specified up/down periods.
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="upPeriod">The lookback period to determine the highest high for the AroonDown</param>
        /// <param name="downPeriod">The lookback period to determine the lowest low for the AroonUp</param>
        public AroonOscillator(string name, int upPeriod, int downPeriod)
            : base(name)
        {
            var max = new Maximum(name + "_Max", upPeriod);
            AroonUp = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonUp",
                input => ComputeAroonUp(upPeriod, max, input),
                aroonUp => max.IsReady
                );

            var min = new Minimum(name + "_Min", downPeriod);
            AroonDown = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonDown",
                input => ComputeAroonDown(downPeriod, min, input),
                aroonDown => min.IsReady
                );
        }
Exemplo n.º 9
0
        public void ResetsProperly() {
            var left = new Maximum("left", 2);
            var right = new Minimum("right", 2);
            var composite = new CompositeIndicator<IndicatorDataPoint>(left, right, (l, r) => l + r);

            left.Update(DateTime.Today, 1m);
            right.Update(DateTime.Today,-1m);

            left.Update(DateTime.Today.AddDays(1), -1m);
            right.Update(DateTime.Today.AddDays(1), 1m);

            Assert.AreEqual(left.PeriodsSinceMaximum, 1);
            Assert.AreEqual(right.PeriodsSinceMinimum, 1);

            composite.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(composite);
            TestHelper.AssertIndicatorIsInDefaultState(left);
            TestHelper.AssertIndicatorIsInDefaultState(right);
            Assert.AreEqual(left.PeriodsSinceMaximum, 0);
            Assert.AreEqual(right.PeriodsSinceMinimum, 0);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Creates a new Williams %R.
 /// </summary>
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The lookback period to determine the highest high for the AroonDown</param>
 public WilliamsPercentR(string name, int period)
     : base(name)
 {
     Maximum = new Maximum(name + "_Max", period);
     Minimum = new Minimum(name + "_Min", period);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Initialize the data and resolution you require for your strategy
        /// </summary>
        public override void Initialize()
        {
            //Initialize
            SetStartDate(2013, 1, 1);
            SetEndDate(2014, 12, 31);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

            //Add the Custom Data:
            AddData<Bitcoin>("BTC");

            //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
            _indicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                EMA = EMA(_symbol, 14, Resolution.Daily),
                SMA = SMA(_symbol, 14, Resolution.Daily),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily),
                AROON = AROON(_symbol, 20, Resolution.Daily),
                MOM = MOM(_symbol, 20, Resolution.Daily),
                MOMP = MOMP(_symbol, 20, Resolution.Daily),
                STD = STD(_symbol, 20, Resolution.Daily),
                MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property
                MAX = MAX(_symbol, 14, Resolution.Daily)  // by default if the symbol is a tradebar type then it will be the max of the high property
            };

            // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
            //  These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value
            //  We'll define these 'selector' functions to select the Low value
            //
            //  For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function
            //                                                     https://msdn.microsoft.com/en-us/library/bb397687.aspx
            //
            _selectorIndicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low),
                SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low),
                MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low),
                STD = STD(_symbol, 20, Resolution.Daily, Field.Low),
                MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property
                MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low),  // this will find the 14 day max of the low property

                // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
                // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar),
                AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar)
            };

            //Custom Data Indicator:
            _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily);
            _minCustom = MIN(_customSymbol, 14, Resolution.Daily);
            _maxCustom = MAX(_customSymbol, 14, Resolution.Daily);

            // in addition to defining indicators on a single security, you can all define 'composite' indicators.
            // these are indicators that require multiple inputs. the most common of which is a ratio.
            // suppose we seek the ratio of BTC to SPY, we could write the following:
            var spyClose = Identity(_symbol);
            var btcClose = Identity(_customSymbol);
            // this will create a new indicator whose value is BTC/SPY
            _ratio = btcClose.Over(spyClose);
            // we can also easily plot our indicators each time they update using th PlotIndicator function
            PlotIndicator("Ratio", _ratio);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            //Initialize dates
            SetStartDate(2015, 6, 15);
            SetEndDate(2015, 6, 15);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
            #region "Init indicators"
            Price = new RollingWindow<IndicatorDataPoint>(samplesize);
            ema = new RollingWindow<IndicatorDataPoint>(samplesize);
            zema = new RollingWindow<IndicatorDataPoint>(samplesize);
            OptimalValue1 = new RollingWindow<IndicatorDataPoint>(samplesize);
            OmtimalValue2 = new RollingWindow<IndicatorDataPoint>(samplesize);
            OptimalTrackingFilter = new RollingWindow<IndicatorDataPoint>(samplesize);
            lambda = new RollingWindow<IndicatorDataPoint>(samplesize);
            alpha = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalDiff = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalSign = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalCross = new RollingWindow<IndicatorDataPoint>(samplesize);
            fudge = new RollingWindow<IndicatorDataPoint>(samplesize);
            instantTrend = new RollingWindow<IndicatorDataPoint>(samplesize);
            instantTrendTrigger = new RollingWindow<IndicatorDataPoint>(samplesize);
            cyberCycle = new RollingWindow<IndicatorDataPoint>(samplesize);
            centerGravity = new RollingWindow<IndicatorDataPoint>(samplesize);
            cyberCycleSmooth = new RollingWindow<IndicatorDataPoint>(samplesize);
            rvi = new RelativeVigorIndex(8);
            rviHistory = new RollingWindow<IndicatorDataPoint>(samplesize);

            stochCenterGravityValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochCenterGravityValue2 = new RollingWindow<IndicatorDataPoint>(8);

            stochCyberCycleValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleValue2 = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleInverseFisher = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleFisher = new RollingWindow<IndicatorDataPoint>(8);

            stochRviHistoryValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochRviHistoryValue2 = new RollingWindow<IndicatorDataPoint>(8);

            ROC = new RateOfChange(4);
            maxCyberCycle = new Maximum(8);
            minCyberCycle = new Minimum(8);
            #endregion
            //mylog.Debug(transheader);
            mylog.Debug(ondataheader);
            string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees";
            mylog.Debug(msg);
            mylog.Debug(tradeheader);
        }
Exemplo n.º 13
0
    public static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyMediaLite.Util.Handlers.UnhandledExceptionHandler);
        Console.CancelKeyPress += new ConsoleCancelEventHandler(AbortHandler);

        // recommender arguments
        string method              = null;
        string recommender_options = string.Empty;

        // help/version
        bool show_help    = false;
        bool show_version = false;

        // variables for iteration search
        int max_iter   = 500;
        double cutoff  = 0;
        double epsilon = 0;
        string measure = "AUC";

        compute_fit         = false;

        // other parameters
        test_ratio         = 0;
        num_test_users     = -1;
        repeat_eval        = false;

        var p = new OptionSet() {
            // string-valued options
            { "training-file=",       v => training_file          = v },
            { "test-file=",           v => test_file              = v },
            { "recommender=",         v => method                 = v },
            { "group-recommender=",   v => group_method           = v },
            { "recommender-options=", v => recommender_options   += " " + v },
            { "data-dir=",            v => data_dir               = v },
            { "user-attributes=",     v => user_attributes_file   = v },
            { "item-attributes=",     v => item_attributes_file   = v },
            { "user-relations=",      v => user_relations_file    = v },
            { "item-relations=",      v => item_relations_file    = v },
            { "save-model=",          v => save_model_file        = v },
            { "load-model=",          v => load_model_file        = v },
            { "save-user-mapping=",   v => save_user_mapping_file = v },
            { "save-item-mapping=",   v => save_item_mapping_file = v },
            { "load-user-mapping=",   v => load_user_mapping_file = v },
            { "load-item-mapping=",   v => load_item_mapping_file = v },
            { "prediction-file=",     v => prediction_file        = v },
            { "test-users=",          v => test_users_file        = v },
            { "candidate-items=",     v => candidate_items_file   = v },
            { "user-groups=",         v => user_groups_file       = v },
            { "measure=",             v => measure                = v },
            // integer-valued options
            { "find-iter=",            (int v) => find_iter            = v },
            { "max-iter=",             (int v) => max_iter             = v },
            { "random-seed=",          (int v) => random_seed          = v },
            { "predict-items-number=", (int v) => predict_items_number = v },
            { "num-test-users=",       (int v) => num_test_users       = v },
            { "cross-validation=",     (uint v) => cross_validation    = v },
            // floating point options
            { "epsilon=",             (double v)     => epsilon      = v },
            { "cutoff=",              (double v)     => cutoff       = v },
            { "test-ratio=",          (double v) => test_ratio       = v },
            { "rating-threshold=",    (float v)  => rating_threshold = v },
            // enum options
            { "file-format=",         (ItemDataFileFormat v) => file_format = v },
            // boolean options
            { "user-prediction",      v => user_prediction   = v != null },
            { "compute-fit",          v => compute_fit       = v != null },
            { "online-evaluation",    v => online_eval       = v != null },
            { "repeat-evaluation",    v => repeat_eval       = v != null },
            { "no-id-mapping",        v => no_id_mapping     = v != null },
            { "overlap-items",        v => overlap_items     = v != null },
            { "all-items",            v => all_items         = v != null },
            { "in-training-items",    v => in_training_items = v != null },
            { "in-test-items",        v => in_test_items     = v != null },
            { "help",                 v => show_help         = v != null },
            { "version",              v => show_version      = v != null },
        };
        IList<string> extra_args = p.Parse(args);

        bool no_eval = true;
        if (test_ratio > 0 || test_file != null)
            no_eval = false;

        if (show_version)
            ShowVersion();
        if (show_help)
            Usage(0);

        if (random_seed != -1)
            MyMediaLite.Util.Random.Seed = random_seed;

        // set up recommender
         		if (load_model_file != null)
            recommender = Model.Load(load_model_file);
        else if (method != null)
            recommender = Recommender.CreateItemRecommender(method);
        else
            recommender = Recommender.CreateItemRecommender("MostPopular");
        // in case something went wrong ...
        if (recommender == null && method != null)
            Usage(string.Format("Unknown recommendation method: '{0}'", method));
        if (recommender == null && load_model_file != null)
            Abort(string.Format("Could not load model from file {0}.", load_model_file));

        CheckParameters(extra_args);

        recommender.Configure(recommender_options, (string m) => { Console.Error.WriteLine(m); Environment.Exit(-1); });

        if (no_id_mapping)
        {
            user_mapping = new IdentityMapping();
            item_mapping = new IdentityMapping();
        }
        if (load_user_mapping_file != null)
            user_mapping = EntityMappingExtensions.LoadMapping(load_user_mapping_file);
        if (load_item_mapping_file != null)
            item_mapping = EntityMappingExtensions.LoadMapping(load_item_mapping_file);

        // load all the data
        LoadData();
        Console.Write(training_data.Statistics(test_data, user_attributes, item_attributes));

        // if requested, save ID mappings
        if (save_user_mapping_file != null)
            user_mapping.SaveMapping(save_user_mapping_file);
        if (save_item_mapping_file != null)
            item_mapping.SaveMapping(save_item_mapping_file);

        TimeSpan time_span;

        if (find_iter != 0)
        {
            if ( !(recommender is IIterativeModel) )
                Abort("Only iterative recommenders (interface IIterativeModel) support --find-iter=N.");

            var iterative_recommender = (IIterativeModel) recommender;
            Console.WriteLine(recommender);
            var eval_stats = new List<double>();

            if (cross_validation > 1)
            {
                recommender.DoIterativeCrossValidation(cross_validation, test_users, candidate_items, eval_item_mode, repeat_eval, max_iter, find_iter);
            }
            else
            {
                if (load_model_file == null)
                    recommender.Train();

                if (compute_fit)
                    Console.WriteLine("fit: {0} iteration {1} ", ComputeFit(), iterative_recommender.NumIter);

                var results = Evaluate();
                Console.WriteLine("{0} iteration {1}", results, iterative_recommender.NumIter);

                for (int it = (int) iterative_recommender.NumIter + 1; it <= max_iter; it++)
                {
                    TimeSpan t = Wrap.MeasureTime(delegate() {
                        iterative_recommender.Iterate();
                    });
                    training_time_stats.Add(t.TotalSeconds);

                    if (it % find_iter == 0)
                    {
                        if (compute_fit)
                        {
                            t = Wrap.MeasureTime(delegate() {
                                Console.WriteLine("fit: {0} iteration {1} ", ComputeFit(), it);
                            });
                            fit_time_stats.Add(t.TotalSeconds);
                        }

                        t = Wrap.MeasureTime(delegate() { results = Evaluate(); });
                        eval_time_stats.Add(t.TotalSeconds);
                        eval_stats.Add(results[measure]);
                        Console.WriteLine("{0} iteration {1}", results, it);

                        Model.Save(recommender, save_model_file, it);
                        Predict(prediction_file, test_users_file, it);

                        if (epsilon > 0.0 && eval_stats.Max() - results[measure] > epsilon)
                        {
                            Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} >> {1}", results["RMSE"], eval_stats.Min()));
                            Console.Error.WriteLine("Reached convergence on training/validation data after {0} iterations.", it);
                            break;
                        }
                        if (results[measure] < cutoff)
                        {
                                Console.Error.WriteLine("Reached cutoff after {0} iterations.", it);
                                Console.Error.WriteLine("DONE");
                                break;
                        }
                    }
                } // for
            }
        }
        else
        {
            Console.WriteLine(recommender + " ");

            if (load_model_file == null)
            {
                if (cross_validation > 1)
                {
                    var results = recommender.DoCrossValidation(cross_validation, test_users, candidate_items, eval_item_mode, compute_fit, true);
                    Console.Write(results);
                    no_eval = true;
                }
                else
                {
                    time_span = Wrap.MeasureTime( delegate() { recommender.Train(); } );
                    Console.Write("training_time " + time_span + " ");
                }
            }

            if (prediction_file != null)
            {
                Predict(prediction_file, test_users_file);
            }
            else if (!no_eval)
            {
                if (compute_fit)
                    Console.WriteLine("fit: {0}", ComputeFit());

                if (online_eval)
                    time_span = Wrap.MeasureTime( delegate() {
                        var results = recommender.EvaluateOnline(test_data, training_data, test_users, candidate_items, eval_item_mode);
                        Console.Write(results);
                    });
                else if (group_method != null)
                {
                    GroupRecommender group_recommender = null;

                    Console.Write("group recommendation strategy: {0} ", group_method);
                    // TODO GroupUtils.CreateGroupRecommender(group_method, recommender);
                    if (group_method == "Average")
                        group_recommender = new Average(recommender);
                    else if (group_method == "Minimum")
                        group_recommender = new Minimum(recommender);
                    else if (group_method == "Maximum")
                        group_recommender = new Maximum(recommender);
                    else
                        Usage("Unknown group recommendation strategy in --group-recommender=METHOD");

                    time_span = Wrap.MeasureTime( delegate() {
                        var result = group_recommender.Evaluate(test_data, training_data, group_to_user, candidate_items);
                        Console.Write(result);
                    });
                }
                else
                    time_span = Wrap.MeasureTime( delegate() { Console.Write(Evaluate()); });
                Console.Write(" testing_time " + time_span);
            }
            Console.WriteLine();
        }
        Model.Save(recommender, save_model_file);
        DisplayStats();
    }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DonchianChannel"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="upperPeriod">The period for the upper channel.</param>
 /// <param name="lowerPeriod">The period for the lower channel</param>
 public DonchianChannel(string name, int upperPeriod, int lowerPeriod)
     : base(name)
 {
     UpperBand = new Maximum(name + "_UpperBand", upperPeriod);
     LowerBand = new Minimum(name + "_LowerBand", lowerPeriod);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            #region logging
            var algoname = this.GetType().Name;
            mylog.Debug(algoname);
            mylog.Debug(ondataheader);
            dailylog.Debug(algoname);
            dailylog.Debug(dailyheader);
            _transactions = new List<OrderTransaction>();

            var days = _endDate.Subtract(_startDate).TotalDays;
            MaxDailyProfit = new Maximum("MaxDailyProfit", (int)days);
            MinDailyProfit = new Minimum("MinDailyProfit", (int)days);
            #endregion

            //Initialize dates
            SetStartDate(_startDate);
            SetEndDate(_endDate);
            SetCash(_portfolioAmount);

            //Add as many securities as you like. All the data will be passed into the event handler:
            //AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);

            // Initialize the Symbol indexed dictionaries
            foreach (string s in Symbols)
            {
                AddSecurity(SecurityType.Equity, s, Resolution.Minute);
                Strategy.Add(symbol, new MultiITStrategy(s, ITrendPeriod, this));
                Tickets.Add(s, new List<OrderTicket>());
                // Equal portfolio shares for every stock.
                ShareSize.Add(s, (maxLeverage * (1 - leverageBuffer)) / Symbols.Count());
                LastOrderSent.Add(s, OrderSignal.doNothing);

                #region Logging stuff - Initializing Stock Logging

                //stockLogging.Add(new StringBuilder());
                //stockLogging[i].AppendLine("Counter, Time, Close, ITrend, Trigger," +
                //    "Momentum, EntryPrice, Signal," +
                //    "TriggerCrossOverITrend, TriggerCrossUnderITrend, ExitFromLong, ExitFromShort," +
                //    "StateFromStrategy, StateFromPorfolio, Portfolio Value");
                //i++;

                #endregion Logging stuff - Initializing Stock Logging
            }

            // Indicators
            Price = new RollingWindow<IndicatorDataPoint>(14);      // The price history

            // ITrend
            trend = new InstantaneousTrend("Main", 7, .25m);
            trendHistory = new RollingWindow<IndicatorDataPoint>(14);

            // The ITrendStrategy
            iTrendStrategy = new InstantTrendStrategy(symbol, 14, this);
            iTrendStrategy.ShouldSellOutAtEod = shouldSellOutAtEod;

            #region lists
            // Initialize the lists for the strategies
            trendList = new Dictionary<int, InstantaneousTrend>();
            trendHistoryList = new Dictionary<int, RollingWindow<IndicatorDataPoint>>();
            strategyList = new Dictionary<int, MultiITStrategy>();
            entryPriceList = new Dictionary<int, decimal>();

            int listIndex = 0;
            for (decimal d = .25m; d < .26m; d += .01m)
            {
                trendList.Add(listIndex, new InstantaneousTrend("ITrend_" + d, 7, d));  // eg ITrend.25, period 7, alpha .25
                trendHistoryList.Add(listIndex, new RollingWindow<IndicatorDataPoint>(4));
                strategyList.Add(listIndex, new MultiITStrategy(symbol, 7, this));
                entryPriceList.Add(listIndex, 0);
                listIndex++;
            }

            #endregion
            #region Proforma

            _brokerSimulator = new BrokerSimulator(this);

            #endregion
        }
Exemplo n.º 16
0
 /// <summary>
 /// AroonUp = 100 * (period - {periods since max})/period
 /// </summary>
 /// <param name="upPeriod">The AroonUp period</param>
 /// <param name="max">A Maximum indicator used to compute periods since max</param>
 /// <param name="input">The next input data</param>
 /// <returns>The AroonUp value</returns>
 private static decimal ComputeAroonUp(int upPeriod, Maximum max, IndicatorDataPoint input)
 {
     max.Update(input);
     return 100m * (upPeriod - max.PeriodsSinceMaximum) / upPeriod;
 }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a new IchimokuKinkoHyo indicator from the specific periods
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="tenkanPeriod">The Tenkan-sen period</param>
        /// <param name="kijunPeriod">The Kijun-sen period</param>
        /// <param name="senkouAPeriod">The Senkou A Span period</param>
        /// <param name="senkouBPeriod">The Senkou B Span period</param>
        /// <param name="senkouADelayPeriod">The Senkou A Span delay</param>
        /// <param name="senkouBDelayPeriod">The Senkou B Span delay</param>
        public IchimokuKinkoHyo(string name, int tenkanPeriod = 9, int kijunPeriod = 26, int senkouAPeriod = 26, int senkouBPeriod = 52, int senkouADelayPeriod = 26, int senkouBDelayPeriod = 26)
            : base(name)
        {
            TenkanMaximum = new Maximum(name + "_TenkanMax", tenkanPeriod);
            TenkanMinimum = new Minimum(name + "_TenkanMin", tenkanPeriod);
            KijunMaximum = new Maximum(name + "_KijunMax", kijunPeriod);
            KijunMinimum = new Minimum(name + "_KijunMin", kijunPeriod);
            SenkouBMaximum = new Maximum(name + "_SenkouBMaximum", senkouBPeriod);
            SenkouBMinimum = new Minimum(name + "_SenkouBMinimum", senkouBPeriod);
            DelayedTenkanSenkouA = new Delay(name + "DelayedTenkan", senkouADelayPeriod);
            DelayedKijunSenkouA = new Delay(name + "DelayedKijun", senkouADelayPeriod);
            DelayedMaximumSenkouB = new Delay(name + "DelayedMax", senkouBDelayPeriod);
            DelayedMinimumSenkouB = new Delay(name + "DelayedMin", senkouBDelayPeriod);


            SenkouA = new FunctionalIndicator<TradeBar>(
                name + "_SenkouA",
                input => computeSenkouA(senkouAPeriod, input),
                senkouA => DelayedTenkanSenkouA.IsReady && DelayedKijunSenkouA.IsReady,
                () =>
                {
                    Tenkan.Reset();
                    Kijun.Reset();
                });

            SenkouB = new FunctionalIndicator<TradeBar>(
                name + "_SenkouB",
                input => computeSenkouB(senkouBPeriod, input),
                senkouA => DelayedMaximumSenkouB.IsReady && DelayedMinimumSenkouB.IsReady,
                () =>
                {
                    Tenkan.Reset();
                    Kijun.Reset();
                });


            Tenkan = new FunctionalIndicator<TradeBar>(
                name + "_Tenkan",
                input => ComputeTenkan(tenkanPeriod, input),
                tenkan => TenkanMaximum.IsReady && TenkanMinimum.IsReady,
                () =>
                {
                    TenkanMaximum.Reset();
                    TenkanMinimum.Reset();
                });

            Kijun = new FunctionalIndicator<TradeBar>(
                name + "_Kijun",
                input => ComputeKijun(kijunPeriod, input),
                kijun => KijunMaximum.IsReady && KijunMinimum.IsReady,
                () =>
                {
                    KijunMaximum.Reset();
                    KijunMinimum.Reset();
                });
        }