private bool ParseHarpex(StockSerie stockSerie, string fileName)
        {
            // Read new downloaded values
             if (!File.Exists(fileName))
             {
            return false;
             }
             bool res = false;

             StockDailyValue harpexValue = null;
             DateTime date;
             float harpex = 0;
             string line = string.Empty;
             try
             {
            using (StreamReader sr = new StreamReader(fileName, true))
            {
               // File format
               // "date";"HARPEX";"Class 1";"Class 2";"Class 3";"Class 4";"Class 5";"Class 6";"Class 7";"Class 8"
               // 14/07/07;1296.25;1196.94;1163.11;1207.74;1180.47;1406.11;1404.5;1388.44;1475.32

               sr.ReadLine(); // Skip first line
               while (!sr.EndOfStream)
               {
                  line = sr.ReadLine();
                  string[] row = line.Split(';');
                  date = DateTime.Parse(row[0], StockAnalyzerApp.Global.EnglishCulture);
                  harpex = float.Parse(row[1], StockAnalyzerApp.Global.EnglishCulture);

                  harpexValue = new StockDailyValue(stockSerie.StockName,
                      harpex,
                      harpex,
                      harpex,
                      harpex, 0, date);
                  stockSerie.Add(harpexValue.DATE, harpexValue);
                  harpexValue.Serie = stockSerie;
               }
            }
            res = true;
             }
             catch (System.Exception e)
             {
            StockLog.Write("Failed to parse Harpex file " + e.Message + "\r\r" + line);
             }
             return res;
        }
        private static bool ParseIntradayData(StockSerie stockSerie, string fileName)
        {
            bool res = false;
             try
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               string line = sr.ReadLine();

               while (!(line = sr.ReadLine()).StartsWith("INTERVAL")) ;
               int interval;
               interval = int.Parse(line.Split('=')[1]);

               while (!(line = sr.ReadLine()).StartsWith("TIMEZONE_OFFSET")) ;
               int offset;
               offset = int.Parse(line.Split('=')[1]);

               string[] row;
               DateTime startDate = DateTime.Now;
               while (!sr.EndOfStream)
               {
                  line = sr.ReadLine();
                  DateTime openDate = DateTime.Now;
                  row = line.Split(new char[] { ',' });

                  if (line.StartsWith("a"))
                  {
                     // new day detected
                     string startString = row[0].Replace("a", "");
                     double seconds = double.Parse(startString);

                     startDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).AddMinutes(offset);
                     openDate = startDate;
                  }
                  else if (line.StartsWith("TIMEZONE_OFFSET"))
                  {
                     offset = int.Parse(line.Split('=')[1]);
                     continue;
                  }
                  else
                  {
                     // just a new bar
                     openDate = startDate.AddSeconds(long.Parse(row[0]) * interval);
                  }

                  if (!stockSerie.ContainsKey(openDate))
                  {
                     StockDailyValue dailyValue = new StockDailyValue(stockSerie.StockName,
                            float.Parse(row[4], usCulture),
                            float.Parse(row[2], usCulture),
                            float.Parse(row[3], usCulture),
                            float.Parse(row[1], usCulture),
                            long.Parse(row[5]),
                            openDate);
                     stockSerie.Add(dailyValue.DATE, dailyValue);
                  }
               }

               stockSerie.ClearBarDurationCache();

               res = true;
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write("Unable to parse intraday data for " + stockSerie.StockName);
            StockLog.Write(e);
             }
             return res;
        }
Exemplo n.º 3
0
        private void startButton_Click(object sender, EventArgs e)
        {
            if (started)
            {
                replaySerie = null;
                started = false;
                startButton.Text = "Start";
                startButton.Focus();
                nextButton.Enabled = false;
                moveButton.Enabled = false;

                this.Position.Number = 0;
                this.Position.OpenValue = 0;
                this.totalValue = 0;

                this.buyButton.Enabled = false;
                this.sellButton.Enabled = false;
                this.shortButton.Enabled = false;
                this.coverButton.Enabled = false;

                string msg = "Replay serie was:\t" + refSerie.StockName + Environment.NewLine +
                             "Start date:\t\t" + startDate.ToShortDateString() + Environment.NewLine +
                             "NbTrades:\t\t\t" + nbTrade + Environment.NewLine +
                             "NbWinTrades:\t\t" + nbWinTrade + Environment.NewLine +
                             "NbLostTrades:\t\t" + nbLostTrade + Environment.NewLine +
                             "AvgGain:\t\t\t" + (tradeGains.Sum() / nbTrade).ToString("P2");

                MessageBox.Show(msg);
            }
            else
            {
                Cursor cursor = this.Cursor;
                this.Cursor = Cursors.WaitCursor;

                try
                {
                    // Initialise stats
                    nbTrade = 0;
                    nbWinTrade = 0;
                    nbLostTrade = 0;
                    tradeGains.Clear();

                    // Create Portfolio
                    StockAnalyzerForm.MainFrame.CurrentPortofolio = portfolio;

                    portfolio.Clear();
                    replaySerie = new StockSerie("Replay", "Replay", StockSerie.Groups.ALL, StockDataProvider.Replay);

                    // Random pick

                    Random rand = new Random(DateTime.Now.Millisecond);
                    var series =
                       StockDictionary.StockDictionarySingleton.Values.Where(s => !s.IsPortofolioSerie && s.BelongsToGroup(StockSerie.Groups.COUNTRY))
                          .Select(s => s.StockName);

                    StockSerie serie = null;
                    do
                    {
                        string stockName = series.ElementAt(rand.Next(0, series.Count()));

                        serie = StockDictionary.StockDictionarySingleton[stockName];
                        serie.Initialise();
                        serie.BarDuration = StockSerie.StockBarDuration.Daily;
                    }
                    while (serie.Count < 400);

                    DateTime currentDate = DateTime.Today;
                    refSerie = new StockSerie(serie.StockName, serie.ShortName, serie.StockGroup, StockDataProvider.Replay);
                    foreach (StockDailyValue dailyVal in serie.Values)
                    {
                        StockDailyValue newValue = new StockDailyValue(serie.StockName, dailyVal.OPEN, dailyVal.HIGH, dailyVal.LOW, dailyVal.CLOSE, dailyVal.VOLUME, currentDate);
                        refSerie.Add(currentDate, newValue);
                        currentDate = currentDate.AddDays(1);
                    }

                    currentDate = DateTime.Today;
                    int nbInitBars = rand.Next(200, refSerie.Count - 200);

                    for (index = 0; index < nbInitBars; index++)
                    {
                        replaySerie.Add(currentDate, refSerie.ValueArray[index]);
                        currentDate = currentDate.AddDays(1);
                    }

                    dailyValue = serie.Values.Last();
                    startDate = dailyValue.DATE;

                    startButton.Text = "Stop";
                    nextButton.Enabled = true;
                    moveButton.Enabled = true;
                    nextButton.Focus();

                    OnPositionClosed();

                    this.Position.Number = 0;
                    this.Position.OpenValue = 0;
                    this.Position.CurrentValue = replaySerie.Values.Last().CLOSE;
                    this.totalValue = 0;

                    started = true;

                    refSerie.BarDuration = StockAnalyzerForm.MainFrame.BarDuration;
                    replaySerie.BarDuration = StockAnalyzerForm.MainFrame.BarDuration;
                    StockAnalyzerForm.MainFrame.CurrentStockSerie = replaySerie;

                    StockAnalyzerForm.MainFrame.Activate();
                }
                catch
                {
                }
                finally
                {
                    this.Cursor = cursor;
                }
            }
        }
        private static bool ParseIntradayData(StockSerie stockSerie, string fileName)
        {
            bool res = false;
             try
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               while (!sr.EndOfStream)
               {
                  string line = sr.ReadLine();
                  string[] row = line.Split(',');
                  if (row.Length <2) continue;

                  DateTime openDate;
                  if (!DateTime.TryParse(row[0], out openDate)) continue;
                  float value = float.Parse(row[1]);

                  if (!stockSerie.ContainsKey(openDate))
                  {
                     StockDailyValue dailyValue = new StockDailyValue(stockSerie.StockName,
                            value,
                            value,
                            value,
                            value,
                            0,
                            openDate);
                     stockSerie.Add(dailyValue.DATE, dailyValue);
                  }
               }

               stockSerie.ClearBarDurationCache();

               res = true;
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write("Unable to parse intraday data for " + stockSerie.StockName);
            StockLog.Write(e);
             }
             return res;
        }
