private static bool IsAdjustedDataPointValid(StockDataPoint dp, bool hasSplitCoefficient)
 {
     return(dp is StockAdjustedDataPoint adp &&
            adp.AdjustedClosingPrice > 0 &&
            // adp.DividendAmount != default &&
            (hasSplitCoefficient == false || adp.SplitCoefficient != null));
 }
Exemple #2
0
 /// <summary>
 /// Parse line like 7-Apr-17,899.65,900.09,889.31,894.88,3710922 mapped as Date,Open,High,Low,Close,Volume
 /// </summary>
 /// <param name="reader"></param>
 /// <param name="stockDataPoints"></param>
 /// <returns></returns>
 private Tuple <bool, string> ParseDataPoint(StreamReader reader, List <StockDataPoint> stockDataPoints)
 {
     while (!reader.EndOfStream)
     {
         var line = reader.ReadLine();
         if (line != null)
         {
             var values = line.Split(',');
             if (values.Length != 6)
             {
                 return(new Tuple <bool, string>(false, line));
             }
             var stockDataPoint = new StockDataPoint
             {
                 Date   = DateTime.Parse(values[0]),
                 Open   = ParseHelper.ParseDouble(values[1]),
                 High   = ParseHelper.ParseDouble(values[2]),
                 Low    = ParseHelper.ParseDouble(values[3]),
                 Close  = ParseHelper.ParseDouble(values[4]),
                 Volume = ParseHelper.ParseDouble(values[5])
             };
             stockDataPoints.Add(stockDataPoint);
         }
     }
     return(new Tuple <bool, string>(true, null));
 }
Exemple #3
0
        private void UpdateLableStockData(int mouseX, int mouseY)
        {
            if (Linked)
            {
                if (_chart.StockData != null)
                {
                    StockDataPoint mouseDataPoint = _chart.PickStockData(mouseX);
                    if (ShowCandleDate)
                    {
                        labelStockData.Text = "Date : " + mouseDataPoint.DateTime.ToString("dddd dd MMMM yyyy");
                    }
                    else
                    {
                        labelStockData.Text = "Date : " + mouseDataPoint.DateTime.ToString("dddd dd MMMM");
                    }
                    labelStockData.Text    += "\nOpen : " + mouseDataPoint.Open.ToString() + "\nClose : " + mouseDataPoint.Close.ToString() + "\nVolume : " + mouseDataPoint.Volume.ToString();
                    labelStockData.Location = new Point(pictureBoxRender.Width - labelStockData.Width - 10, labelStockData.Location.Y);

                    if (_chart.Graphs.Count > 0)
                    {
                        foreach (GraphData graph in _chart.Graphs)
                        {
                            int            graphIndex     = graph.FindDateIndex(mouseDataPoint.DateTime);
                            GraphDataPoint graphDataPoint = graph.DataPoints[graphIndex];
                            labelGraphData.Text     = "Date : " + graphDataPoint.DateTime.ToShortDateString() + "\nValue : " + graphDataPoint.GraphData.ToString();
                            labelGraphData.Location = new Point(pictureBoxRender.Width - labelGraphData.Width - 10, labelGraphData.Location.Y);
                        }
                    }
                }
            }
        }
 private static bool IsDataPointValid(StockDataPoint dp)
 {
     return(dp.Time != default &&
            dp.OpeningPrice > 0 &&
            dp.ClosingPrice > 0 &&
            dp.HighestPrice > 0 &&
            dp.LowestPrice > 0 &&
            dp.Volume > 0);
 }
