Оптимизация стратегии по всем возможным значениям индикатора, перестановка - PullRequest
0 голосов
/ 07 апреля 2020

Я боролся с этим в течение нескольких часов, я пытаюсь сгенерировать все возможные комбинации всех параметров индикатора. Предположим, у меня есть индикаторы
Имя возможное значение
sma5 5, 7, 9
sma10 10, 15
sma20 20, 25, 30

Может генерировать все комбинации с простой вложенный цикл for для (sma5 = 5; sma5 <= 9; sma5 = sma5 + 2) <br>для (sma10 = 10; sma10 <= 15; sma10 = sma10 + 5) <br>для (sma20 = 20 ; sma20 <= 30; sma20 = sma20 + 5) <br>Это дало бы 18 возможных комбинаций

, но я хочу сделать немного больше, говоря, что sma5 и sma20 можно переключать, диапазон sma5 теперь 20-30 sma20 диапазон теперь 5-9 Это даст еще 6 комбинаций, если я прав, что составляет 3 !, 2x3

Таким образом, всего будет 6 x 18 = 108 комбинаций

Как мне написать это в чистом коде? Я хочу, чтобы это было как можно более чистым, но не могу понять, потому что я мог бы добавить еще несколько индикаторов, чтобы моя программа была более гибкой для изменения

class StrObject
{
    public string indicName { get; set; }
    public int numbegin { get; set; }
    public int numend { get; set; }
    public int gap { get; set; }
}

class StrObjects : IEnumerable
{
    ArrayList mylist = new ArrayList();

    public StrObject this[int index]
    {
        get { return (StrObject)mylist[index]; }
        set { mylist.Insert(index, value); }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return mylist.GetEnumerator();
    }
}


class Program
{

    static IEnumerable<IEnumerable<T>>
    GetPermutations<T>(IEnumerable<T> list, int length)
    {
        if (length == 1) return list.Select(t => new T[] { t });
        return GetPermutations(list, length - 1)
            .SelectMany(t => list.Where(o => !t.Contains(o)),
                (t1, t2) => t1.Concat(new T[] { t2 }));
    }

    private static void Main()
    {
        int countP = 0, countC = 0;
        const int k = 3;

        StrObjects myObjects = new StrObjects();
        myObjects[0] = new StrObject() { indicName = "sma_5", numbegin = 5, numend=9, gap=2 };
        myObjects[1] = new StrObject() { indicName = "sma_20", numbegin = 20, numend = 30, gap = 5 };
        myObjects[2] = new StrObject() { indicName = "sma_50", numbegin = 50, numend = 60, gap = 5 };

        var n = new[] { myObjects[0].indicName, myObjects[1].indicName, myObjects[2].indicName };

        Console.Write("n: ");
        foreach (var item in n)
        {
            Console.Write("{0} ", item);
        }
        Console.WriteLine();
        Console.WriteLine("k: {0}", k);
        Console.WriteLine();
        Console.WriteLine("===============================");
        Console.WriteLine("Permutations");
        Console.WriteLine("===============================");
        foreach (IEnumerable<string> i in GetPermutations(n, k))
        {
            Console.WriteLine(string.Join(" ", i));
            countC++;
        }
        Console.WriteLine("Count : " + countC);


        Console.ReadKey();
    }
}

'' '

1 Ответ

0 голосов
/ 07 апреля 2020

наконец-то смог вытащить какой-то рабочий код, я не знаю, почему он работает, но он работает вроде кода. по крайней мере он получает то, что я хочу

sma_day, 5,7,9
sma_day10, 10,15
sma_day50, 50,55,60

sma_vol5, 5,7, 9
sma_vol10, 10,15,20
sma_vol20, 20,25,30

psyvalue 30,35,40,45,50
Это должно дать все 87480 комбинаций

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Collections;

namespace optimization
{
class indiObject
{
    public string indicName { get; set; }
    public int numbegin { get; set; }
    public int numend { get; set; }
    public int gap { get; set; }
}

class IndiObjects : IEnumerable
{
    ArrayList mylist = new ArrayList();

