用.NET语言写一个计算股票技术指标DMI的函数,第一个参数为datatable类型,另外两个参数为int型;日期列名为“日期”,开盘价列名为“开盘”,收盘价列名为“收盘”,最高价列名为“最高”,最低价列名为“最低”,返回值为datatable类型,返回值包含PDI,MDI,ADX,ADXR等列,double类型全部四舍五入保留3位小数。
时间: 2024-03-27 09:41:27 浏览: 40
Trady:Trady是一个方便的库,用于计算技术指标,它的目标是成为一个自动交易系统,提供股票数据馈送,指标计算,策略建立和自动交易。 它基于.NET Standard 2.0构建
好的,以下是用.NET语言写的计算DMI指标的函数:
```csharp
public static DataTable CalculateDMI(DataTable table, int n, int m)
{
// 计算TR、+DI、-DI、DX
double[] tr = new double[table.Rows.Count];
double[] pdm = new double[table.Rows.Count];
double[] mdm = new double[table.Rows.Count];
double[] pdi = new double[table.Rows.Count];
double[] mdi = new double[table.Rows.Count];
double[] dx = new double[table.Rows.Count];
for (int i = 1; i < table.Rows.Count; i++)
{
double h1 = Convert.ToDouble(table.Rows[i]["最高"]);
double l1 = Convert.ToDouble(table.Rows[i]["最低"]);
double c1 = Convert.ToDouble(table.Rows[i]["收盘"]);
double h2 = Convert.ToDouble(table.Rows[i - 1]["最高"]);
double l2 = Convert.ToDouble(table.Rows[i - 1]["最低"]);
double c2 = Convert.ToDouble(table.Rows[i - 1]["收盘"]);
tr[i] = Math.Max(Math.Max(h1 - l1, Math.Abs(h1 - c2)), Math.Abs(l1 - c2));
pdm[i] = Math.Max(h1 - h2, 0);
mdm[i] = Math.Max(l2 - l1, 0);
if (pdm[i] > mdm[i])
{
pdm[i] -= mdm[i];
mdm[i] = 0;
}
else
{
mdm[i] -= pdm[i];
pdm[i] = 0;
}
}
for (int i = n; i < table.Rows.Count; i++)
{
double sum_tr = 0;
double sum_pdm = 0;
double sum_mdm = 0;
for (int j = i - n + 1; j <= i; j++)
{
sum_tr += tr[j];
sum_pdm += pdm[j];
sum_mdm += mdm[j];
}
pdi[i] = 100 * sum_pdm / sum_tr;
mdi[i] = 100 * sum_mdm / sum_tr;
if (pdi[i] + mdi[i] == 0)
{
dx[i] = 0;
}
else
{
dx[i] = 100 * Math.Abs(pdi[i] - mdi[i]) / (pdi[i] + mdi[i]);
}
}
// 计算ADX、ADXR
double[] adx = new double[table.Rows.Count];
double[] adxr = new double[table.Rows.Count];
for (int i = m; i < table.Rows.Count; i++)
{
double sum_dx = 0;
for (int j = i - m + 1; j <= i; j++)
{
sum_dx += dx[j];
}
adx[i] = sum_dx / m;
adxr[i] = (adx[i] + adx[i - m]) / 2;
}
// 返回结果
DataTable result = new DataTable();
result.Columns.Add("日期", typeof(DateTime));
result.Columns.Add("PDI", typeof(double));
result.Columns.Add("MDI", typeof(double));
result.Columns.Add("ADX", typeof(double));
result.Columns.Add("ADXR", typeof(double));
for (int i = m; i < table.Rows.Count; i++)
{
DataRow row = result.NewRow();
row["日期"] = table.Rows[i]["日期"];
row["PDI"] = Math.Round(pdi[i], 3);
row["MDI"] = Math.Round(mdi[i], 3);
row["ADX"] = Math.Round(adx[i], 3);
row["ADXR"] = Math.Round(adxr[i], 3);
result.Rows.Add(row);
}
return result;
}
```
其中,n和m分别为计算DMI指标的参数,table为输入的股票数据表,返回值为包含PDI、MDI、ADX、ADXR等列的数据表。函数内部首先计算TR、+DI、-DI、DX等指标,然后根据这些指标计算ADX和ADXR,并将结果保存在结果数据表中。注意,函数内部的所有double类型都使用了四舍五入保留3位小数。
阅读全文