Exemple #5
0
        public List <StockDataPoint> DataPoints; //stores info for this day


        public Day(string ticker, List <StockDataPoint> dataPoints)
        {
            //set from passed in
            Ticker     = ticker;
            DataPoints = dataPoints;
            //PreviousClose = previousClose;

            //set from DataPoints
            Open = DataPoints.Last().OpeningPrice;
            //if (PreviousClose <= 0) { PreviousClose = Open; } //if not passed in set to open, in future use API to get day before whatever is first day so that it can be used, or throw away first day??
            Close    = DataPoints.First().ClosingPrice;
            OpenTime = DataPoints.Last().Time;

            //set with calculations
            decimal        avg  = 0;
            StockDataPoint high = DataPoints.Last();
            StockDataPoint low  = DataPoints.Last();

            foreach (var sdp in DataPoints)
            {
                avg    += sdp.ClosingPrice;
                Volume += sdp.Volume;
                if (sdp.ClosingPrice > high.ClosingPrice)
                {
                    high = sdp;
                }
                if (sdp.ClosingPrice < low.ClosingPrice)
                {
                    low = sdp;
                }
            }
            DayAverage  = avg / DataPoints.Count;
            High        = high.ClosingPrice;
            DayHighTime = high.Time;
            Low         = low.ClosingPrice;
            DayLowTime  = low.Time;

            /*
             * //DEBUGGING output day to text file
             * string dayFile = $"SPY_debug_dump_{OpenTime.ToString("yyyy-MM-dd")}.txt";
             * Console.WriteLine(dayFile);
             * if (!File.Exists(dayFile))
             * {
             *  using (StreamWriter f = new StreamWriter(Path.Combine(Directory.GetCurrentDirectory(), dayFile)))
             *  {
             *      string header = $"{Ticker},  {OpenTime},  Total points:{DataPoints.Count}\n";
             *      f.WriteLine(header);
             *      foreach (var sdp in DataPoints)
             *      {
             *          string temp = $"Time:{sdp.Time}\tOpen:{sdp.OpeningPrice}\tClose:{sdp.ClosingPrice}\tVolume:{sdp.Volume}";
             *          f.WriteLine(temp);
             *      }
             *  }
             * }
             */

            //set time segments with Datapoints
            Segments_130min = new List <TimeSegment>();
            Segments_65min  = new List <TimeSegment>();
            Segments_30min  = new List <TimeSegment>();
            Segments_5min   = new List <TimeSegment>();
            var       temp_130 = new List <TimeSlice>();
            var       temp_65  = new List <TimeSlice>();
            var       temp_30  = new List <TimeSlice>();
            var       temp_5   = new List <TimeSlice>();
            TimeSlice temp;
            int       i = 1;

            foreach (var sdp in DataPoints)
            {
                temp = new TimeSlice {
                    Time = sdp.Time, Open = sdp.OpeningPrice, Close = sdp.ClosingPrice, Volume = sdp.Volume
                };
                temp_130.Add(temp);
                temp_65.Add(temp);
                temp_30.Add(temp);
                temp_5.Add(temp);

                if (i % 130 == 0 || sdp == DataPoints.Last())
                {
                    Segments_130min.Add(new TimeSegment(temp_130));
                    temp_130 = new List <TimeSlice>();
                }
                if (i % 65 == 0 || sdp == DataPoints.Last())
                {
                    Segments_65min.Add(new TimeSegment(temp_65));
                    temp_65 = new List <TimeSlice>();
                }
                if (i % 30 == 0 || sdp == DataPoints.Last())
                {
                    Segments_30min.Add(new TimeSegment(temp_30));
                    temp_30 = new List <TimeSlice>();
                }
                if (i % 5 == 0 || sdp == DataPoints.Last())
                {
                    Segments_5min.Add(new TimeSegment(temp_5));
                    temp_5 = new List <TimeSlice>();
                }

                i++;
            }
        }
            private static StockData JObjectToAPIResult(JObject jObject)
            {
                StockData result = new StockData();

                foreach (JProperty obj in (JToken)jObject)
                {
                    if (obj.Name == "Meta Data")
                    {
                        foreach (JProperty meta in obj.Values())
                        {
                            if (meta.Name.Contains("Information"))
                            {
                                result.MetaData.Information = meta.Value.ToString();
                            }
                            if (meta.Name.Contains("Symbol"))
                            {
                                result.MetaData.Symbol = meta.Value.ToString();
                            }
                            if (meta.Name.Contains("Last Refreshed"))
                            {
                                result.MetaData.LastRefreshed = meta.Value.ToString();
                            }
                            if (meta.Name.Contains("Output Size"))
                            {
                                result.MetaData.OutputSize = meta.Value.ToString();
                            }
                            if (meta.Name.Contains("Time Zone"))
                            {
                                result.MetaData.TimeZone = meta.Value.ToString();
                            }
                        }
                    }
                    if (obj.Name.Contains("Time Series"))
                    {
                        foreach (JProperty timeEntry in obj.Values())
                        {
                            StockDataPoint stockData = new StockDataPoint();
                            stockData.DateTime = DateTime.Parse(timeEntry.Name);
                            foreach (JProperty dataPoint in timeEntry.Values())
                            {
                                if (dataPoint.Name.Contains("open"))
                                {
                                    stockData.Open = Convert.ToDouble(dataPoint.Value.ToString());
                                }
                                if (dataPoint.Name.Contains("high"))
                                {
                                    stockData.High = Convert.ToDouble(dataPoint.Value.ToString());
                                }
                                if (dataPoint.Name.Contains("low"))
                                {
                                    stockData.Low = Convert.ToDouble(dataPoint.Value.ToString());
                                }
                                if (dataPoint.Name.Contains("close"))
                                {
                                    stockData.Close = Convert.ToDouble(dataPoint.Value.ToString());
                                }
                                if (dataPoint.Name.Contains("volume"))
                                {
                                    stockData.Volume = Convert.ToDouble(dataPoint.Value.ToString());
                                }
                            }
                            result.TimeSeries.DataPoints.Add(stockData);
                        }
                        result.TimeSeries.DataPoints.Reverse();
                    }
                }
                result = SetInterval(result);

                return(result);
            }
