如何将DataTable转换为Skender.Stock.Indicators所需的IEnumerable<Quote>
实现方法
首先确认你的项目已正确安装引用Skender.Stock.Indicators的NuGet包,转换函数可直接参考如下实现:
using Skender.Stock.Indicators; using System.Data; using System.Globalization; public IEnumerable<Quote> ConvertDataTableToQuotes(DataTable klineDt) { List<Quote> quotes = new List<Quote>(); // 遍历K线数据表的每一行 foreach (DataRow row in klineDt.Rows) { // 转换日期:适配你表中MM/dd/yy的日期格式 DateTime tradeDate = DateTime.ParseExact( row["date"].ToString(), "MM/dd/yy", CultureInfo.InvariantCulture); // 转换价格类字段:去掉$符号后转decimal类型 decimal openPrice = decimal.Parse( row["open"].ToString().Replace("$", ""), CultureInfo.InvariantCulture); decimal highPrice = decimal.Parse( row["high"].ToString().Replace("$", ""), CultureInfo.InvariantCulture); decimal lowPrice = decimal.Parse( row["low"].ToString().Replace("$", ""), CultureInfo.InvariantCulture); decimal closePrice = decimal.Parse( row["close"].ToString().Replace("$", ""), CultureInfo.InvariantCulture); // 转换成交量:去掉千位分隔逗号后转long类型 long tradeVolume = long.Parse( row["volume"].ToString().Replace(",", ""), CultureInfo.InvariantCulture); // 组装成库要求的Quote对象 quotes.Add(new Quote { Date = tradeDate, Open = openPrice, High = highPrice, Low = lowPrice, Close = closePrice, Volume = tradeVolume }); } return quotes; }
使用示例
你可以直接用这个函数替换官方示例里的自定义函数调用:
// 传入你存储K线数据的DataTable即可 DataTable myKlineTable = GetYourOriginalDataTable(); IEnumerable<Quote> quotes = ConvertDataTableToQuotes(myKlineTable);
注意事项
- 若后续你的DataTable日期格式发生变化,需要对应调整
ParseExact方法里的格式字符串 - 若表中存在空值、异常值,建议提前加空值判断和异常捕获逻辑,避免运行时报错
- 转换后的结果可以直接传入库的各类技术指标计算方法使用
内容的提问来源于stack exchange,提问作者goku salvador
相关产品推荐
相关产品推荐