Exemplo n.º 5
0
        // Private methods
        private bool ParseVIXPCRatioCSV(StockSerie stockSerie, string fileName)
        {
            if (File.Exists(fileName))
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               try
               {
                  StockDailyValue readValue = null;

                  // Skip 2 first lines
                  string name = "PCR.VIX";
                  sr.ReadLine();
                  sr.ReadLine();
                  while (sr.ReadLine().Contains("\"") && !sr.EndOfStream) ;

                  while (!sr.EndOfStream)
                  {
                     readValue = null;
                     string[] row = sr.ReadLine().Split(',');
                     if (row.GetLength(0) == 5)
                     {
                        readValue = new StockDailyValue(
                            name,
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            long.Parse(row[4], usCulture),
                            DateTime.Parse(row[0], usCulture));
                        stockSerie.Add(readValue.DATE, readValue);
                     }
                  }
               }
               catch (System.Exception e)
               {
                  StockLog.Write(e);
                  return false;
               }
            }
            return true;
             }
             else
             {
            return false;
             }
        }
Exemplo n.º 6
0
        private bool ParseCBOEIndexCSV(StockSerie stockSerie, string fileName)
        {
            if (File.Exists(fileName))
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               try
               {
                  StockDailyValue readValue = null;

                  sr.ReadLine();  // Skip the first line
                  sr.ReadLine();  // Skip the second line

                  while (!sr.EndOfStream)
                  {
                     // File format
                     // Date,Close
                     // 10-May-07,27.09
                     string[] row = sr.ReadLine().Split(',');
                     if (row.GetLength(0) == 2 && row[1] != "")
                     {
                        readValue = new StockDailyValue(
                            stockSerie.StockName,
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            float.Parse(row[1], usCulture),
                            100,
                            DateTime.Parse(row[0], usCulture));

                        if (readValue != null)
                        {
                           stockSerie.Add(readValue.DATE, readValue);
                        }
                     }
                  }
               }
               catch (System.Exception e)
               {
                  StockLog.Write(e);
                  return false;
               }
            }
            return true;
             }
             else
             {
            return false;
             }
        }
        private static bool ParseIntradayData(StockSerie stockSerie, string fileName)
        {
            bool res = false;
             try
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               string line;

               while ((line = sr.ReadLine()) != null)
               {
                  if (line.StartsWith("timezone")) break;
               }
               if (sr.EndOfStream) return false;
               string[] row = line.Split(new char[] { ':' });
               string timeZone = row[1];
               double gmtoffset = timeZone == "CEST" ? -32400 : 0;

               while ((line = sr.ReadLine()) != null)
               {
                  if (line.StartsWith("gmtoffset")) break;
               }
               if (sr.EndOfStream) return false;

               row = line.Split(new char[] { ':' });
               gmtoffset += double.Parse(row[1]);

               DateTime now = DateTime.Now;
               DateTime utcNow = now.ToUniversalTime();
               gmtoffset -= (now - utcNow).TotalSeconds;

               while (!(line = sr.ReadLine()).StartsWith("range")) ;

               // First Range, read second offest for date calculation.
               row = line.Split(new char[] { ',', ':' });
               DateTime startDate = new DateTime(int.Parse(row[1].Substring(0, 4)), int.Parse(row[1].Substring(4, 2)), int.Parse(row[1].Substring(6, 2)));

               //  startDate = startDate.AddHours(9);
               long startTimeStamp = long.Parse(row[2]);

               while (!(line = sr.ReadLine()).StartsWith("volume")) ;

               while (!sr.EndOfStream)
               {
                  line = sr.ReadLine();

                  row = line.Split(new char[] { ',' });

                  DateTime openDate = startDate;
                  openDate = startDate.AddSeconds(long.Parse(row[0]) - startTimeStamp);
                  openDate = startDate.AddSeconds(long.Parse(row[0]) - startTimeStamp - gmtoffset);
                  if (!stockSerie.ContainsKey(openDate))
                  {
                     StockDailyValue dailyValue = new StockDailyValue(stockSerie.StockName,
                            float.Parse(row[4], usCulture),
                            float.Parse(row[2], usCulture),
                            float.Parse(row[3], usCulture),
                            float.Parse(row[1], usCulture),
                            long.Parse(row[5]),
                            openDate);
                     stockSerie.Add(dailyValue.DATE, dailyValue);
                  }
               }

               stockSerie.ClearBarDurationCache();

               res = true;
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write("Unable to parse intraday data for " + stockSerie.StockName);
            StockLog.Write(e);
             }
             return res;
        }
