예제 #1
0
 /// <summary>
 /// If we load a workspace, we need to instantiate the filters from the loaded model
 /// </summary>
 /// <param name="logAnalysis"></param>
 private void GenerateFiltersFromAnalysis(LogAnalysis logAnalysis)
 {
     foreach (var filter in logAnalysis.Filters)
     {
         AddQuery(filter);
     }
 }
예제 #2
0
 /// <summary>
 /// Generate the markers for the model loaded in the workspace
 /// </summary>
 /// <param name="currentAnalysis"></param>
 private void GenerateMarkersFromAnalysis(LogAnalysis currentAnalysis)
 {
     foreach (var textMarker in currentAnalysis.TextMarkers)
     {
         this.AddMarker(new TextMarkerViewModel(textMarker));
     }
 }
예제 #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 public ManageTextMarkersViewModel(LogAnalysis analysis)
 {
     _analysis                = analysis;
     _textMarkerVmList        = new ObservableCollection <TextMarkerViewModel>();
     CommandUpdateTextMarkers = new CommandRelay(CommandUpdateTextMarkersExecute,
                                                 CommandUpdateTextMarkersCanExecute);
 }
        public void CreateNewLogAnalysisTest()
        {
            var logA = new LogAnalysis();

            _session.CurrentAnalysis = logA;
            Assert.AreEqual(_session.Analyses[0], logA);
        }
예제 #5
0
        private static ParameterModel[] CreateParameterModels(CloudStorageAccount account, FunctionInstanceSnapshot snapshot)
        {
            List <ParameterModel> models = new List <ParameterModel>();

            // It's important that we order any virtual parameters (e.g. Singleton parameters) to the end
            // so they don't interfere with actual function parameter ordering
            var parameters = snapshot.Arguments.OrderBy(p => p.Value.IsVirtualParameter);
            IDictionary <string, ParameterLog> parameterLogs = LogAnalysis.GetParameterLogs(account, snapshot);

            foreach (KeyValuePair <string, FunctionInstanceArgument> parameter in parameters)
            {
                string name = parameter.Key;
                FunctionInstanceArgument argument = parameter.Value;
                ParameterLog             log;

                if (parameterLogs != null && parameterLogs.ContainsKey(name))
                {
                    log = parameterLogs[name];
                }
                else
                {
                    log = null;
                }

                LogAnalysis.AddParameterModels(name, argument, log, snapshot, models);
            }

            return(models.ToArray());
        }
예제 #6
0
        private static ParameterModel[] CreateParameterModels(CloudStorageAccount account, FunctionInstanceSnapshot snapshot)
        {
            List <ParameterModel> models = new List <ParameterModel>();

            IDictionary <string, FunctionInstanceArgument> parameters    = snapshot.Arguments;
            IDictionary <string, ParameterLog>             parameterLogs = LogAnalysis.GetParameterLogs(account, snapshot);

            foreach (KeyValuePair <string, FunctionInstanceArgument> parameter in parameters)
            {
                string name = parameter.Key;
                FunctionInstanceArgument argument = parameter.Value;
                ParameterLog             log;

                if (parameterLogs != null && parameterLogs.ContainsKey(name))
                {
                    log = parameterLogs[name];
                }
                else
                {
                    log = null;
                }

                LogAnalysis.AddParameterModels(name, argument, log, snapshot, models);
            }

            return(models.ToArray());
        }
예제 #7
0
 public void PrintData(LogAnalysis userDataAnalysis)
 {
     PrintMainInformation(userDataAnalysis);
     PrintUsers(userDataAnalysis);
     PrintEntryPages(userDataAnalysis);
     PrintDeparturePages(userDataAnalysis);
     PrintTenFirsSessions(userDataAnalysis.TenFirstSessions);
 }
예제 #8
0
        public void Format_BinderParameterLog_ReturnsNull()
        {
            ParameterLog log = new BinderParameterLog();

            string result = LogAnalysis.Format(log);

            Assert.Null(result);
        }
