Visual Studio中如何将读取的股票文件数据显示到图表中?
问题描述
我正在开发一个基于Visual Studio .NET Framework的WinForms项目,功能是从本地文件读取股票K线数据,点击加载按钮后将数据展示在图表中。目前已完成数据读取和DataGridView展示部分,但对C#不熟悉,不知道主窗体类的connectChart方法里需要写什么代码来实现K线图表展示。
相关代码如下:
主窗体类代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Stock_Project_Loader_Final { public partial class StockLoader : Form { aCandlestickReader candlestickReader = null; List<aCandlestick> listOfCandlesticks = null; public StockLoader() { InitializeComponent(); candlestickReader = new aCandlestickReader(); dataGridView1.DataSource = listOfCandlesticks = new List<aCandlestick>(512); } private void buttonLoad_Click(object sender, EventArgs e) { String Period = String.Empty; if (radioButtonDaily.Checked ) { Period = "Day"; } else if (radioButtonWeekly.Checked) { Period = "Week"; } else { MessageBox.Show("Please select a period"); } listOfCandlesticks = candlestickReader.readStock(textBoxTicker.Text, Period, dateTimePickerStart.Value, dateTimePickerEnd.Value); dataGridView1.DataSource = listOfCandlesticks; connectChart(); } public void connectChart() { //WHAT GOES IN HERE?????????????????????????????????????? } } }
K线数据读取类代码
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace Stock_Project_Loader_Final { public class aCandlestickReader { const string dataFolder = "Stock Data"; public List<aCandlestick> listOfCandlesticks = null; public aCandlestickReader() { listOfCandlesticks = new List<aCandlestick>(256); } public List<aCandlestick> readlistOfCandlesticks(string csvFilename, DateTime startDate, DateTime endDate) { char[] separators = new char[] { '-', ',', '"' }; //Get all the lines as a String array by reading all the lines String[] lines = System.IO.File.ReadAllLines(csvFilename); //Skip the header String header = lines[0]; //use first line to make sure the file is a proper candlestick file if (header == "\"Date\",\"Open\",\"High\",\"Low\",\"Close\",\"Volume\"") { //Create list of candlesticks with enough capacity for number of candlesticks read listOfCandlesticks = new List<aCandlestick>(lines.Length - 1); for (int l = 1; l < lines.Length; ++l) { //Get the lth line String line = lines[l].Trim(); //Split it base on ,-" string[] subStrings = line.Split(separators, StringSplitOptions.RemoveEmptyEntries); //Parse the date info int year = int.Parse(subStrings[0]); int month = int.Parse(subStrings[1]); int day = int.Parse(subStrings[2]); //Build a date object from the first 3 substrings DateTime date = new DateTime(year, month, day); //Compare the date of this line with our range of desired dates if (date.CompareTo(startDate) >= 0 && date.CompareTo(endDate) <= 0) { //Now get the other parts of the line: Open, High, Low, Close, and Volume Decimal open = Decimal.Parse(subStrings[3]); Decimal high = Decimal.Parse(subStrings[4]); Decimal low = Decimal.Parse(subStrings[5]); Decimal close = Decimal.Parse(subStrings[6]); long volume = long.Parse(subStrings[7]); open = Math.Round(open, 2); high = Math.Round(high, 2); low = Math.Round(low, 2); close = Math.Round(close, 2); //Create new candlestick with proper parameters aCandlestick candleStick = new aCandlestick(date, open, high, low, close, volume); //Add newly created candlestick to the list of listOfCandlesticks listOfCandlesticks.Add(candleStick); } } } return listOfCandlesticks; } public List<aCandlestick> readStock(String ticker, String period, DateTime startDate, DateTime endDate) { //Create filename for the ticker by concatenating the dataFolder name, ticker name, period and extension String csvFilename = dataFolder + @"\\" + ticker + "-" + period + ".csv"; //Read the candlesticks and return them as the listOfCandlestick member listOfCandlesticks = readlistOfCandlesticks(csvFilename, startDate, endDate); return listOfCandlesticks; } } }
K线实体类代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stock_Project_Loader_Final { public class aCandlestick { public DateTime date { get; set; } public Decimal open { get; set; } public Decimal high { get; set; } public Decimal low { get; set; } public Decimal close { get; set; } public long volume { get; set; } public aCandlestick() { date = DateTime.Now; open = 0; high = 0; low = 0; close = 0; volume = 0; } public aCandlestick(DateTime date, Decimal open, Decimal high, Decimal low, Decimal close, long volume) { this.date = date; this.open = open; this.high = high; this.low = low; this.close = close; this.volume = volume; } } }
解决方案
首先确保你的WinForms窗体上已经拖拽添加了Chart控件(命名为chartStock,可自行修改),并给项目添加System.Windows.Forms.DataVisualization引用(右键项目→添加→引用→勾选该程序集)。之后在connectChart方法中编写以下代码:
using System.Windows.Forms.DataVisualization.Charting; public void connectChart() { // 清空图表现有数据 chartStock.Series.Clear(); // 无数据时直接返回 if (listOfCandlesticks == null || listOfCandlesticks.Count == 0) { MessageBox.Show("No data to display"); return; } // 创建K线系列并设置类型 Series candleSeries = new Series("Candlesticks"); candleSeries.ChartType = SeriesChartType.Candlestick; // 配置数据映射:X轴为日期,Y轴对应开盘/最高/最低/收盘 candleSeries.XValueType = ChartValueType.DateTime; candleSeries.YValuesPerPoint = 4; // 遍历K线数据,添加到图表系列 foreach (var candle in listOfCandlesticks) { double open = Convert.ToDouble(candle.open); double high = Convert.ToDouble(candle.high); double low = Convert.ToDouble(candle.low); double close = Convert.ToDouble(candle.close); candleSeries.Points.AddXY(candle.date, open, high, low, close); } // 设置K线颜色:上涨绿,下跌红 candleSeries["PriceUpColor"] = "Green"; candleSeries["PriceDownColor"] = "Red"; // 将系列添加到图表 chartStock.Series.Add(candleSeries); // 配置图表区域样式 ChartArea chartArea = chartStock.ChartAreas[0]; chartArea.AxisX.LabelStyle.Format = "yyyy-MM-dd"; chartArea.AxisX.MajorGrid.Enabled = false; chartArea.AxisY.Title = "Price"; chartArea.AxisY.MajorGrid.LineColor = Color.LightGray; // 设置图表标题 chartStock.Titles.Clear(); chartStock.Titles.Add($"Stock: {textBoxTicker.Text}"); }
关键说明
- 代码中使用WinForms自带的Chart控件实现K线图,无需额外第三方库
- 将Decimal类型转换为double是因为Chart控件仅支持数值类型为double
- 配置了基础的K线样式和图表布局,可根据需求调整颜色、网格线、标签格式等
内容的提问来源于stack exchange,提问作者Verminator25
相关产品推荐
相关产品推荐