Exemple #7
0
        public override async Task <MarketPriceRes> Execute(MarketPriceReq request)
        {
            try
            {
                string          apiKey = plcalc.Common.Properties.Settings.Default.AlphaVantageApiKey;; // enter your API key here
                var             client = new AlphaVantageStocksClient(apiKey);
                StockTimeSeries timeSeries;
                StockDataPoint  data = null;
                switch (request.ApiFunction)
                {
                case ApiFunction.TIME_SERIES_DAILY:
                    timeSeries =
                        await client.RequestDailyTimeSeriesAsync(request.Ticker, TimeSeriesSize.Compact, adjusted : false);

                    if (request.getPreviousClose)
                    {
                        var prevDate = DateTime.Now.DayOfWeek == DayOfWeek.Monday
                                ? DateTime.Now.AddDays(-3).Date
                                : DateTime.Now.Date.AddDays(-1).Date;
                        data = timeSeries.DataPoints.OrderByDescending(a => a.Time)
                               .FirstOrDefault(a => a.Time.Date == prevDate);
                    }
                    else
                    {
                        data = timeSeries.DataPoints.OrderByDescending(a => a.Time).FirstOrDefault();
                    }

                    if (data == null)
                    {
                        return(null);
                    }

                    return(new MarketPriceRes
                    {
                        Ticker = request.Ticker,
                        Date = data.Time,
                        Price = data.ClosingPrice
                    });

                case ApiFunction.TIME_SERIES_INTRADAY:
                    timeSeries =
                        await client.RequestIntradayTimeSeriesAsync(request.Ticker, IntradayInterval.OneMin, TimeSeriesSize.Compact);

                    data = timeSeries.DataPoints.OrderByDescending(a => a.Time).FirstOrDefault();
                    if (data == null)
                    {
                        return(null);
                    }

                    return(new MarketPriceRes
                    {
                        Ticker = request.Ticker,
                        Date = data.Time,
                        Price = data.ClosingPrice
                    });

                default:
                    throw new plcalcException("Invalid apifunction");
                }
            }
            catch (Exception ex)
            {
                //log error
                return(null);
            }
        }