예제 #9
0
 private void PrintEntryPages(LogAnalysis userDataAnalysis)
 {
     Console.WriteLine("Strony wejściowe: ");
     userDataAnalysis.EntryPageNumbers.ForEach(u =>
     {
         Console.WriteLine($"{u.Key}, : {u.Value.ToString()}");
     });
     Console.WriteLine();
 }
예제 #10
0
 private void PrintMainInformation(LogAnalysis userDataAnalysis)
 {
     Console.WriteLine($"Ilość wszytskich sesji: {userDataAnalysis.TotalNumberOffSessions.ToString()}");
     Console.WriteLine();
     Console.WriteLine($"Najczęstsza strona startowa: {userDataAnalysis.MostCommonEntryPage.Key}; {userDataAnalysis.MostCommonEntryPage.Value.ToString()}");
     Console.WriteLine();
     Console.WriteLine($"Najczęstsza strona końcowa: {userDataAnalysis.MostCommonDeparturePage.Key}; {userDataAnalysis.MostCommonDeparturePage.Value.ToString()}");
     Console.WriteLine();
 }
예제 #11
0
 private void PrintUsers(LogAnalysis userDataAnalysis)
 {
     Console.WriteLine("Lista użytkowników, i ich dane: ");
     userDataAnalysis.UserList.ForEach(u =>
     {
         Console.WriteLine($"Użytkownik: {u.Ip}, ilość sesji: {u.UserSession.Count.ToString()}, średnia ilość żądań: {u.AverageNumberOfRequest.ToString()}");
     });
     Console.WriteLine();
 }
예제 #12
0
 private void PrintDeparturePages(LogAnalysis userDataAnalysis)
 {
     Console.WriteLine("Strony końcowe: ");
     userDataAnalysis.DeparturePageNumbers.ForEach(u =>
     {
         Console.WriteLine($"{u.Key}, : {u.Value.ToString()}");
     });
     Console.WriteLine();
 }
예제 #13
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="logAnalysis">Log analysis for the textmarkers informations</param>
 public FilterConverterViewModel(LogAnalysis logAnalysis)
 {
     _converter = new Filters.Converters.StringConverter();
     _context   = new Context {
         Analysis = logAnalysis
     };
     _queries = new List <FilterQueryViewModel>();
     GenerateFiltersFromAnalysis(logAnalysis);
     ActualQuery = string.Empty;
     InitAutoCompleteList();
 }
예제 #14
0
        public void FormatTime_Minutes(double minutes, string expected)
        {
            // Arrange
            var time = TimeSpan.FromMinutes(minutes);

            // Act
            string result = LogAnalysis.Format(time);

            // Assert
            AssertExpectedTimeString(expected, result);
        }
예제 #15
0
        public void FormatTime_ZeroTime_NoOutput()
        {
            // Arrange
            var time = TimeSpan.Zero;

            // Act
            string result = LogAnalysis.Format(time);

            // Assert
            Assert.Equal(string.Empty, result);
        }
예제 #16
0
        public void FormatTime_Hours(double hours, string expected)
        {
            // Arrange
            var time = TimeSpan.FromHours(hours);

            // Act
            string result = LogAnalysis.Format(time);

            // Assert
            AssertExpectedTimeString(expected, result);
        }
예제 #17
0
        public void FormatTime_Seconds(double seconds, string expected)
        {
            // Arrange
            var time = TimeSpan.FromSeconds(seconds);

            // Act
            string result = LogAnalysis.Format(time);

            // Assert
            AssertExpectedTimeString(expected, result);
        }
예제 #18
0
        public void Format_TextParameterLog()
        {
            const string expected = "Pass-Through";
            ParameterLog log      = new TextParameterLog()
            {
                Value = expected
            };

            string result = LogAnalysis.Format(log);

            Assert.Equal(expected, result);
        }
예제 #19
0
        public void Format_TableParameterLog(int entitiesWritten, double elapsedTime, string expected)
        {
            ParameterLog log = new TableParameterLog()
            {
                EntitiesWritten  = entitiesWritten,
                ElapsedWriteTime = TimeSpan.FromMilliseconds(elapsedTime)
            };

            string result = LogAnalysis.Format(log);

            Assert.Equal(expected, result);
        }
