用.NET语言写出计算股票技术指标DMI的函数,第一个参数为datatable类型,其他参数为int型;日期列名为“日期”,开盘价列名为“开盘”,收盘价列名为“收盘”,最高价列名为“最高”,最低价列名为“最低”,返回值为datatable类型,
时间: 2024-03-27 16:38:02 浏览: 102
好的,下面是用.NET语言写出计算股票技术指标DMI的函数的代码:
```csharp
public static DataTable CalculateDMI(DataTable dt, int n, int m)
{
DataTable resultDt = new DataTable();
resultDt.Columns.Add("日期");
resultDt.Columns.Add("PDI");
resultDt.Columns.Add("MDI");
resultDt.Columns.Add("ADX");
resultDt.Columns.Add("ADXR");
double[] tr = new double[dt.Rows.Count];
double[] dmP = new double[dt.Rows.Count];
double[] dmM = new double[dt.Rows.Count];
double[] diP = new double[dt.Rows.Count];
double[] diM = new double[dt.Rows.Count];
double[] dx = new double[dt.Rows.Count];
double[] adx = new double[dt.Rows.Count];
double[] adxr = new double[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
double tr1 = Math.Max(Math.Abs(Convert.ToDouble(dt.Rows[i]["最高"]) - Convert.ToDouble(dt.Rows[i]["最低"])), Math.Abs(Convert.ToDouble(dt.Rows[i]["最高"]) - Convert.ToDouble(dt.Rows[i]["收盘"])));
double tr2 = Math.Abs(Convert.ToDouble(dt.Rows[i]["最低"]) - Convert.ToDouble(dt.Rows[i]["收盘"]));
tr[i] = Math.Max(tr1, tr2);
if (i > 0)
{
dmP[i] = Convert.ToDouble(dt.Rows[i]["最高"]) - Convert.ToDouble(dt.Rows[i - 1]["最高"]);
dmM[i] = Convert.ToDouble(dt.Rows[i - 1]["最低"]) - Convert.ToDouble(dt.Rows[i]["最低"]);
if (dmP[i] > dmM[i] && dmP[i] > 0)
{
diP[i] = dmP[i];
}
else
{
diP[i] = 0;
}
if (dmM[i] > dmP[i] && dmM[i] > 0)
{
diM[i] = dmM[i];
}
else
{
diM[i] = 0;
}
}
if (i >= n)
{
double sumTR = 0;
double sumDIP = 0;
double sumDIM = 0;
for (int j = i; j > i - n; j--)
{
sumTR += tr[j];
sumDIP += diP[j];
sumDIM += diM[j];
}
double pdi = sumDIP / sumTR * 100;
double mdi = sumDIM / sumTR * 100;
double diff = Math.Abs(pdi - mdi);
double sum = pdi + mdi;
dx[i] = diff / sum * 100;
if (i >= n + m - 1)
{
double sumDX = 0;
for (int k = i; k > i - m; k--)
{
sumDX += dx[k];
}
adx[i] = sumDX / m;
adxr[i] = (adx[i] + adx[i - m]) / 2;
}
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i >= n + m - 1)
{
DataRow dr = resultDt.NewRow();
dr["日期"] = dt.Rows[i]["日期"];
dr["PDI"] = diP[i];
dr["MDI"] = diM[i];
dr["ADX"] = adx[i];
dr["ADXR"] = adxr[i];
resultDt.Rows.Add(dr);
}
}
return resultDt;
}
```
其中,n和m分别为计算DMI指标所需的天数,tr为真实波幅数组,dmP为上升动向数组,dmM为下降动向数组,diP为上升指标数组,diM为下降指标数组,dx为动向指标数组,adx为平均动向指标数组,adxr为平均动向指标的平均数组。最终返回的是一个包含PDI、MDI、ADX、ADXR指标的DataTable类型。
阅读全文