Exemple #8
0
        public void Run(string key)
        {
            string fileName;

            using (var client = new WebClient())
            {
                fileName = AlphaVantageConfigs.BuildFilename(this.OutputSize, this.ApiFunction, this.TargetSymbol);
                string url = AlphaVantageConfigs.BuildUrl(this.OutputSize, this.ApiFunction, this.TargetSymbol, key);

                Console.WriteLine("key agent {2} requesting file {0} from {1}", fileName, url, key);
                client.DownloadFile(url, fileName);
            }

            List <StockDataPoint> data = new List <StockDataPoint>();

            try
            {
                using (TextFieldParser csvParser = new TextFieldParser(fileName))
                {
                    csvParser.SetDelimiters(new string[] { "," });
                    csvParser.ReadLine();

                    int rowsLoaded = 0;
                    while (!csvParser.EndOfData)
                    {
                        string[] fields = csvParser.ReadFields();

                        data.Add(new StockDataPoint(fields));
                        rowsLoaded += 1;
                    }
                    Console.WriteLine("key agent {0} loaded {1} rows", key, rowsLoaded);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            DataTable table = SQLUtilities.ToDataTable <StockDataPoint>(data);

            using (SqlConnection connection = new SqlConnection(AlphaVantageConfigs.ConnectionString))
            {
                connection.Open();

                string tempTableName = "#StockData";

                StockDataPoint.SqlCreateTempTable(connection, tempTableName);

                SqlBulkCopy sb = new SqlBulkCopy(connection);

                sb.DestinationTableName = tempTableName;

                sb.WriteToServer(table);

                string updateScript = "";
                string insertScript = "";

                if (this.ApiFunction == ApiFunction.Daily && this.OutputSize == OutputSize.Full)
                {
                    updateScript = $@"update s
set s.HistoricalLoadStatus = 1,
    s.MinDate = t.MinDate
from StockSymbol s
     inner join (select Symbol, min(PriceDate) as MinDate
	             from StockPriceDaily ss
				 where ss.Symbol = '{this.TargetSymbol}'
				 group by Symbol) t
	     on s.Symbol = t.Symbol
where s.Symbol = '{this.TargetSymbol}';";
                }
                else if (this.ApiFunction == ApiFunction.ThirtyMin && this.OutputSize == OutputSize.Full)
                {
                    updateScript = $@"update s
set s.HalfHourlyFullStatus = 1,
    s.MinDateTime = t.MinDateTime
from StockSymbol s
     inner join (select Symbol, min(PriceDate) as MinDateTime
	             from StockPrice30Min ss
				 where ss.Symbol = '{this.TargetSymbol}'
				 group by Symbol) t
	     on s.Symbol = t.Symbol
where s.Symbol = '{this.TargetSymbol}';";
                }

                insertScript = $@"insert into <Table> with (tablock)
(Symbol, PriceDate, [Open], High, Low, [Close], Volume)
select '{this.TargetSymbol}', [Open], [High], [Low], [Close], Volume
from #StockData t
where not exists (select 1
                  from StockPrice s 
				  where s.Symbol = '{this.TargetSymbol}'
				        and cast([TimeStamp] as date) = s.PriceDate
						and cast([TimeStamp] as time(0)) = s.PriceTime);"
                               .Replace("<Table>", this.ApiFunction == ApiFunction.Daily ? "StockPriceDaily" : "StockPrice30Min");

                string script = $@"
begin try
    begin transaction;
    {insertScript}
    {updateScript}
    commit transaction;
end try
begin catch
    --do some stuff or whatever...
end catch
";

                SqlCommand cmd = new SqlCommand(insertScript, connection);

                cmd.ExecuteNonQuery();

                connection.Close();
            }

            Console.WriteLine("key agent {0} saved {1} to database", key, this.Descriptor);
        }
Exemple #9
0
 public DataBar(StockDataPoint stockDataPoint) : this(stockDataPoint.Time, stockDataPoint.OpeningPrice, stockDataPoint.ClosingPrice, stockDataPoint.HighestPrice, stockDataPoint.LowestPrice, stockDataPoint.Volume)
 {
 }