예제 #20
0
        public void Format_WriteBlobParameterLog(bool wasWritten, long bytesWritten, string expected)
        {
            ParameterLog log = new WriteBlobParameterLog()
            {
                WasWritten   = wasWritten,
                BytesWritten = bytesWritten
            };

            string result = LogAnalysis.Format(log);

            Assert.Equal(expected, result);
        }
예제 #21
0
        public void Format_ReadBlobParameterLog(long bytesRead, long logLength, double elapsedTime, string expected)
        {
            ParameterLog log = new ReadBlobParameterLog()
            {
                BytesRead   = bytesRead,
                Length      = logLength,
                ElapsedTime = TimeSpan.FromMilliseconds(elapsedTime)
            };

            string result = LogAnalysis.Format(log);

            Assert.Equal(expected, result);
        }
예제 #22
0
        public void FormatTime_Milliseconds(double milliseconds, string expected)
        {
            // Arrange
            // this is required since the FromMilliseconds method rounds the
            // result (so for e.g. FromMilliseconds(0.1) will create Timespan.Zero
            // which is not what we are trying to test here).
            var time = TimeSpan.FromTicks((long)(milliseconds * 10000));

            // Act
            string result = LogAnalysis.Format(time);

            // Assert
            AssertExpectedTimeString(expected, result);
        }
예제 #23
0
        public static void AddPnLHoldTime(this Plotter plotter, SimulatorCore sim)
        {
            var tradeLog = LogAnalysis
                           .GroupPositions(sim.Log, true)
                           .OrderBy(i => i.Entry.BarOfExecution.Time);

            plotter.SelectChart(Plotter.SheetNames.PNL_HOLD_TIME, "Days Held");
            foreach (var trade in tradeLog)
            {
                var pnl   = (trade.Quantity > 0 ? 100.0 : -100.0) * (trade.Exit.FillPrice / trade.Entry.FillPrice - 1.0);
                var label = pnl > 0.0 ? "Profit" : "Loss";
                plotter.SetX((trade.Exit.BarOfExecution.Time - trade.Entry.BarOfExecution.Time).TotalDays);
                plotter.Plot(label, pnl);
            }
        }
예제 #24
0
        public void Format_SingletonParameterLog()
        {
            SingletonParameterLog log = new SingletonParameterLog
            {
                LockAcquired = false
            };
            StringBuilder expected = new StringBuilder();

            expected.AppendLine("Waiting for lock...");
            Assert.Equal(expected.ToString(), LogAnalysis.Format(log));

            log = new SingletonParameterLog
            {
                LockAcquired      = false,
                TimeToAcquireLock = TimeSpan.FromSeconds(4),
                LockOwner         = "8F4DA397-4EF4-428E-9043-FC240376165E"
            };
            expected = new StringBuilder();
            expected.AppendLine("Waiting for lock...");
            expected.AppendLine("Lock Owner: 8F4DA397-4EF4-428E-9043-FC240376165E.");
            expected.AppendLine("Wait time: About 4 seconds.");
            Assert.Equal(expected.ToString(), LogAnalysis.Format(log));

            log = new SingletonParameterLog
            {
                LockAcquired      = true,
                TimeToAcquireLock = TimeSpan.FromSeconds(4)
            };
            expected = new StringBuilder();
            expected.AppendLine("Lock acquired.");
            expected.AppendLine("Wait time: About 4 seconds.");
            Assert.Equal(expected.ToString(), LogAnalysis.Format(log));

            log = new SingletonParameterLog
            {
                LockAcquired      = true,
                TimeToAcquireLock = TimeSpan.FromSeconds(4),
                LockDuration      = TimeSpan.FromSeconds(2)
            };
            expected = new StringBuilder();
            expected.AppendLine("Lock acquired.");
            expected.AppendLine("Wait time: About 4 seconds.");
            expected.AppendLine("Lock duration: About 2 seconds.");
            Assert.Equal(expected.ToString(), LogAnalysis.Format(log));
        }
