public void WriteToOutput(AlgoResult res)
 {
     using (StreamWriter w = File.AppendText(OutputPath))
     {
         w.WriteLine(res.ToCSVRow());
     }
 }
Exemplo n.º 2
0
        internal void RunSearch(Guid guid, Map graph)
        {
            _logger.LogInformation("Begin search with algorithm {name} (graph V={nodes}, E={edges})", DisplayNames[guid], graph.Vertices.Count(), graph.Edges.Count());

            if (Algos.TryGetValue(guid, out var algo))
            {
                var sw = Stopwatch.StartNew();

                var robots = new List <Robot>();
                for (var i = 0; i < graph.Starts.Count; i++)
                {
                    robots.Add(algo.RobotFactory(graph.Starts[i], graph.Targets[i]));
                }

                _logger.LogInformation("Robots={robots}", robots.Count);

                algo.InitializeInternal(graph.Clone(), robots);
                var initTime = sw.ElapsedMilliseconds;
                _logger.LogInformation("{action} took {ms} ms", "init", initTime);

                sw.Restart();
                algo.RunSearch();
                sw.Stop();
                _logger.LogInformation("{action} took {ms} ms", "search", sw.ElapsedMilliseconds);

                var result = new AlgoResult(graph, algo, initTime, sw.ElapsedMilliseconds);

                _eventAggregator.Publish(new SearchDoneEvent(result));
            }
            else
            {
                throw new KeyNotFoundException($"Could not find algorithm with guid '{guid}'");
            }
        }
Exemplo n.º 3
0
        public static AlgorithmResultMetrics FromAlgorithmResult(AlgoResult result)
        {
            var containersUsed  = result.Trucks.Count;
            var calculationTime = result.Time;

            var volumeUtilizations = result.Trucks.Select(CalculateContainerVolumeUtilization).ToList();
            var averageContainerVolumeUtilization =
                volumeUtilizations.Aggregate(0.0, (current, utilization) => current + Math.Pow(utilization, 2)) /
                containersUsed * 100;
            var worstUtilizationExceptLastOne = Math.Pow(volumeUtilizations.Count > 1? volumeUtilizations.Take(volumeUtilizations.Count - 1).Min(): volumeUtilizations.Min(), 2) * 100;
            var averageAxleLoadExceptLastOne  = result.Trucks.Aggregate(0.0,
                                                                        (current, truck) =>
                                                                        current +
                                                                        Math.Pow((truck.FrontAxle.FinalLoad / truck.FrontAxle.MaximumLoad + truck.RearAxle.FinalLoad / truck.RearAxle.MaximumLoad) / 2, 2)) /
                                                containersUsed * 100;

            ;           return(new AlgorithmResultMetrics(containersUsed: containersUsed, calculationTime: calculationTime, averageContainerVolumeUtilization: averageContainerVolumeUtilization, worstUtilizationExceptLastOne: worstUtilizationExceptLastOne, averageAxleLoadExceptLastOne: averageAxleLoadExceptLastOne));
        }