Exemplo n.º 8
0
        private void GenerateCAC_Random()
        {
            List<StockSerie> cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise()).ToList();
            StockSerie cacEWSerie = new StockSerie("CAC_RANDOM", "CAC_RANDOM", StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();
            StockSerie BX4Serie = this.StockDictionary["BX4"];
            BX4Serie.Initialise();
            cacSeries.Add(BX4Serie);

            Random rnd = new Random();

            float value = 1000f;
            int previousCount = 0;
            foreach (DateTime date in cacSerie.Keys)
            {
                float var = 0.0f;
                int count = 0;
                int nbActive = 0;
                foreach (StockSerie serie in cacSeries)
                {
                    if (serie.ContainsKey(date))
                    {
                        count++;
                        if (rnd.Next(0, 11) > 5)
                        {
                            StockDailyValue dailyValue = serie[date];
                            var += dailyValue.VARIATION;
                            nbActive++;
                        }
                    }
                }
                //if (count < 5 && previousCount >= count && BX4Serie.ContainsKey(date))
                //{
                //   count++;
                //   StockDailyValue dailyValue = BX4Serie[date];
                //   var += dailyValue.VARIATION;
                //}
                if (count != 0) value += value * (var / count);
                cacEWSerie.Add(date, new StockDailyValue("CAC_RANDOM", value, value, value, value, (long)nbActive, date));

                previousCount = count;
            }
            StockDictionary.Add("CAC_RANDOM", cacEWSerie);
        }
Exemplo n.º 9
0
        private void GenerateCAC_SAR(bool stopOnLowBreadth, float speed)
        {
            string serieName = "CAC_SAR_" + speed.ToString("#.######");
            List<StockSerie> cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise()).ToList();
            StockSerie newIndexSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();
            //StockSerie BX4Serie = this.StockDictionary["BX4"];
            //BX4Serie.Initialise();
            //cacSeries.Add(BX4Serie);

            float value = 1000f;
            int previousCount = 0;
            int previousNbActive = 0;
            foreach (DateTime date in cacSerie.Keys)
            {
                float var = 0.0f;
                int count = 0;
                int nbActive = 0;
                foreach (StockSerie serie in cacSeries)
                {
                    if (serie.ContainsKey(date))
                    {
                        IStockIndicator indicator = serie.GetIndicator("SAR(0," + speed + ",0.2)");

                        count++;

                        int index = serie.IndexOf(date) - 1;
                        if (index >= 0 && indicator.Events[8][index])
                        {
                            StockDailyValue dailyValue = serie[date];
                            var += dailyValue.VARIATION;
                            nbActive++;
                        }
                    }
                }
                //if (count < 5 && previousCount >= count && BX4Serie.ContainsKey(date))
                //{
                //   count++;
                //   StockDailyValue dailyValue = BX4Serie[date];
                //   var += dailyValue.VARIATION;
                //}
                if (stopOnLowBreadth && previousNbActive < count / 2)
                {
                    newIndexSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)0, date));
                }
                else
                {
                    if (count != 0) value += value * (var / count);
                    newIndexSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)nbActive, date));
                }
                previousNbActive = nbActive;
                previousCount = count;
            }
            StockDictionary.Add(serieName, newIndexSerie);
        }
Exemplo n.º 10
0
        private void GenerateCACEqualWeightNoUpDay(DayOfWeek dayOfWeek)
        {
            //var cacSeries =
            //   this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise());
            string serieName = "CAC_EW_NO_UP_" + dayOfWeek;

            StockSplashScreen.ProgressText = "Generating " + serieName + "...";

            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();

            float value = cacSerie.First().Value.OPEN;
            int cacIndex = 0;
            StockDailyValue previousDailyValue = cacSerie.Values.First();

            foreach (StockDailyValue dailyValue in cacSerie.Values)
            {
                float volume = 0.0f;
                if (previousDailyValue.DATE.DayOfWeek == dayOfWeek && previousDailyValue.VARIATION < 0)
                {
                    value += value * dailyValue.VARIATION;
                }
                cacEWSerie.Add(dailyValue.DATE, new StockDailyValue(serieName, value, value, value, value, (long)volume, dailyValue.DATE));
                cacIndex++;
                previousDailyValue = dailyValue;
            }
            StockDictionary.Add(serieName, cacEWSerie);
        }
Exemplo n.º 11
0
        private void GenerateCAC_Event(string indexName, StockSerie.StockBarDuration barDuration, int period1, int period2,
           string eventPattern, string eventName, bool stopOnLowBreadth)
        {
            var cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise()).ToList();
            string serieName = indexName + period1 + "_" + period2 + "_" + barDuration;
            string ieventName = eventPattern.Replace("%PERIOD1%", period1.ToString());
            ieventName = ieventName.Replace("%PERIOD2%", period2.ToString());
            int eventIndex =
               ((IStockEvent)StockViewableItemsManager.GetViewableItem(ieventName)).EventNames.ToList().IndexOf(eventName);

            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();
            //StockSerie BX4Serie = this.StockDictionary["BX4"];
            //BX4Serie.Initialise();
            //cacSeries.Add(BX4Serie);

            foreach (StockSerie serie in cacSeries)
            {
                if (serie.BarDuration != barDuration) serie.BarDuration = barDuration;
            }
            float value = 1000f;
            int previousCount = 0;
            int previousNbActive = 0;
            foreach (DateTime date in cacSerie.Keys.Where(d => d.Year > 2005))
            {
                float var = 0.0f;
                int count = 0;
                int nbActive = 0;
                foreach (StockSerie serie in cacSeries)
                {
                    if (serie.ContainsKey(date) && serie.Count > 200)
                    {
                        count++;
                        IStockEvent events = (IStockEvent)serie.GetViewableItem(ieventName);
                        int index = serie.IndexOf(date) - 1;
                        if (index >= 0 && events.Events[eventIndex][index])
                        {
                            StockDailyValue dailyValue = serie.GetValues(StockSerie.StockBarDuration.Daily)
                               .ElementAt(index + 1);
                            var += dailyValue.VARIATION;
                            nbActive++;
                        }
                    }
                }
                if (stopOnLowBreadth && previousNbActive < count / 2)
                {
                    cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)0, date));
                }
                else
                {
                    if (count != 0) value += value * (var / count);
                    cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)nbActive, date));
                }
                previousNbActive = nbActive;
                previousCount = count;
            }
            foreach (StockSerie serie in cacSeries)
            {
                if (serie.BarDuration != StockSerie.StockBarDuration.Daily) serie.BarDuration = StockSerie.StockBarDuration.Daily;
            }
            StockDictionary.Add(serieName, cacEWSerie);
            StockLog.Write(serieName + ";" + period1 + ";" + period2 + ";" + cacEWSerie.Values.Last().CLOSE);
        }
Exemplo n.º 12
0
        private void GenerateCACEqualWeight2()
        {
            var cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise());
            string serieName = "CAC_EW2";
            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();

            IStockEvent CACIndicator = cacSerie.GetTrailStop("TRAILHLS(19,3)") as IStockEvent;

            float value = 1000f;
            int cacIndex = -1;
            foreach (DateTime date in cacSerie.Keys)
            {
                float var = 0.0f;
                float volume = 0.0f;
                int count = 0;
                if (cacIndex >= 0 && CACIndicator.Events[0][cacIndex])
                {
                    foreach (StockSerie serie in cacSeries)
                    {
                        if (serie.ContainsKey(date))
                        {
                            count++;
                            StockDailyValue dailyValue = serie[date];
                            var += dailyValue.VARIATION;
                            volume += dailyValue.CLOSE * dailyValue.VOLUME;
                        }
                    }
                    value += value * (var / count);
                }
                cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)volume, date));
                cacIndex++;
            }
            StockDictionary.Add(serieName, cacEWSerie);
        }