예제 #25
0
        public static void AddMfeMae(this Plotter plotter, SimulatorCore sim)
        {
            var tradeLog = LogAnalysis
                           .GroupPositions(sim.Log, true)
                           .OrderBy(i => i.Entry.BarOfExecution.Time);

            plotter.SelectChart(Plotter.SheetNames.PNL_MFE_MAE, "Max Excursion");
            foreach (var trade in tradeLog)
            {
                var pnl   = 100.0 * (trade.Exit.FillPrice / trade.Entry.FillPrice - 1.0);
                var label = pnl > 0.0 ? "Profit" : "Loss";

                plotter.SetX(100.0 * (trade.HighestHigh / trade.Entry.FillPrice - 1.0));
                plotter.Plot(label, pnl);

                plotter.SetX(100.0 * (trade.LowestLow / trade.Entry.FillPrice - 1.0));
                plotter.Plot(label, pnl);
            }
        }
예제 #26
0
        public static void AddPositionLog(this Plotter plotter, SimulatorCore sim)
        {
            var tradeLog = LogAnalysis
                           .GroupPositions(sim.Log, true)
                           .OrderBy(i => i.Entry.BarOfExecution.Time);

            plotter.SelectChart("Position Log", "entry date");
            foreach (var trade in tradeLog)
            {
                plotter.SetX(string.Format("{0:MM/dd/yyyy}", trade.Entry.BarOfExecution.Time));
                plotter.Plot("exit date", string.Format("{0:MM/dd/yyyy}", trade.Exit.BarOfExecution.Time));
                plotter.Plot("days held", (trade.Exit.BarOfExecution.Time - trade.Entry.BarOfExecution.Time).TotalDays);
                plotter.Plot("Symbol", trade.Symbol);
                plotter.Plot("Quantity", trade.Quantity);
                plotter.Plot("% Profit", Math.Round((trade.Quantity > 0 ? 100.0 : -100.0) * (trade.Exit.FillPrice / trade.Entry.FillPrice - 1.0), 2));
                plotter.Plot("Exit", trade.Exit.OrderTicket.Comment ?? "");
                //plotter.Plot("$ Profit", trade.Quantity * (trade.Exit.FillPrice - trade.Entry.FillPrice));
            }
        }
예제 #27
0
        /// <summary>
        /// Standard constructor
        /// </summary>
        public YalvViewModel()
        {
            _manageRepoViewModel = new ManageRepositoryViewModel();
            _manageRepoViewModel.ActiveChanged += ManageRepoViewModelOnPropertyChanged;

            _logAnalysis = new LogAnalysis();
            YalvRegistry.Instance.ActualWorkspace.CurrentAnalysis = _logAnalysis;
            _manageTextMarkersViewModel = new ManageTextMarkersViewModel(_logAnalysis);


            _logEntryRows = new DisplayLogViewModel(_manageTextMarkersViewModel);

            CommandCancelProcessing = new CommandRelay(CommandCancelProcessingExecuted,
                                                       CommandCancelProcessingCanExecute);

            CommandRefresh = new CommandRelay(CommandRefreshExecute, CommandRequiresDataCanExecute);
            CommandDelete  = new CommandRelay(LogEntryRows.CommandDeleteExecute, LogEntryRows.CommandDeleteCanExecute);


            CommandUpdateTextMarkers = new CommandRelay(_manageTextMarkersViewModel.CommandUpdateTextMarkersExecute,
                                                        _manageTextMarkersViewModel.CommandUpdateTextMarkersCanExecute);

            CommandUpdateDelta = new CommandRelay(CommandUpdateDeltaExecute, CommandUpdateDeltaCanExecute);
        }
