I am trying to get this code to run faster as it has billions of combinations. I need to look through four loops and based on those parameters find the highest profit. The dictionary could have 500 records and I usually use excel to find patterns of the top performing settings and after a few minutes I end up with about 100 entries. What approach do you guys think its best for me or what recommendations do you have?
using System;
using System.Collections.Concurrent;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public class Stock {
public double PNL { get; set; }
public double OD { get; set; }
public double DR { get; set; }
public double Volume { get; set; }
public double Liquidity { get; set; }
public Stock(double iPNL, double iOD, double iDR, double iVolume, double iLiquidity) {
PNL = iPNL;
OD = iOD;
DR = iDR;
Volume = iVolume;
Liquidity = iLiquidity;
}
}
private ConcurrentDictionary<string, Stock> StockData = new();
private void button1_Click(object sender, EventArgs e) {
StockData["A"] = new Stock(-109, 60, 0.92, 32, 5.99);
StockData["B"] = new Stock(41, 25, 0.96, 37, 6.75);
StockData["C"] = new Stock(41, 62, 1.12, 79, 8.4);
long iLoops = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
double iODMax = 999;
double iDRMax = 1500;
double iVolMax = 999;
double iLiqMax = 2000;
double PNL = 0;
for (int iODMin = 0; iODMin <= iODMax; iODMin += 6) {
for (double iDRMin = 1; iDRMin <= iDRMax; iDRMin += 6) {
for (int iVolMin = 0; iVolMin <= iVolMax; iVolMin += 6) {
for (double iLiqMin = 1; iLiqMin <= iLiqMax; iLiqMin += 6) {
iLoops += 1;
var aaaa = StockData.Where(n => n.Value.OD >= iODMin && n.Value.OD <= iODMax &&
n.Value.DR >= iDRMin && n.Value.DR <= (iDRMax / 100) &&
n.Value.Liquidity >= iLiqMin && n.Value.Liquidity <= (iLiqMax / 100) &&
n.Value.Volume >= iVolMin && n.Value.Volume <= iVolMax).FirstOrDefault();
if (aaaa.Value != null) {
PNL += aaaa.Value.PNL;
}
}
}
}
}
stopwatch.Stop();
Debug.Print(stopwatch.Elapsed.ToString() + " | " + iLoops.ToString("#,#") + " | " + PNL.ToString("#,#"));
}
}
}