    public indiObject this[int index]
    {
        get { return (indiObject)mylist[index]; }
        set { mylist.Insert(index, value); }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return mylist.GetEnumerator();
    }
}

class Program
{
    public static List<Task> tasks;
    private const string pythonpath = @"C:\Python\Scripts\python.exe";
    private const string scriptpath = @"C:\psy-Optimizer.py";
    private const string connectionstr = @"SERVER =localhost;DATABASE=Stock;Trusted_Connection=True";
    public delegate void strategy(Dictionary<string, string> dict);
    public static int processcount = 0;
    public static Task[] tasksArray;
    static void Main(string[] args)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        tasks = new List<Task>();

        int countC = 0;
        const int k = 3;

        IndiObjects myObjects = new IndiObjects();
        myObjects[0] = new indiObject() { indicName = "sma_day5", numbegin = 5, numend = 9, gap = 2 };
        myObjects[1] = new indiObject() { indicName = "sma_day20", numbegin = 20, numend = 30, gap = 5 };
        myObjects[2] = new indiObject() { indicName = "sma_day50", numbegin = 50, numend = 60, gap = 5 };

        IndiObjects myObjects2 = new IndiObjects();
        myObjects2[0] = new indiObject() { indicName = "sma_vol5", numbegin = 5, numend = 9, gap = 2 };
        myObjects2[1] = new indiObject() { indicName = "sma_vol10", numbegin = 10, numend = 19, gap = 5 };
        myObjects2[2] = new indiObject() { indicName = "sma_vol20", numbegin = 20, numend = 30, gap = 5 };

        var var1 = new[] { myObjects[0].indicName, myObjects[1].indicName, myObjects[2].indicName };
        var var2 = new[] { myObjects2[0].indicName, myObjects2[1].indicName, myObjects2[2].indicName };