Exemplo n.º 13
0
        private void GenerateCACEqualWeight()
        {
            var cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise());
            string serieName = "CAC_EW";
            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();

            float value = 1000f;
            int cacIndex = 0;
            foreach (DateTime date in cacSerie.Keys)
            {
                float var = 0.0f;
                float volume = 0.0f;
                int count = 0;
                foreach (StockSerie serie in cacSeries)
                {
                    if (serie.ContainsKey(date))
                    {
                        count++;
                        StockDailyValue dailyValue = serie[date];
                        var += dailyValue.VARIATION;
                        volume += dailyValue.CLOSE * dailyValue.VOLUME;
                    }
                }
                value += value * (var / count);
                cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)volume, date));
                cacIndex++;
            }
            StockDictionary.Add(serieName, cacEWSerie);
        }
Exemplo n.º 14
0
        private void GenerateCAC2_Event(string indexName, StockSerie.StockBarDuration barDuration, int period, string eventPattern, string eventName, bool stopOnLowBreadth)
        {
            var cacSeries = this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise()).ToList();
            int seriesCount = cacSeries.Count;
            string serieName = indexName + "2_" + period + "_" + barDuration;
            string ieventName = eventPattern.Replace("%PERIOD%", period.ToString());
            int eventIndex =
               ((IStockEvent)StockViewableItemsManager.GetViewableItem(ieventName)).EventNames.ToList().IndexOf(eventName);

            foreach (StockSerie serie in cacSeries)
            {
                serie.BarDuration = barDuration;
            }
            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();

            float cash = cacSeries.Count * 1000;
            float value = cash;

            List<Position> openedPositions = new List<Position>();
            List<Position> closedPositions = new List<Position>();
            foreach (DateTime date in cacSerie.Keys.Where(d => d.Year > 1991))
            {
                // Try to sell
                foreach (Position pos in openedPositions)
                {
                    StockSerie serie = cacSeries.First(s => s.StockName == pos.Name);
                    int index = serie.IndexOf(date) - 1;
                    if (index > 0)
                    {
                        IStockEvent events = (IStockEvent)serie.GetViewableItem(ieventName);
                        if (!events.Events[eventIndex][index])
                        {
                            StockDailyValue dailyValue = serie.GetValues(StockSerie.StockBarDuration.Daily).ElementAt(index + 1);
                            cash += pos.EndPosition(dailyValue.OPEN);

                            closedPositions.Add(pos);
                        }
                    }
                }

                // Try to buy
                int openPositionCount = openedPositions.Count(p => p.IsOpened);
                float invested = 0.0f;
                foreach (StockSerie serie in cacSeries.Where(s => !openedPositions.Any(p => p.Name == s.StockName)))
                {
                    int index = serie.IndexOf(date) - 1;
                    if (index > 0)
                    {
                        IStockEvent events = (IStockEvent)serie.GetViewableItem(ieventName);
                        if (events.Events[eventIndex][index])
                        {
                            StockDailyValue dailyValue = serie.GetValues(StockSerie.StockBarDuration.Daily).ElementAt(index + 1);
                            int qty = (int)(cash / ((seriesCount - openPositionCount) * dailyValue.OPEN));

                            openedPositions.Add(new Position(serie.StockName, dailyValue.OPEN, qty));

                            invested += qty * dailyValue.OPEN;
                        }
                    }
                }
                cash -= invested;

                // Clean opened positions
                openedPositions.RemoveAll(p => !p.IsOpened);

                int count = openedPositions.Count;

                value = cash;
                foreach (Position pos in openedPositions)
                {
                    StockSerie serie = cacSeries.First(s => s.StockName == pos.Name);
                    DateTime posDate = date;
                    StockDailyValue dailyValue = null;
                    do
                    {
                        dailyValue = serie.GetValues(StockSerie.StockBarDuration.Daily).FirstOrDefault(v => v.DATE == posDate);
                        posDate = posDate.AddDays(-1);
                    } while (dailyValue == null);

                    value += pos.Number * dailyValue.CLOSE;
                }

                value = value / (float)cacSeries.Count;

                cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)count, date));
            }
            foreach (StockSerie serie in cacSeries)
            {
                serie.BarDuration = StockSerie.StockBarDuration.Daily;
            }
            StockDictionary.Add(serieName, cacEWSerie);

            StockLog.Write(serieName + ";" + period + ";" + cacEWSerie.Values.Last().CLOSE);
        }
        private bool GenerateSumSerie(StockSerie stockSerie, StockSerie trinSerie, bool inverse)
        {
            StockDailyValue logValue = null;
             float sum = 0f;
             foreach (StockDailyValue dailyValue in trinSerie.Values)
             {
            sum += dailyValue.CLOSE;

            logValue = new StockDailyValue(stockSerie.StockName,
               sum,
               sum,
               sum,
               sum, 0, dailyValue.DATE);
            stockSerie.Add(logValue.DATE, logValue);
            logValue.Serie = stockSerie;
             }
             return true;
        }