Exemplo n.º 4
0
        private static void PrintResult(AlgoResult algorithmResult)
        {
            foreach (var iterator in algorithmResult.Trucks.Select((Value, Index) => new { Value, Index }))
            {
                var truck = iterator.Value;
                Console.WriteLine($@"===========================Container {iterator.Index}===========================");
                Console.WriteLine(
                    $@"===========================Container volume: {truck.Volume}===========================");
                Console.WriteLine(
                    $@"===========================Container volume utilization: {AlgoResult.CalculateContainerVolumeUtilization(truck)}===========================");
                Console.WriteLine(
                    $@"===========================Steering axle load: {truck.FrontAxle.FinalLoad}===========================");
                Console.WriteLine(
                    $@"===========================Driving axle load: {truck.RearAxle.FinalLoad}===========================");

                foreach (var cargoItem in truck.Items)
                {
                    Console.WriteLine(cargoItem);
                }
            }
        }
        public async Task Run()
        {
            Console.WriteLine("Updating VIX and SPX data");
            await ApplyUpdates(true, false);

            Console.WriteLine("Loading VIX file");
            vixPrices = CSVProcessor.ProcessVIXFile(VIXPath);

            Console.WriteLine("Connecting to alpaca trading API");
            alpacaTradingClient = Environments.Paper.GetAlpacaTradingClient(API_KEY, new SecretKey(API_SECRET));

            Console.WriteLine("Connecting to alpaca data API");
            alpacaDataClient = Environments.Paper.GetAlpacaDataClient(API_KEY, new SecretKey(API_SECRET));

            Console.WriteLine("Getting Market Calendars");
            var calendars = (await alpacaTradingClient.ListCalendarAsync(StartDate, EndDate)).ToList();

            Console.WriteLine("Writing header line in output file");
            using (StreamWriter w = File.CreateText(OutputPath))
            {
                w.WriteLine("Symbol, Date, StartTime, EndTime, PatternAlgFound, PatternVisFound, PosOpenTime, PosCloseTime, PosLong, PosReturn");
            }

            foreach (var calDate in calendars)
            {
                List <DateTime> startTimes     = new List <DateTime>();
                DateTime        loopTime       = calDate.TradingOpenTime.AddMinutes(15);
                TimeSpan        timeUntilClose = calDate.TradingCloseTime.Subtract(loopTime);
                while (timeUntilClose.TotalMinutes >= 30)
                {
                    startTimes.Add(loopTime);
                    loopTime       = loopTime.Add(new TimeSpan(0, 30, 0));
                    timeUntilClose = calDate.TradingCloseTime.Subtract(loopTime);
                }

                // High volatility only.
                if (!vixPrices.ContainsKey(calDate.TradingDate.ToString("yyyy-MM-dd")))
                {
                    continue;
                }
                if (vixPrices[calDate.TradingDate.ToString("yyyy-MM-dd")].Open < 28)
                {
                    continue;
                }

                foreach (DateTime dateTime in startTimes)
                {
                    var barSet = (await alpacaDataClient.GetBarSetAsync(symbols, TimeFrame.Minute, 60, true, dateTime.Subtract(TimeSpan.FromMinutes(14)), calDate.TradingCloseTime));


                    foreach (string sym in symbols)
                    {
                        if (!barSet.ContainsKey(sym))
                        {
                            continue;
                        }
                        var bars = barSet[sym].ToList();
                        // Pattern matching algorithm:
                        if (bars.Count < 44)
                        {
                            continue;
                        }

                        int  istr    = 14;
                        int  endtime = 14;
                        bool gr      = false;
                        bool found   = false;

                        for (int i = 14; i < 44; i++)
                        {
                            var price = bars[i];
                            if (price.Close - price.Open > 0)
                            {
                                if (gr)
                                {
                                    continue;
                                }

                                if (i - istr >= 4)
                                {
                                    found   = true;
                                    endtime = i;
                                    break;
                                }

                                istr = i;
                                gr   = true;
                            }
                            else
                            {
                                if (!gr)
                                {
                                    continue;
                                }

                                if (i - istr >= 6)
                                {
                                    found   = true;
                                    endtime = i;
                                    break;
                                }

                                istr = i;
                                gr   = false;
                            }
                        }

                        if (!found)
                        {
                            continue;
                        }

                        bool lng = !gr;

                        decimal entPrice = bars[endtime].Close;
                        decimal exPrice  = bars[43].Close;

                        decimal profit = lng ? exPrice - entPrice : entPrice - exPrice;
                        decimal pct    = profit / entPrice;

                        // End of Algorithm - Should be a pattern match now

                        List <PriceData> prices = new List <PriceData>();
                        for (int i = 0; i < 30; i++)
                        {
                            var price = bars[i + 14];
                            prices.Add(new PriceData(price.Time.ToString("HH:mm"), i, price.Open, price.Close, price.High, price.Low));
                        }

                        AlgoResult match = new AlgoResult(prices, sym, dateTime, dateTime.AddMinutes(30), true, res => {
                            //WriteToOutput(res);
                        }, dateTime.AddMinutes(14 + endtime), dateTime.AddMinutes(44), lng, pct);

                        ChartManager.SendToChartQueue(match);
                        match.PatternVisFound = true;
                        WriteToOutput(match);
                    }
                }
            }
            ChartManager.DoneProcessing();
        }
Exemplo n.º 6
0
 public SearchDoneEvent(AlgoResult result)
 {
     _logger.Trace("{event} called", nameof(SearchDoneEvent));
     Result = result;
 }