예제 #28
0
        public override void Run()
        {
            //========== initialization ==========

            StartTime = DateTime.Parse("01/01/2008");
            EndTime   = DateTime.Now.Date - TimeSpan.FromDays(5);

            foreach (var n in UNIVERSE)
            {
                AddDataSource(n);
            }
            AddDataSource(BENCHMARK);

            Deposit(INITIAL_CAPITAL);
            CommissionPerShare = 0.015;

            //========== simulation loop ==========

            foreach (var s in SimTimes)
            {
                //----- find instruments

                _benchmark = _benchmark ?? FindInstrument(BENCHMARK);
                var universe = Instruments
                               .Where(i => i != _benchmark)
                               .ToList();

                //----- calculate indicators

                // make sure to calculate indicators for the
                // full universe on every single bar
                var indicators = universe
                                 .ToDictionary(
                    i => i,
                    i => new
                {
                    rsi = i.Close.RSI(3),
                    roc = i.Close.Momentum(200),
                });

                var smaBand = _benchmark.Close.SMA(200).Multiply(0.98); // 2% below 200-day SMA

                // filter universe to potential candidates
                var filtered = universe
                               .Where(i => _benchmark.Close[0] > smaBand[0] &&
                                      indicators[i].rsi[0] < MAX_RSI)
                               .ToList();

                if (NextSimTime.DayOfWeek < SimTime[0].DayOfWeek) // open positions on Monday
                {
                    // sort candidates by ROC to find entries
                    var entries = filtered
                                  .OrderByDescending(i => indicators[i].roc[0])
                                  .Take(MAX_ENTRIES)
                                  .ToList();

                    foreach (var i in universe)
                    {
                        int targetShares = entries.Contains(i)
                            ? (int)Math.Floor(NetAssetValue[0] / MAX_ENTRIES / i.Close[0])
                            : 0;

                        i.Trade(targetShares - i.Position);
                    }
                }

                //----- output

                if (!IsOptimizing)
                {
                    // plot to chart
                    _plotter.SelectChart(Name + ": " + OptimizerParamsAsString, "date");
                    _plotter.SetX(SimTime[0]);
                    _plotter.Plot("nav", NetAssetValue[0]);
                    _plotter.Plot(_benchmark.Symbol, _benchmark.Close[0]);

                    // placeholder, to make sure positions land on sheet 2
                    _plotter.SelectChart(Name + " positions", "entry date");

                    // additional indicators
                    _plotter.SelectChart(Name + " extra", "date");
                    _plotter.SetX(SimTime[0]);
                    _plotter.Plot("leverage", Instruments.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]);
                }
            }

            //========== post processing ==========

            //----- print position log, grouped as LIFO

            if (!IsOptimizing)
            {
                var tradeLog = LogAnalysis
                               .GroupPositions(Log, true)
                               .OrderBy(i => i.Entry.BarOfExecution.Time);

                _plotter.SelectChart(Name + " positions", "entry date");
                foreach (var trade in tradeLog)
                {
                    _plotter.SetX(trade.Entry.BarOfExecution.Time);
                    _plotter.Plot("exit date", trade.Exit.BarOfExecution.Time);
                    _plotter.Plot("Symbol", trade.Symbol);
                    _plotter.Plot("Quantity", trade.Quantity);
                    _plotter.Plot("% Profit", (trade.Quantity > 0 ? 1.0 : -1.0) * (trade.Exit.FillPrice / trade.Entry.FillPrice - 1.0));
                    _plotter.Plot("Exit", trade.Exit.OrderTicket.Comment ?? "");
                    //_plotter.Plot("$ Profit", trade.Quantity * (trade.Exit.FillPrice - trade.Entry.FillPrice));
                }
            }

            //----- optimization objective

            double cagr = Math.Exp(252.0 / Math.Max(1, TradingDays) * Math.Log(NetAssetValue[0] / INITIAL_CAPITAL)) - 1.0;

            FitnessValue = cagr / Math.Max(1e-10, Math.Max(0.01, NetAssetValueMaxDrawdown));

            if (!IsOptimizing)
            {
                Output.WriteLine("CAGR = {0:P2}, DD = {1:P2}, Fitness = {2:F4}", cagr, NetAssetValueMaxDrawdown, FitnessValue);
            }
        }