        foreach (IEnumerable<string> i in GetPermutations(var1, k))
        {
            int[,] loopcount0 = new int[3, 3];
            int count0 = 0;

            foreach (string s in i)
            {
                //Console.WriteLine(s);
                switch (s)
                {
                    case "sma_day5":
                        loopcount0[count0, 0] = myObjects[0].numbegin;
                        loopcount0[count0, 1] = myObjects[0].numend;
                        loopcount0[count0, 2] = myObjects[0].gap;
                        break;
                    case "sma_day20":
                        loopcount0[count0, 0] = myObjects[1].numbegin;
                        loopcount0[count0, 1] = myObjects[1].numend;
                        loopcount0[count0, 2] = myObjects[1].gap;
                        break;
                    case "sma_day50":
                        loopcount0[count0, 0] = myObjects[2].numbegin;
                        loopcount0[count0, 1] = myObjects[2].numend;
                        loopcount0[count0, 2] = myObjects[2].gap;
                        break;
                }
                count0++;
            }
            for (int f1 = loopcount0[0, 0]; f1 <= loopcount0[0, 1]; f1 += loopcount0[0, 2])
                for (int f2 = loopcount0[1, 0]; f2 <= loopcount0[1, 1]; f2 += loopcount0[1, 2])
                    for (int f3 = loopcount0[2, 0]; f3 <= loopcount0[2, 1]; f3 += loopcount0[2, 2])
                       foreach (IEnumerable<string> i2 in GetPermutations(var2, k))
                       {
                            int[,] loopcount = new int [3,3];
                            int count = 0;
                            //Console.WriteLine("sma_day5 " + f1 + "sma_day20" + f2 + "sma_day50" + f3);
                            foreach (string s in i2)
                            {
                                //Console.WriteLine(s);
                                switch (s)
                                {
                                    case "sma_vol5":
                                        loopcount[count, 0] = myObjects2[0].numbegin;
                                        loopcount[count, 1] = myObjects2[0].numend;
                                        loopcount[count, 2] = myObjects2[0].gap;
                                        break;
                                    case "sma_vol10":
                                        loopcount[count, 0] = myObjects2[1].numbegin;
                                        loopcount[count, 1] = myObjects2[1].numend;
                                        loopcount[count, 2] = myObjects2[1].gap;
                                        break;
                                    case "sma_vol20":
                                        loopcount[count, 0] = myObjects2[2].numbegin;
                                        loopcount[count, 1] = myObjects2[2].numend;
                                        loopcount[count, 2] = myObjects2[2].gap;
                                        break;
                                }
                                count++;
                            }
                            for (int f4 = loopcount[0, 0]; f4 <= loopcount[0,1]; f4 += loopcount[0, 2])
                                for (int f5 = loopcount[1, 0]; f5 <= loopcount[1, 1]; f5 += loopcount[1, 2])
                                    for (int f6 = loopcount[2, 0]; f6 <= loopcount[2, 1]; f6 += loopcount[2, 2])
                                        for (int psyvalue = 30; psyvalue <= 50; psyvalue += 5)
                                            for (int atrdist = 5; atrdist <= 5; atrdist++)
                                                for (int day_atrdist = 5; day_atrdist <= 5; day_atrdist++)
                                                {
                                                    try
                                                    {
                                                        dict.Clear();
                                                        dict.Add("--minutefromdate", "2017-01-01");
                                                        dict.Add("--dayfromdate", "2016-01-01");
                                                        dict.Add("--todate", "2022-01-01");
                                                        dict.Add("--sma_day5", f1.ToString());
                                                        dict.Add("--sma_day20", f2.ToString());
                                                        dict.Add("--sma_day50", f3.ToString());
                                                        dict.Add("--lfi", "11");
                                                        dict.Add("--sma_vol5", f4.ToString());
                                                        dict.Add("--sma_vol10", f5.ToString());
                                                        dict.Add("--sma_vol20", f6.ToString());
                                                        dict.Add("--day_atrdist", "5");
                                                        dict.Add("--atrdist", "5");
                                                        dict.Add("--psyvalue", psyvalue.ToString());
                                                        if (countC >= 72893)
                                                        {
                                                            tasks.Add(Task.Factory.StartNew(() => RunBacktrader(dict), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default));
                                                        }
                                                          //  Console.WriteLine("Process ID " + countC++);


                                                        /*
                                                        string str="";
                                                        foreach (KeyValuePair<string, string> kvp in dict)
                                                        {
                                                            str += kvp.Key + "=" + kvp.Value ;
                                                        }
                                                        */
                                                        Console.WriteLine("Process ID " + countC++);
                                                        tasksArray = tasks.Where(t => t != null).ToArray();

                                                        while (tasksArray.Length >= 10)
                                                        {
                                                            var completedTask = Task.WhenAny(tasks).Result;
                                                            tasks.Remove(completedTask);
                                                            Console.WriteLine("A task has been completed with result {0}.", completedTask.Id);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        RecordLog(ex.Message);
                                                    }

                                                }
                        }
            //Console.WriteLine(string.Join(" ", i));
        }
        Console.Read();
    }

    private static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
    {
        if (length == 1) return list.Select(t => new T[] { t });
        return GetPermutations(list, length - 1)
            .SelectMany(t => list.Where(o => !t.Contains(o)),
                (t1, t2) => t1.Concat(new T[] { t2 }));
    }

    private static void RunBacktrader(Dictionary<string, string> dict)
    {
        try
        {
            string paras = "";
            foreach (KeyValuePair<string, string> pp in dict)
            {
                paras += pp.Key + "=" + pp.Value + " ";
            }

            Console.WriteLine("Tasks count " + processcount++);
            string scriptName = scriptpath + " " + paras;

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@pythonpath, @scriptName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }
        catch (Exception ex)
        {
            RecordLog("5 " + ex.Message);
        }

    }

    private static void RecordLog(string message)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionstr))
            {
                SqlCommand sqlcmd = new SqlCommand();
                sqlcmd.Parameters.Add(new SqlParameter("message", message));
                connection.Open();
                sqlcmd.Connection = connection;
                sqlcmd.CommandText = "INSERT INTO [dbo].[optmizationLog] (ExecTime, Steps) VALUES (GETDATE(), CAST(@message as varchar(512)) )";
                sqlcmd.ExecuteNonQuery();
                connection.Close();
            }
        }
        catch (Exception ex)
        {
            Console.Write("duplicate");
        }
    }
}

}

...