public async Task SaveHistory(StockHistory history) { var collection = _mongoWrapper.StockDatabase.GetCollection <StockHistoryData>(StockHistoryData); FilterDefinition <StockHistoryData> filter = Builders <StockHistoryData> .Filter.Eq(s => s.Symbol, history.Symbol); var filteredData = await collection.FindAsync(filter); var existing = filteredData.FirstOrDefault(); if (existing == null) { var data = new StockHistoryData { Id = ObjectId.GenerateNewId().ToString(), Symbol = history.Symbol, History = history.History.OrderByDescending(h => h.ClosingDate).ToList() }; await collection.InsertOneAsync(data); } else { UpdateDefinition <StockHistoryData> update = Builders <StockHistoryData> .Update.Set(s => s.History, history.History); await collection.UpdateOneAsync(filter, update); } }
/// <summary> /// 通过yahoo接口获得股票历史数据 /// </summary> /// <param name="Code">股票代码</param> /// <param name="StartDate">数据开始时间</param> /// <param name="EndDate">数据结束时间</param> /// <returns>改股票的历史数据</returns> public List <StockHistoryData> getDataFromYahoo(string Code, DateTime StartDate, DateTime EndDate) { List <StockHistoryData> result = new List <StockHistoryData>(); try { string yahooApiUrl = DataHelper.GetConfig("getYahooStockHistoryDataUrl"); string request = getRequestUrl(yahooApiUrl, Code, StartDate, EndDate); string data = wc.DownloadString(request); string[] dataline = DataHelper.Remove(data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries), 0); foreach (var item in dataline) { string[] datarow = item.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); StockHistoryData shd = new StockHistoryData(); shd.StockCode = Code; shd.StockHistoryDate = Convert.ToDateTime(datarow[0]).ToString("yyyy-MM-dd"); shd.SOpen = decimal.Round(Convert.ToDecimal(datarow[1]), 2); shd.SHigh = decimal.Round(Convert.ToDecimal(datarow[2]), 2); shd.SLow = decimal.Round(Convert.ToDecimal(datarow[3]), 2); shd.SClose = decimal.Round(Convert.ToDecimal(datarow[4]), 2); shd.SVolume = Convert.ToInt64(datarow[5]); result.Add(shd); } } catch (Exception ex) { LogHelper.WriteLog(string.Format("下载股票历史数据失败<br/>股票代码:{0}<br/>下载数据开始时间:{1}<br/>下载数据结束时间:{2}<br/>错误原因:{3}", Code, StartDate, EndDate, ex.Message)); } return(result); }
public static StockHistoryData Load(string file, StockNameTable nameTable) { StockHistoryData data; data = _cache.GetOrAdd(file, (string f) => StockHistoryData.LoadFromFile(f, DateTime.MinValue, DateTime.MaxValue, nameTable)); return(data); }
public StockHistoryData getDataFromXinLang(string Code) { StockHistoryData result = new StockHistoryData(); try { string xinLangApiUrl = DataHelper.GetConfig("getStockDataUrl"); string request = getRequestUrl(xinLangApiUrl, Code); string[] data = wc.DownloadString(request).Split(','); result.StockCode = Code; result.SClose = Convert.ToDecimal(data[2]); result.SOpen = Convert.ToDecimal(data[3]); result.SHigh = Convert.ToDecimal(data[4]); result.SLow = Convert.ToDecimal(data[5]); result.SVolume = Convert.ToInt64(data[8]); result.StockHistoryDate = Convert.ToDateTime(data[30]).ToString("yyyy-MM-dd"); } catch (Exception ex) { LogHelper.WriteLog(string.Format("下载股票数据失败<br/>股票代码:{0}<br/>错误原因:{1}", Code, ex.Message)); result.StockCode = "-1"; //表示下载失败 } return(result); }
static void ProcessOneFile(string file, DateTime startDate, DateTime endDate, string outputFileFolder, string[] metrics) { if (string.IsNullOrEmpty(file) || string.IsNullOrEmpty(outputFileFolder)) { throw new ArgumentNullException(); } var data = StockHistoryData.LoadFromFile(file, startDate, endDate); if (data == null) { return; } var allFieldNames = new List <string>(); // parse metrics to expression var metricExpressions = metrics .Select(MetricEvaluationContext.ParseExpression) .ToArray(); // build field names for (var i = 0; i < metrics.Length; ++i) { if (metricExpressions[i].FieldNames.Length == 1) { allFieldNames.Add(metrics[i]); } else { var i1 = i; allFieldNames.AddRange(metricExpressions[i].FieldNames.Select(s => metrics[i1] + "." + s)); } } // calculate metrics var metricValues = data.DataOrderedByTime .Select(bar => metricExpressions .SelectMany( m => { m.MultipleOutputUpdate(bar); return(m.Values); }) .ToArray()) .ToList(); var outputFile = Path.Combine(outputFileFolder, data.Name.Code + ".day.metric.csv"); using (var outputter = new StreamWriter(outputFile, false, Encoding.UTF8)) { var header = "code,date," + string.Join(",", allFieldNames.Select(MetricHelper.ConvertMetricToCsvCompatibleHead)); outputter.WriteLine(header); var times = data.DataOrderedByTime.Select(d => d.Time).ToArray(); for (var i = 0; i < times.Length; ++i) { var value = string.Join( ",", metricValues[i] .Select(v => string.Format("{0:0.00}", v))); outputter.WriteLine( "{0},{1:yyyy/MM/dd},{2}", data.Name.Code, times[i], value); } } }
static void ProcessOneFile(string file, DateTime startDate, DateTime endDate, string outputFileFolder, string[] metrics) { if (string.IsNullOrEmpty(file) || string.IsNullOrEmpty(outputFileFolder)) { throw new ArgumentNullException(); } StockHistoryData data = LoadInputFile(file, startDate, endDate); List <double[]> metricValues = new List <double[]>(); List <string> allFieldNames = new List <string>(); // parse metrics to expression MetricExpression[] metricExpressions = metrics .Select(m => MetricEvaluationContext.ParseExpression(m)) .ToArray(); // build field names for (int i = 0; i < metrics.Length; ++i) { if (metricExpressions[i].FieldNames.Length == 1) { allFieldNames.Add(metrics[i]); } else { allFieldNames.AddRange(metricExpressions[i].FieldNames.Select(s => metrics[i] + "." + s)); } } // calculate metrics foreach (Bar bar in data.Data) { var metricValuesForOneBar = metricExpressions.SelectMany(m => m.MultipleOutputUpdate(bar)).ToArray(); metricValues.Add(metricValuesForOneBar); } string outputFile = Path.Combine(outputFileFolder, data.Name.Code + ".day.metric.csv"); using (StreamWriter outputter = new StreamWriter(outputFile, false, Encoding.UTF8)) { string header = "code,date," + string.Join(",", allFieldNames.Select(m => MetricHelper.ConvertMetricToCsvCompatibleHead(m))); outputter.WriteLine(header); var times = data.Data.Select(d => d.Time).ToArray(); for (int i = 0; i < times.Length; ++i) { string value = string.Join( ",", metricValues[i] .Select(v => string.Format("{0:0.00}", v))); outputter.WriteLine( "{0},{1:yyyy/MM/dd},{2}", data.Name.Code, times[i], value); } } }
private void ShowStockData(string code, DateTime startTime, DateTime endTime, bool addAnnotation) { string file = _stockDataSettings.BuildActualDataFilePathAndName(code); StockHistoryData data; try { data = ChinaStockDataAccessor.Load(file, _stockNameTable); } catch (Exception ex) { ShowError("Load data file failed", ex); return; } // update label of code labelCode.Text = code; var stockSeries = chartData.Series[StockSeriesIndex]; var volumeSeries = chartData.Series[VolumeSeriesIndex]; var chartArea = chartData.ChartAreas[ChartAreaIndex]; var bars = data.DataOrderedByTime; if (bars == null || bars.Count() == 0) { stockSeries.Points.Clear(); volumeSeries.Points.Clear(); return; } // add data to chart if (data != _currentShownData) { _currentShownData = data; stockSeries.Points.Clear(); volumeSeries.Points.Clear(); for (int i = 0; i < bars.Length; ++i) { var bar = bars[i]; stockSeries.Points.AddXY( bar.Time, bar.HighestPrice, bar.LowestPrice, bar.OpenPrice, bar.ClosePrice); volumeSeries.Points.AddXY(bar.Time, bar.Volume); } } // calculate the index of start time and end time in data int startIndex = GetIndexOfTimeInBars(bars, startTime); int endIndex = GetIndexOfTimeInBars(bars, endTime); if (startIndex > endIndex) { int temp = startIndex; startIndex = endIndex; endIndex = temp; } // create scale view to cover start time and end time int position = startIndex - SurroundDataPointCount; int size = endIndex - startIndex + SurroundDataPointCount * 2; position = Math.Max(0, position); size = Math.Min(Math.Max(MinScaleViewSize, size), bars.Length); if (size + position > bars.Length) { position = bars.Length - size; } chartArea.AxisX.ScaleView = new System.Windows.Forms.DataVisualization.Charting.AxisScaleView() { Position = position, Size = size }; // adjust view to accomendate the scale AdjustChartView(); // add annotation var startAnnotation = chartData.Annotations[StartAnnotationIndex]; var endAnnotation = chartData.Annotations[EndAnnotationIndex]; if (addAnnotation) { //startAnnotation.AnchorDataPoint = stockSeries.Points[startIndex]; //endAnnotation.AnchorDataPoint = stockSeries.Points[endIndex]; startAnnotation.AnchorX = startIndex + 1; startAnnotation.AnchorY = bars[startIndex].LowestPrice; endAnnotation.AnchorX = endIndex + 1; endAnnotation.AnchorY = bars[endIndex].HighestPrice; startAnnotation.Visible = true; endAnnotation.Visible = true; } else { //startAnnotation.AnchorDataPoint = null; //endAnnotation.AnchorDataPoint = null; startAnnotation.AnchorX = 0; startAnnotation.AnchorY = 0; endAnnotation.AnchorX = 0; endAnnotation.AnchorY = 0; startAnnotation.Visible = false; endAnnotation.Visible = false; } chartData.Invalidate(); chartData.Update(); }