예제 #29
0
        public override void Run()
        {
            //========== initialization ==========

            StartTime = DateTime.Parse("01/01/2008");
            EndTime   = DateTime.Now.Date - TimeSpan.FromDays(5);

            foreach (var n in UNIVERSE)
            {
                AddDataSource(n);
            }
            AddDataSource(BENCHMARK);

            Deposit(INITIAL_CAPITAL);
            CommissionPerShare = 0.015;

            var entryParameters = Enumerable.Empty <Instrument>()
                                  .ToDictionary(
                i => i,
                i => new
            {
                entryDate    = default(DateTime),
                entryPrice   = default(double),
                stopLoss     = default(double),
                profitTarget = default(double),
            });

            //========== simulation loop ==========

            foreach (var s in SimTimes)
            {
                //----- find instruments

                _benchmark = _benchmark ?? FindInstrument(BENCHMARK);
                var universe = Instruments
                               .Where(i => i != _benchmark)
                               .ToList();

                //----- calculate indicators

                // make sure to calculate indicators for the
                // full universe on every single bar
                var indicators = universe
                                 .ToDictionary(
                    i => i,
                    i => new
                {
                    sma150 = i.Close.SMA(SMA_DAYS),
                    adx7   = i.ADX(7),
                    atr10  = i.TrueRange().Divide(i.Close).SMA(10),
                    rsi3   = i.Close.RSI(3),
                });

                // filter universe to potential candidates
                var filtered = universe
                               .Where(i =>
                                      (ENTRY_DIR > 0
                            ? i.Close[0] > indicators[i].sma150[0]                // long: above sma
                            : i.Close[0] > i.Close[1] && i.Close[1] > i.Close[2]) && // short: 2 up-days
                                      indicators[i].adx7[0] > MIN_ADX &&
                                      indicators[i].atr10[0] > MIN_ATR / 10000.0 &&
                                      (ENTRY_DIR > 0
                            ? indicators[i].rsi3[0] < MINMAX_RSI   // long: maximum
                            : indicators[i].rsi3[0] > MINMAX_RSI)) // short: minimum
                               .ToList();

                //----- manage existing positions

                int numOpenPositions = Positions.Keys.Count();
                foreach (var pos in Positions.Keys)
                {
                    // time-based exit
                    if (entryParameters[pos].entryDate <= SimTime[MAX_HOLD_DAYS - 1])
                    {
                        pos.Trade(-pos.Position, OrderType.closeThisBar).Comment = "time exit";
                        numOpenPositions--;
                    }
                    else if (ENTRY_DIR > 0
                        ? pos.Close[0] >= entryParameters[pos].profitTarget  // long
                        : pos.Close[0] <= entryParameters[pos].profitTarget) // short
                    {
                        pos.Trade(-pos.Position,
                                  OrderType.openNextBar)
                        .Comment = "profit target";
                        numOpenPositions--;
                    }
                    else
                    {
                        pos.Trade(-pos.Position,
                                  OrderType.stopNextBar,
                                  entryParameters[pos].stopLoss)
                        .Comment = "stop loss";
                    }
                }

                //----- open new positions

                if (NextSimTime.DayOfWeek < SimTime[0].DayOfWeek) // open positions on Monday
                {
                    // sort candidates by RSI to find entries
                    var entries = ENTRY_DIR > 0
                        ? filtered // long
                                  .Where(i => i.Position == 0)
                                  .OrderBy(i => indicators[i].rsi3[0])
                                  .Take(MAX_ENTRIES - numOpenPositions)
                                  .ToList()
                        : filtered // short
                                  .Where(i => i.Position == 0)
                                  .OrderByDescending(i => indicators[i].rsi3[0])
                                  .Take(MAX_ENTRIES - numOpenPositions)
                                  .ToList();

                    foreach (var i in entries)
                    {
                        // save our entry parameters, so that we may access
                        // them later to manage exits
                        double entryPrice = ENTRY_DIR > 0
                                ? i.Close[0] * (1.0 - MIN_ATR / 10000.0) // long
                                : i.Close[0];                            // short

                        double stopLoss = ENTRY_DIR > 0
                                ? entryPrice * (1.0 - STOP_LOSS / 100.0 * indicators[i].atr10[0])  // long
                                : entryPrice * (1.0 + STOP_LOSS / 100.0 * indicators[i].atr10[0]); // short

                        double profitTarget = ENTRY_DIR > 0
                            ? entryPrice * (1.0 + PROFIT_TARGET / 10000.0)  // long
                            : entryPrice * (1.0 - PROFIT_TARGET / 10000.0); // short

                        entryParameters[i] = new
                        {
                            entryDate = NextSimTime,
                            entryPrice,
                            stopLoss,
                            profitTarget,
                        };

                        // calculate target shares in two ways:
                        // * fixed-fractional risk (with entry - stop-loss = "risk"), and
                        // * fixed percentage of total equity
                        double riskPerShare = ENTRY_DIR > 0
                            ? Math.Max(0.10, entryPrice - stopLoss)  // long
                            : Math.Max(0.10, stopLoss - entryPrice); // short

                        int sharesRiskLimited = (int)Math.Floor(MAX_RISK / 100.0 / MAX_ENTRIES * NetAssetValue[0] / riskPerShare);
                        int sharesCapLimited  = (int)Math.Floor(MAX_CAP / 100.0 / MAX_ENTRIES * NetAssetValue[0] / entryParameters[i].entryPrice);
                        int targetShares      = (ENTRY_DIR > 0 ? 1 : -1) * Math.Min(sharesRiskLimited, sharesCapLimited);

                        // enter positions with limit order
                        i.Trade(targetShares,
                                OrderType.limitNextBar,
                                entryParameters[i].entryPrice);
                    }
                }

                //----- output

                if (!IsOptimizing)
                {
                    // plot to chart
                    _plotter.SelectChart(Name + ": " + OptimizerParamsAsString, "date");
                    _plotter.SetX(SimTime[0]);
                    _plotter.Plot("nav", NetAssetValue[0]);
                    _plotter.Plot(_benchmark.Symbol, _benchmark.Close[0]);

                    // placeholder, to make sure positions land on sheet 2
                    _plotter.SelectChart(Name + " positions", "entry date");

                    // additional indicators
                    _plotter.SelectChart(Name + " extra", "date");
                    _plotter.SetX(SimTime[0]);
                    _plotter.Plot("leverage", Instruments.Sum(i => i.Position * i.Close[0]) / NetAssetValue[0]);
                }
            }

            //========== post processing ==========

            //----- print position log, grouped as LIFO

            if (!IsOptimizing)
            {
                var tradeLog = LogAnalysis
                               .GroupPositions(Log, true)
                               .OrderBy(i => i.Entry.BarOfExecution.Time);

                _plotter.SelectChart(Name + " positions", "entry date");
                foreach (var trade in tradeLog)
                {
                    _plotter.SetX(trade.Entry.BarOfExecution.Time);
                    _plotter.Plot("exit date", trade.Exit.BarOfExecution.Time);
                    _plotter.Plot("Symbol", trade.Symbol);
                    _plotter.Plot("Quantity", trade.Quantity);
                    _plotter.Plot("% Profit", (ENTRY_DIR > 0 ? 1.0 : -1.0) * (trade.Exit.FillPrice / trade.Entry.FillPrice - 1.0));
                    _plotter.Plot("Exit", trade.Exit.OrderTicket.Comment ?? "");
                    //_plotter.Plot("$ Profit", trade.Quantity * (trade.Exit.FillPrice - trade.Entry.FillPrice));
                }
            }

            //----- optimization objective

            double cagr = Math.Exp(252.0 / Math.Max(1, TradingDays) * Math.Log(NetAssetValue[0] / INITIAL_CAPITAL)) - 1.0;

            FitnessValue = cagr / Math.Max(1e-10, Math.Max(0.01, NetAssetValueMaxDrawdown));

            if (!IsOptimizing)
            {
                Output.WriteLine("CAGR = {0:P2}, DD = {1:P2}, Fitness = {2:F4}", cagr, NetAssetValueMaxDrawdown, FitnessValue);
            }
        }
예제 #30
0
 public void InitEnvironment()
 {
     _analysis = new LogAnalysis();
     _entry1   = new LogEntry();
     _entry2   = new LogEntry();
 }