用.NET语言写出计算股票技术指标KDJ,返回值为datatable类型,double类型全部四舍五入保留3位小数。
时间: 2023-05-17 09:07:37 浏览: 97
【ASP.NET编程知识】C#将DataTable转化为ListT.docx
以下是用.NET语言写出计算股票技术指标KDJ的代码,返回值为datatable类型,double类型全部四舍五入保留3位小数:
```csharp
using System;
using System.Data;
namespace KDJ
{
public class KDJCalculator
{
public static DataTable CalculateKDJ(DataTable dataTable, int n, int m1, int m2)
{
DataTable resultTable = new DataTable();
resultTable.Columns.Add("K", typeof(double));
resultTable.Columns.Add("D", typeof(double));
resultTable.Columns.Add("J", typeof(double));
double[] high = new double[dataTable.Rows.Count];
double[] low = new double[dataTable.Rows.Count];
double[] close = new double[dataTable.Rows.Count];
double[] rsv = new double[dataTable.Rows.Count];
double[] k = new double[dataTable.Rows.Count];
double[] d = new double[dataTable.Rows.Count];
double[] j = new double[dataTable.Rows.Count];
for (int i = 0; i < dataTable.Rows.Count; i++)
{
high[i] = Convert.ToDouble(dataTable.Rows[i]["High"]);
low[i] = Convert.ToDouble(dataTable.Rows[i]["Low"]);
close[i] = Convert.ToDouble(dataTable.Rows[i]["Close"]);
if (i < n - 1)
{
rsv[i] = 0;
k[i] = 0;
d[i] = 0;
j[i] = 0;
}
else
{
double maxHigh = double.MinValue;
double minLow = double.MaxValue;
for (int j = i - n + 1; j <= i; j++)
{
if (high[j] > maxHigh)
{
maxHigh = high[j];
}
if (low[j] < minLow)
{
minLow = low[j];
}
}
rsv[i] = (close[i] - minLow) / (maxHigh - minLow) * 100;
if (i == n - 1)
{
k[i] = rsv[i];
d[i] = k[i];
}
else
{
k[i] = (m1 - 1) * d[i - 1] / m1 + rsv[i] / m1;
d[i] = (m2 - 1) * d[i - 1] / m2 + k[i] / m2;
}
j[i] = 3 * k[i] - 2 * d[i];
}
DataRow row = resultTable.NewRow();
row["K"] = Math.Round(k[i], 3);
row["D"] = Math.Round(d[i], 3);
row["J"] = Math.Round(j[i], 3);
resultTable.Rows.Add(row);
}
return resultTable;
}
}
}
```
其中,n为KDJ指标的周期,m1为平滑因子1,m2为平滑因子2。使用时,可以将股票数据存储在一个DataTable中,然后调用CalculateKDJ方法进行计算,返回一个包含KDJ指标的DataTable。
阅读全文