Exemplo n.º 16
0
        private void GenerateCAC_TL(StockSerie.StockBarDuration barDuration, int period)
        {
            var cacSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise());
            string serieName = "CAC_TL" + period + "_" + barDuration;
            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC,
               StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary["CAC40"];
            cacSerie.Initialise();
            StockSerie BX4Serie = this.StockDictionary["BX4"];
            BX4Serie.Initialise();

            float value = 1000f;
            int previousCount = 0;
            foreach (DateTime date in cacSerie.Keys)
            {
                float var = 0.0f;
                int count = 0;
                foreach (StockSerie serie in cacSeries)
                {
                    if (serie.ContainsKey(date))
                    {
                        serie.BarDuration = barDuration;
                        IStockPaintBar trendLine = serie.GetPaintBar("TRENDLINEHL(" + period + ",10)");
                        int index = serie.IndexOf(date) - 1;
                        if (index >= 0 && trendLine.Events[5][index])
                        {
                            count++;
                            StockDailyValue dailyValue = serie.GetValues(StockSerie.StockBarDuration.Daily)
                               .ElementAt(index + 1);
                            var += dailyValue.VARIATION;
                        }
                    }
                }
                //if (count < 5 && previousCount >= count && BX4Serie.ContainsKey(date))
                //{
                //   count++;
                //   StockDailyValue dailyValue = BX4Serie[date];
                //   var += dailyValue.VARIATION;
                //}
                if (count != 0) value += value * (var / count);
                cacEWSerie.Add(date, new StockDailyValue(serieName, value, value, value, value, (long)count, date));

                previousCount = count;
            }
            foreach (StockSerie serie in cacSeries)
            {
                serie.BarDuration = StockSerie.StockBarDuration.Daily;
            }
            StockDictionary.Add(serieName, cacEWSerie);
        }
        private bool ParseBarChartFile(StockSerie stockSerie, string fileName)
        {
            bool res = false;
             try
             {
            if (File.Exists(fileName))
            {
               using (StreamReader sr = new StreamReader(fileName))
               {
                  DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
                  Response jsonResponse = jsonSerializer.ReadObject(sr.BaseStream) as Response;
                  if (jsonResponse != null && jsonResponse.error != null)
                  {
                     foreach (var data in jsonResponse.data.series[0].data)
                     {
                        DateTime date = refDate.AddMilliseconds(data[0]).Date;
                        if (!stockSerie.ContainsKey(date))
                        {
                           stockSerie.Add(date, new StockDailyValue(stockSerie.StockName, (float)data[1], (float)data[2], (float)data[3], (float)data[4], 0, date));
                        }
                     }

                     res = true;
                  }
               }
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write(e);
            res = false;
             }
             return res;
        }
Exemplo n.º 18
0
        private void GenerateIndexOnlyDay(string stockName, DayOfWeek dayOfWeek)
        {
            string serieName = stockName + "_ONLY_" + dayOfWeek;

            StockSplashScreen.ProgressText = "Generating " + serieName + "...";

            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC, StockDataProvider.Generated);
            StockSerie stockSerie = this.StockDictionary[stockName];
            stockSerie.Initialise();

            float value = stockSerie.First().Value.OPEN;
            int cacIndex = 0;
            foreach (StockDailyValue dailyValue in stockSerie.Values)
            {
                float volume = 0.0f;
                if (dailyValue.DATE.DayOfWeek == dayOfWeek)
                {
                    value += value * dailyValue.VARIATION;
                }
                cacEWSerie.Add(dailyValue.DATE, new StockDailyValue(serieName, value, value, value, value, (long)volume, dailyValue.DATE));
                cacIndex++;
            }
            StockDictionary.Add(serieName, cacEWSerie);
        }
Exemplo n.º 19
0
        public override bool LoadData(string rootFolder, StockSerie stockSerie)
        {
            string[] row = stockSerie.StockName.Split('/');
             string serieName = row[0] + "/" + row[1];
             if (!StockDictionary.StockDictionarySingleton.ContainsKey(row[0]))
             {
            throw new Exception("Stock " + row[0] + " Not found, cannot calculate ratio");
             }
             StockSerie s1 = StockDictionary.StockDictionarySingleton[row[0]];
             if (!StockDictionary.StockDictionarySingleton.ContainsKey(row[1]))
             {
            throw new Exception("Stock " + row[1] + " Not found, cannot calculate ratio");
             }
             StockSerie s2 = StockDictionary.StockDictionarySingleton[row[1]];

             // Generate ratio serie
             StockSerie s3 = s1.GenerateRelativeStrenthStockSerie(s2);

             // Copy Into current serie
             stockSerie.IsInitialised = false;
             foreach (var pair in s3)
             {
            stockSerie.Add(pair.Key, pair.Value);
             }
             return true;
        }
Exemplo n.º 20
0
        private void GenerateIndex_Event(string stockName, string indexName, StockSerie.StockBarDuration barDuration, int period1, int period2, string eventPattern, string eventName)
        {
            string serieName = stockName + "_" + indexName + period1 + "_" + period2 + "_" + barDuration;
            StockSplashScreen.ProgressText = "Generating " + serieName + "...";

            string ieventName = eventPattern.Replace("%PERIOD1%", period1.ToString());
            ieventName = ieventName.Replace("%PERIOD2%", period2.ToString());
            int eventIndex = ((IStockEvent)StockViewableItemsManager.GetViewableItem(ieventName)).EventNames.ToList().IndexOf(eventName);

            StockSerie cacEWSerie = new StockSerie(serieName, serieName, StockSerie.Groups.INDICES_CALC, StockDataProvider.Generated);
            StockSerie cacSerie = this.StockDictionary[stockName];
            cacSerie.Initialise();
            cacSerie.BarDuration = barDuration;

            float value = 1000f;// cacSerie.Values.First().CLOSE;
            IStockEvent events = (IStockEvent)cacSerie.GetViewableItem(ieventName);
            int index = 2;
            foreach (StockDailyValue dailyValue in cacSerie.Values.Skip(2))
            {
                if (events.Events[eventIndex][index - 1])
                {
                    if (events.Events[eventIndex][index - 2])
                    {
                        value += value * dailyValue.VARIATION;
                    }
                    else
                    {
                        value += value * (dailyValue.CLOSE - dailyValue.OPEN) / dailyValue.OPEN;
                    }
                }

                cacEWSerie.Add(dailyValue.DATE, new StockDailyValue(serieName, value, value, value, value, (long)0, dailyValue.DATE));
                index++;
            }
            StockDictionary.Add(serieName, cacEWSerie);
            StockLog.Write(serieName + ";" + period1 + ";" + period2 + ";" + cacEWSerie.Values.Last().CLOSE);
        }
