用.NET语言写出计算股票技术指标DMI的函数,第一个参数为datatable类型,其他参数为int型;日期列名为“日期”,开盘价列名为“开盘”,收盘价列名为“收盘”,最高价列名为“最高”,最低价列名为“最低”,返回值为datatable类型。所有double类型保留3位小数。
时间: 2024-03-27 15:41:10 浏览: 102
Trady:Trady是一个方便的库,用于计算技术指标,它的目标是成为一个自动交易系统,提供股票数据馈送,指标计算,策略建立和自动交易。 它基于.NET Standard 2.0构建
好的,我会用.NET语言写出计算股票技术指标DMI的函数,以下是代码:
```csharp
public static DataTable CalculateDMI(DataTable dt, int n, int m)
{
DataTable resultDt = new DataTable();
resultDt.Columns.Add("日期", typeof(string));
resultDt.Columns.Add("PDI", typeof(double));
resultDt.Columns.Add("MDI", typeof(double));
resultDt.Columns.Add("ADX", typeof(double));
resultDt.Columns.Add("ADXR", typeof(double));
// 计算TR、HD和LD
double[] trArr = new double[dt.Rows.Count];
double[] hdArr = new double[dt.Rows.Count];
double[] ldArr = new double[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
double h = Convert.ToDouble(dt.Rows[i]["最高"]);
double l = Convert.ToDouble(dt.Rows[i]["最低"]);
double pc = i > 0 ? Convert.ToDouble(dt.Rows[i - 1]["收盘"]) : 0;
double tr = Math.Max(h - l, Math.Max(Math.Abs(h - pc), Math.Abs(l - pc)));
double hd = h - pc;
double ld = pc - l;
trArr[i] = tr;
hdArr[i] = hd;
ldArr[i] = ld;
}
// 计算PDI、MDI、ADX和ADXR
double[] pdiArr = new double[dt.Rows.Count];
double[] mdiArr = new double[dt.Rows.Count];
double[] dxArr = new double[dt.Rows.Count];
double[] adxArr = new double[dt.Rows.Count];
double[] adxrArr = new double[dt.Rows.Count];
double pdi = 0;
double mdi = 0;
double dx = 0;
double adx = 0;
double sumPdi = 0;
double sumMdi = 0;
double sumDx = 0;
double sumAdx = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i < n)
{
pdiArr[i] = 0;
mdiArr[i] = 0;
dxArr[i] = 0;
adxArr[i] = 0;
adxrArr[i] = 0;
continue;
}
if (i == n)
{
sumPdi = pdiArr.Take(n).Sum();
sumMdi = mdiArr.Take(n).Sum();
sumDx = dxArr.Take(n).Sum();
sumAdx = adxArr.Take(n).Sum();
}
else
{
sumPdi = sumPdi - pdiArr[i - n - 1] + pdiArr[i - 1];
sumMdi = sumMdi - mdiArr[i - n - 1] + mdiArr[i - 1];
sumDx = sumDx - dxArr[i - n - 1] + dxArr[i - 1];
sumAdx = sumAdx - adxArr[i - n - 1] + adxArr[i - 1];
}
double trSum = trArr.Skip(i - n).Take(n).Sum();
double hdSum = hdArr.Skip(i - n).Take(n).Sum();
double ldSum = ldArr.Skip(i - n).Take(n).Sum();
pdi = hdSum / trSum * 100;
mdi = ldSum / trSum * 100;
double diff = Math.Abs(pdi - mdi);
double sum = pdi + mdi;
dx = diff / sum * 100;
adx = sumDx / n;
adxr = (adx + adxArr[i - 1]) / 2;
pdiArr[i] = Math.Round(pdi, 3);
mdiArr[i] = Math.Round(mdi, 3);
dxArr[i] = Math.Round(dx, 3);
adxArr[i] = Math.Round(adx, 3);
adxrArr[i] = Math.Round(adxr, 3);
}
// 将计算结果添加到结果DataTable中
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = resultDt.NewRow();
row["日期"] = dt.Rows[i]["日期"];
row["PDI"] = pdiArr[i];
row["MDI"] = mdiArr[i];
row["ADX"] = adxArr[i];
row["ADXR"] = adxrArr[i];
resultDt.Rows.Add(row);
}
return resultDt;
}
```
其中,n为DMI的周期,m为ADX的周期。计算过程中,先计算每日的TR、HD和LD,再根据n计算PDI、MDI、DX、ADX和ADXR。最后将计算结果添加到结果DataTable中,并返回该DataTable。
希望这个函数能够满足你的需求,如果有任何问题,欢迎随时向我提出。
阅读全文