Exemplo n.º 21
0
        private static void ParseIntradayData(StockSerie stockSerie, string folder, string fileName)
        {
            try
             {
            if (File.Exists(folder + "\\" + fileName))
            {
               using (StreamReader sr = new StreamReader(folder + "\\" + fileName))
               {
                  string line = sr.ReadLine();
                  string[] row = line.Replace("\"", "").Replace(" - ", ",").Split(',');
                  if (row.Length == 7)
                  {
                     try
                     {
                        StockDailyValue dailyValue = new StockDailyValue(stockSerie.StockName,
                            float.Parse(row[2], usCulture),
                            float.Parse(row[4], usCulture),
                            float.Parse(row[3], usCulture),
                            float.Parse(row[5], usCulture),
                            long.Parse(row[6]),
                            DateTime.Parse(row[0] + " " + row[1], usCulture));

                        StockDailyValue lastValue = stockSerie.Values.Last();

                        if (lastValue.DATE.Date == dailyValue.DATE.Date)
                        {
                           if (lastValue.DATE.Hour == 0 && lastValue.DATE.Minute == 0) return;

                           stockSerie.Remove(lastValue.DATE);
                        }
                        stockSerie.Add(dailyValue.DATE, dailyValue);
                        stockSerie.ClearBarDurationCache();
                     }
                     catch (System.Exception e)
                     {
                        StockLog.Write("Unable to parse intraday data for " + stockSerie.StockName);
                        StockLog.Write(line);
                        StockLog.Write(e);
                     }
                  }
               }
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write("Unable to parse intraday data for " + stockSerie.StockName);
            StockLog.Write(e);
             }
        }
Exemplo n.º 22
0
        private void GenerateVixPremium()
        {
            if (!this.StockDictionary.ContainsKey("VIX"))
            {
                return;
            }
            StockSerie vixSerie = this.StockDictionary["VIX"];
            if (!vixSerie.Initialise())
            {
                return;
            }
            StockSerie spSerie = this.StockDictionary["SP500"];
            if (!spSerie.Initialise())
            {
                return;
            }
            StockSerie vixPremium = new StockSerie("VIX_PREMIUM", "VIX_PREMIUM", StockSerie.Groups.INDICATOR,
               StockDataProvider.Generated);

            // Generate the VIX Premium
            FloatSerie spVolatilitySerie = spSerie.GetSerie(StockIndicatorType.VOLATILITY_STDEV);
            float spVolatility = 0;
            int index = 0;
            foreach (StockDailyValue vixValue in vixSerie.Values)
            {
                index = spSerie.IndexOf(vixValue.DATE);
                if (index != -1)
                {
                    spVolatility = spVolatilitySerie[index];
                    StockDailyValue dailyValue = new StockDailyValue(vixPremium.StockName, vixValue.OPEN / spVolatility,
                       vixValue.HIGH / spVolatility, vixValue.LOW / spVolatility, vixValue.CLOSE / spVolatility, 0, vixValue.DATE);
                    vixPremium.Add(dailyValue.DATE, dailyValue);
                    dailyValue.Serie = vixPremium;
                }
            }
            vixPremium.Initialise();
            this.StockDictionary.Add(vixPremium.StockName, vixPremium);
        }
Exemplo n.º 23
0
        private bool ParsePCRatioCSV(StockSerie stockSerie, string fileName)
        {
            if (File.Exists(fileName))
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               StockDailyValue readValue = null;

               while (!sr.ReadLine().EndsWith("P/C Ratio") && !sr.EndOfStream) ;

               while (!sr.EndOfStream)
               {
                  try
                  {
                     string[] row = sr.ReadLine().Split(',');
                     float ratio = float.Parse(row[4], usCulture);

                     //ratio = (float)Math.Log10(ratio);
                     //if (inverse) ratio = -ratio;

                     readValue = new StockDailyValue(
                         stockSerie.StockName,
                         ratio,
                         ratio,
                         ratio,
                         ratio,
                         long.Parse(row[3], usCulture),
                         DateTime.Parse(row[0], usCulture));
                     if (readValue != null && !stockSerie.ContainsKey(readValue.DATE))
                     {
                        stockSerie.Add(readValue.DATE, readValue);
                     }
                  }
                  catch (System.Exception e)
                  {
                     StockLog.Write(e);
                     return false;
                  }
               }
            }
            return true;
             }
             else
             {
            return false;
             }
        }
Exemplo n.º 24
0
        private bool ParseBullBearRatio(StockSerie stockSerie, string fileName)
        {
            // Read new downloaded values

             StockDailyValue bearBullRatioValue = null;
             DateTime date;
             float bearish = 0;
             float bullish = 0;
             float neutral = 0;
             float ratio = 0;
             string line = string.Empty;
             bool res = false;
             try
             {
            using (StreamReader sr = new StreamReader(fileName, true))
            {
               // File format
               // Date,Bullish,Neutral,Bearish
               // 9-11-87,50.0,23.0,27.0
               sr.ReadLine(); // Skip first line
               while (!sr.EndOfStream)
               {
                  line = sr.ReadLine();
                  if (string.IsNullOrWhiteSpace(line))
                  {
                     continue;
                  }

                  string[] row = line.Replace(":","").Split(new []{',',':','\t'});
                  date = DateTime.Parse(row[0], usCulture);
                  if (row[1].Contains("%"))
                  {
                     bullish = float.Parse(row[1].TrimEnd(percent), usCulture) / 100f;
                     neutral = float.Parse(row[2].TrimEnd(percent), usCulture) / 100f;
                     bearish = float.Parse(row[3].TrimEnd(percent), usCulture) / 100f;
                  }
                  else
                  {
                     bullish = float.Parse(row[1], usCulture);
                     neutral = float.Parse(row[2], usCulture);
                     bearish = float.Parse(row[3], usCulture);
                  }
                  ratio = bearish / bullish;

                  bearBullRatioValue = new StockDailyValue(bearBullRatioName,
                      ratio,
                      ratio,
                      ratio,
                      ratio, 0, date);
                  stockSerie.Add(bearBullRatioValue.DATE, bearBullRatioValue);
                  bearBullRatioValue.Serie = stockSerie;
               }
            }
            res = true;
             }
             catch (System.Exception e)
             {
            StockLog.Write("Failed to parse Bull/Bear ratio file: " + e.Message + "\r\r" + line);
             }
             return res;
        }
Exemplo n.º 25
0
        private bool ParseRydexData(StockSerie stockSerie, string fileName)
        {
            if (File.Exists(fileName))
             {
            using (StreamReader sr = new StreamReader(fileName))
            {
               StockDailyValue readValue = null;
               string line;

               // Skip 2 first lines
               while (!sr.EndOfStream && !(line = sr.ReadLine()).Contains("Date")) ;

               while (!sr.EndOfStream)
               {
                  readValue = null;
                  line = sr.ReadLine();
                  if (string.IsNullOrEmpty(line))
                  {
                     break;
                  }
                  line = line.Replace("\",\"", ";");
                  line = line.Replace("\"", "");
                  string[] row = line.Split(';');
                  if (row[2] == "N/A" || row[3] == "N/A" || row[1] == "AM") continue;
                  float value = float.Parse(row[3], usCulture) / float.Parse(row[2], usCulture);
                  readValue = new StockDailyValue(
                      stockSerie.StockName,
                      value,
                      value,
                      value,
                      value,
                      0,
                      DateTime.Parse(row[0], usCulture));
                  if (!stockSerie.ContainsKey(readValue.DATE))
                  {
                     stockSerie.Add(readValue.DATE, readValue);
                  }
               }
            }
            return true;
             }
             return false;
        }
Exemplo n.º 26
0
        private bool GenerateBullBearLogRatio(StockSerie stockSerie, bool inverse)
        {
            StockSerie ratioSerie = AAIIDataProvider.stockDictionary[bearBullRatioName];

             StockDailyValue bearBullLogRatioValue = null;
             float ratio;
             foreach (StockDailyValue dailyValue in ratioSerie.Values)
             {
            ratio = (float) Math.Log10(dailyValue.CLOSE);
            if (inverse) ratio = -ratio;

            bearBullLogRatioValue = new StockDailyValue(bearBullRatioName,
               ratio,
               ratio,
               ratio,
               ratio, 0, dailyValue.DATE);
            stockSerie.Add(bearBullLogRatioValue.DATE, bearBullLogRatioValue);
            bearBullLogRatioValue.Serie = stockSerie;
             }
             return true;
        }
Exemplo n.º 27
0
        internal void ToSerie(StockSerie stockSerie, StockSerie referenceSerie = null)
        {
            float open = 0.0f;
             float high = 0.0f;
             float low = 0.0f;
             float close = 0.0f;
             int volume = 1;
             float cash = TotalDeposit;

             Dictionary<string, PositionValues> stockPositionDico = new Dictionary<string, PositionValues>();

             // Statistics
             int nbTrades = 0;
             int nbWinTrades = 0;
             float maxDrawdown = float.MaxValue;
             float maxGain = float.MinValue;
             float maxLoss = float.MinValue;

             if (referenceSerie == null)
             {
            referenceSerie = StockDictionary.StockDictionarySingleton["CAC40"];
             }
             referenceSerie.Initialise();

             foreach (DateTime date in referenceSerie.GetValues(StockSerie.StockBarDuration.Daily).Where(d => d.DATE.Year > 2014).Select(v => v.DATE.Date))
             {
            // Calculate open value

            // Retrieve orders for this date/time
            var orderList = this.OrderList.FindAll(order => order.ExecutionDate.Date == date).OrderBy(o => o.ID);

            // Manage new orders
            foreach (StockOrder stockOrder in orderList)
            {
               int numberOfShare = stockOrder.IsShortOrder ? -stockOrder.Number : stockOrder.Number;
               if (stockOrder.IsBuyOrder()) // Buy position
               {
                  cash -= stockOrder.TotalCost;
                  if (stockPositionDico.ContainsKey(stockOrder.StockName))
                  {
                     stockPositionDico[stockOrder.StockName].Position += numberOfShare;
                     stockPositionDico[stockOrder.StockName].OpenValue =
                        (stockPositionDico[stockOrder.StockName].Position *
                         stockPositionDico[stockOrder.StockName].OpenValue + numberOfShare * stockOrder.Value) /
                        (stockPositionDico[stockOrder.StockName].Position + numberOfShare);
                  }
                  else
                  {
                     if (stockDictionary.ContainsKey(stockOrder.StockName) &&
                         stockDictionary[stockOrder.StockName].Initialise())
                     {
                        stockPositionDico.Add(stockOrder.StockName,
                           new PositionValues(numberOfShare, stockOrder.Value,
                              stockDictionary[stockOrder.StockName].GetValues(StockSerie.StockBarDuration.Daily)));
                     }
                     else
                     {
                        StockLog.Write("Initialisation failed: " + stockOrder.StockName);
                        stockPositionDico.Add(stockOrder.StockName,
                           new PositionValues(numberOfShare, stockOrder.Value, null));
                     }
                  }
               }
               else // Closing Position
               {
                  if (stockPositionDico.ContainsKey(stockOrder.StockName))
                  {
                     cash += stockOrder.TotalCost;
                     PositionValues position = stockPositionDico[stockOrder.StockName];
                     if (position.Position == numberOfShare)
                     {
                        maxDrawdown = Math.Min(maxDrawdown, position.MaxDrawdown);
                        stockPositionDico.Remove(stockOrder.StockName);
                        nbTrades++;
                     }
                     else
                     {
                        position.Position -= numberOfShare;
                     }
                     if (stockOrder.IsShortOrder)
                     {
                        if (position.OpenValue > stockOrder.Value)
                        {
                           nbWinTrades++;
                           maxGain = Math.Max(maxGain, (position.OpenValue - stockOrder.Value) / position.OpenValue);
                        }
                        else
                        {
                           maxLoss = Math.Max(maxLoss, -(position.OpenValue - stockOrder.Value) / position.OpenValue);
                        }
                     }
                     else
                     {
                        if (position.OpenValue < stockOrder.Value)
                        {
                           nbWinTrades++;
                           maxGain = Math.Max(maxGain, -(position.OpenValue - stockOrder.Value) / position.OpenValue);
                        }
                        else
                        {
                           maxLoss = Math.Max(maxLoss, (position.OpenValue - stockOrder.Value) / position.OpenValue);
                        }
                     }
                  }
                  else
                  {
                     // Open short position
                     cash += stockOrder.TotalCost;

                     if (stockDictionary.ContainsKey(stockOrder.StockName) &&
                         stockDictionary[stockOrder.StockName].Initialise())
                     {
                        stockPositionDico.Add(stockOrder.StockName,
                           new PositionValues(-numberOfShare, stockOrder.Value,
                              stockDictionary[stockOrder.StockName].GetValues(StockSerie.StockBarDuration.Daily)));
                     }
                     else
                     {
                        StockLog.Write("Initialisation failed: " + stockOrder.StockName);
                        stockPositionDico.Add(stockOrder.StockName,
                           new PositionValues(-numberOfShare, stockOrder.Value, null));
                     }

                     //throw new System.Exception("Sell order found on non bought stock " + stockOrder.StockName + " in " + this.Name);
                     // @@@@ Need to have proper error manegement otherwise the applications crashes.
                     //return referenceSerie;
                  }
               }
            }

            // Calculate new value after taking into account the orders.
            low = cash;
            high = cash;
            close = cash;
            open = cash;
            if (stockPositionDico.Count != 0)
            {
               foreach (PositionValues position in stockPositionDico.Values)
               {
                  StockDailyValue currentValue = position.AtDate(date);
                  if (currentValue == null)
                  {
                     // Position on stock not in dico
                     if (position.Position > 0)
                     {
                        close += position.OpenValue * position.Position;
                        open += position.OpenValue * position.Position;
                        low += position.OpenValue * position.Position;
                        high += position.OpenValue * position.Position;
                     }
                  }
                  else
                  {
                     // Position on stock  in dico
                     close += currentValue.CLOSE * position.Position;
                     open += currentValue.OPEN * position.Position;
                     if (position.Position > 0)
                     {
                        position.MaxValue = Math.Max(position.MaxValue, currentValue.HIGH);
                        position.MinValue = Math.Min(position.MinValue, currentValue.LOW);

                        low += currentValue.LOW * position.Position;
                        high += currentValue.HIGH * position.Position;
                     }
                     else
                     {
                        // We are facing a short order, everything is reversed
                        low += currentValue.HIGH * position.Position;
                        high += currentValue.LOW * position.Position;

                        position.MaxValue = Math.Max(position.MaxValue, currentValue.LOW);
                        position.MinValue = Math.Min(position.MinValue, currentValue.HIGH);
                     }
                  }
               }
            }

            StockDailyValue dailyValue = new StockDailyValue(stockSerie.StockName, open, high, low, close, volume, date);
            stockSerie.Add(date, dailyValue);
            dailyValue.Serie = stockSerie;
             }

             StockLog.Write("Statistics for " + stockSerie.StockName);
             StockLog.Write("NbTrades: " + nbTrades);
             StockLog.Write("Win %: " + ((float)nbWinTrades / (float)nbTrades).ToString("P2"));
             StockLog.Write("MaxDrowdown: " + maxDrawdown.ToString("P2"));
             StockLog.Write("MaxGain: " + maxGain.ToString("P2"));
             StockLog.Write("MaxLoss: " + maxLoss.ToString("P2"));
        }
 private bool GenerateLogSerie(StockSerie stockSerie, StockSerie ratioSerie, bool inverse)
 {
     StockDailyValue logValue = null;
      float ratio = 0;
      foreach (StockDailyValue dailyValue in ratioSerie.Values)
      {
     if (dailyValue.CLOSE > 0f)
     {
        ratio = (float)Math.Log10(dailyValue.CLOSE);
        if (inverse) ratio = -ratio;
     }
     logValue = new StockDailyValue(stockSerie.StockName,
        ratio,
        ratio,
        ratio,
        ratio, 0, dailyValue.DATE);
     stockSerie.Add(logValue.DATE, logValue);
     logValue.Serie = stockSerie;
      }
      return true;
 }
Exemplo n.º 29
0
        private bool ParseCOT(StockSerie stockSerie, string fileName)
        {
            StockLog.Write("ParseCOT: " + stockSerie.StockName + " from file: " + fileName);
             string line = string.Empty;
             bool res = false;
             try
             {
            int cotLongIndex = 10;
            int cotShortIndex = 11;
            int cotOpenInterestIndex = 6;
            using (StreamReader sr = new StreamReader(fileName))
            {
               StockDailyValue readValue = null;
               int endOfNameIndex = 0;

               string cotSerieName = string.Empty;
               DateTime cotDate;
               float cotValue = 0.0f;
               string[] row;
               sr.ReadLine();   // Skip header line
               while (!sr.EndOfStream)
               {
                  line = sr.ReadLine().Replace("\"", "");
                  if (line == string.Empty)
                  {
                     continue;
                  }
                  res = true;

                  endOfNameIndex = line.IndexOf(",");
                  cotSerieName = line.Substring(0, endOfNameIndex);
                  if (cotSerieName.Contains(" - "))
                  {
                     cotSerieName = cotSerieName.Substring(0, cotSerieName.IndexOf(" - "));
                  }

                  cotSerieName += "_COT";
                  if (stockSerie.StockName != cotSerieName)
                  {
                     continue;
                  }
                  row = line.Substring(endOfNameIndex + 2).Split(',');

                  cotDate = DateTime.Parse(row[1], usCulture);
                  if (!stockSerie.Keys.Contains(cotDate))
                  {
                     float cotLong = float.Parse(row[cotLongIndex]);
                     float cotShort = float.Parse(row[cotShortIndex]);
                     float cotOpenInterest = float.Parse(row[cotOpenInterestIndex]);
                     if (cotOpenInterest != 0.0f)
                     {
                        cotValue = 100.0f * (cotLong - cotShort) / cotOpenInterest;
                     }
                     else
                     {
                        cotValue = 0.0f;
                     }
                     readValue = new StockDailyValue(cotSerieName, cotValue, cotValue, cotValue, cotValue, 0, cotDate);
                     stockSerie.Add(readValue.DATE, readValue);
                     readValue.Serie = stockSerie;
                  }
                  else
                  {
                     StockLog.Write("COT for " + cotSerieName + " already added, data for" + row[3] + " exchange ignored");
                  }
               }
            }
             }
             catch (System.Exception e)
             {
            StockLog.Write(e.Message + "Failed to parse COT file" + "\r\r" + line);
             }
             return res;
        }
Exemplo n.º 30
0
        public override bool LoadData(string rootFolder, StockSerie stockSerie)
        {
            if (finraSerie == null)
            {
                finraSerie = LoadFINRASerie(rootFolder + FOLDER + "\\FINRA_Bond_Breadth.xml");
            }

            // Convert from StockFINRASerie to StockSerie
            var fields = stockSerie.StockName.Split('.');
            StockDailyValue dailyValue = null;
            switch (fields[0])
            {
                case "BOND_AD":
                    switch (fields[1])
                    {
                        case "ALL":

                            break;
                        case "IG":
                            foreach (var val in finraSerie.InvestGrade)
                            {
                                float open = -1.0f + (float)val.Advances * 2.0f / (float)val.Total;
                                dailyValue = new StockDailyValue(stockSerie.StockName, open, open, open, open, val.Volume, val.Date);
                                stockSerie.Add(val.Date, dailyValue);
                            }
                            break;
                        case "HY":
                            foreach (var val in finraSerie.HighYield)
                            {
                                float open = -1.0f + (float)val.Advances * 2.0f / (float)val.Total;
                                dailyValue = new StockDailyValue(stockSerie.StockName, open, open, open, open, val.Volume, val.Date);
                                stockSerie.Add(val.Date, dailyValue);
                            }
                            break;
                    }
                    break;
                case "McClellan":
                    switch (fields[1])
                    {
                        case "ALL":

                            break;
                        case "IG":
                            {
                                var serie = StockDictionary.StockDictionarySingleton["BOND_AD.IG"];
                                if (!serie.Initialise()) return false;
                                FloatSerie ema19 = serie.GetIndicator("EMA(19)").Series[0];
                                FloatSerie ema39 = serie.GetIndicator("EMA(39)").Series[0];
                                var diff = ema19 - ema39;
                                int i = 0;
                                foreach (var val in serie.Values)
                                {
                                    float open = diff[i++];
                                    dailyValue = new StockDailyValue(stockSerie.StockName, open, open, open, open, val.VOLUME, val.DATE);
                                    stockSerie.Add(val.DATE, dailyValue);
                                }
                            }
                            break;
                        case "HY":
                            {
                                var serie = StockDictionary.StockDictionarySingleton["BOND_AD.HY"];
                                if (!serie.Initialise()) return false;
                                FloatSerie ema19 = serie.GetIndicator("EMA(19)").Series[0];
                                FloatSerie ema39 = serie.GetIndicator("EMA(39)").Series[0];
                                var diff = ema19 - ema39;
                                int i = 0;
                                foreach (var val in serie.Values)
                                {
                                    float open = diff[i++];
                                    dailyValue = new StockDailyValue(stockSerie.StockName, open, open, open, open, val.VOLUME, val.DATE);
                                    stockSerie.Add(val.DATE, dailyValue);
                                }
                            }
                            break;
                    }
                    break;
            }

            return true;
        }