public static void tests() { BackTest.run(); return; }
static int Test() { BackTest.Config cfg = new BackTest.Config(); cfg.data_level = "tk"; cfg.begin_date = 20180101; cfg.end_date = 20180201; BackTest.Run(cfg, CreateStralet); return(0); }
private string AktualRV(BackTest obchod) { var opt1 = OptionData.Where(x => x.QuoteDate == dateTimePicker1.Value && x.ExpirationDate == obchod.ExpirationDate) .OrderBy(x => x.Strike) .ToList(); var opt2 = OptionData.Where(x => x.QuoteDate == dateTimePicker1.Value && x.ExpirationDate == obchod.ExpirationDate2) .OrderBy(x => x.Strike) .ToList(); return(jadro.GetAktualRv(opt1, opt2).ToString()); }
private static void DoMainBackTest() { var eventBus = new QueuedEventBus(); var dataSource = CsvDataSource.CreateFromFiles("Data\\Min1", new[] { Symbols.Sber, Symbols.Vtbr }); var marketData = new ComposedMarketData(dataSource.Bars); var bars = new HistoricDataHandler(eventBus, marketData); var strategy = new BuyAndHoldStrategy(eventBus, bars); var executionHandler = new SimulatedExecutionHandler(eventBus, bars); var portfolio = new NaivePortfolio(eventBus, bars, 10000m); var backTest = new BackTest(eventBus, bars, strategy, portfolio, executionHandler); backTest.SimulateTrading(); }
private string JeItm(BackTest obchod) { if (obchod.Optiontype == "AKCIE") { return(""); } if ((obchod.Optiontype == "CALL" && obchod.Strike < double.Parse(lblPrice.Text)) || (obchod.Optiontype == "PUT" && obchod.Strike > double.Parse(lblPrice.Text))) { return(true.ToString()); } return(false.ToString()); }
public static void Optimise(string strategyName, string dllPath, string logPath = null, string tradesPath = null, string reportPath = null) { _logPath = logPath; _tradesPath = tradesPath; _reportPath = reportPath; try { BackTest bt = new BackTest(OnCompleteBackTest, new MessageDelegate(DisplayMessage)); bt.Run(strategyName, dllPath, true); } catch (Exception ex) { Console.WriteLine(ex.Message, MessageType.Error); } }
static void Test() { var begin_time = DateTime.Now; BackTest.Config cfg = new BackTest.Config(); cfg.dapi_addr = "ipc://tqc_10001"; cfg.data_level = "tk"; cfg.begin_date = 20180101; cfg.end_date = 20180516; BackTest.Run(cfg, CreateStralet); var used_time = System.DateTime.Now - begin_time; Console.WriteLine("used_time: " + used_time.TotalSeconds); }
static void Main(string[] args) { Debug.LogInfo(WingSYS.info()); Debug.consol(WingSYS.info()); tmpPath = Directory.GetCurrentDirectory() + @"\tmp\"; Console.WriteLine("Directory.GetCurrentDirectory(); = " + Directory.GetCurrentDirectory()); System.IO.Directory.CreateDirectory(tmpPath); ftnn = new FTNN(); ftnn.init(); /*Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); * System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.10.212"); * System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 11111); * soc.Connect(remoteEP); * //Start sending stuf.. * byte[] byData = System.Text.Encoding.ASCII.GetBytes("{\"Protocol\":\"1007\",\"ReqParam\":{\"QueryAllSocket\":\"0\"},\"Version\":\"1\"}\r\n"); * soc.Send(byData); * System.Diagnostics.Debug.WriteLine("----"); * byte[] buffer = new byte[1024]; * int iRx = soc.Receive(buffer); * char[] chars = new char[iRx]; * * System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); * int charLen = d.GetChars(buffer, 0, iRx, chars, 0); * System.String recv = new System.String(chars); * * System.Diagnostics.Debug.WriteLine("----"); * System.Diagnostics.Debug.WriteLine(recv); * System.Diagnostics.Debug.WriteLine("----"); * soc.Disconnect(false);*/ //Task.Run(() => { Application.Run(new TrackSell()); }); //Task.Run(() => { Application.Run(new mainForm()); }); Console.WriteLine("BackTest start ..."); BackTest bt = new BackTest(); bt.init(); Console.WriteLine("BackTest done ..."); Console.ReadKey(); Application.Run(new chartView01()); }
static void Main(string[] args) { //PARAMS BackTestRequest request = new BackTestRequest { // TradingPairs = new List <string> { "sysbtc" }, From = new DateTime(2020, 01, 29), To = new DateTime(2020, 07, 29), Interval = TimeInterval.Days_1, Algorthm = TradingAlgorthm.Macd, StartAmount = 0.5m, TradingAmount = 0.25m, OrderType = OrderType.LIMIT }; //to start back testing, load the first 100 candles to build the relavent indicators //then loop though the remianing candles to simulate live trade streaming. //the system can then make decisions at which points to buy and sell (simple SMA strategy to start with). //once the processing has been completed the result are displayed, each trade with buy price and sell price and percentage profit. var backTest = new BackTest(request); backTest.Log += LogTrade; //TODO make this process ASYNC. Console.WriteLine($"Starting Amount: {request.StartAmount}btc"); backTest.StartTrading(); backTest.FinishTrading(); Console.WriteLine($"StartTime: {backTest.StartTime} FinishTime: {backTest.FinishTime}"); DisplayTrades(request.TradingResults); Console.WriteLine($"BTC Finishing Amount: {request.FinalAmount}btc"); Console.WriteLine($"Total PNL - {request.TradingResults.Sum(x=>x.Pnl)}"); Console.WriteLine($"Total % profit - {CalculatePercent(request)}"); Console.WriteLine($"Win/Loss - Total - {CalculateRatio(request)}"); Console.ReadKey(); }
private void btnLoadFile_Click(object sender, EventArgs e) { Classification.IsClassifier = cBoxClassification.Checked; if (BackTestSelector.ShowDialog() != DialogResult.OK) { return; } BackTest = new BackTest(); BackTest.FeatureEvaluation = cboxFeatureEvaluation.Checked; SignalProcessor.IsBackTest = true; BackTest.MaxSpeed = cBoxBackTestWait.Checked; // attach event handlers for back test BackTest.OnBackTestBandDataRecieved += SignalProcessor.OnBandPowerRecieved; BackTest.OnBackTestEEGDataRecieved += SignalProcessor.OnEEGDataReceived; if (!BackTest.FeatureEvaluation) { Utils.UserMessage("Backtest will start after dialogue is closed.", messageType: Globals.MessageTypes.Status); } new Thread(() => { BackTest.HandleRecords(BackTestSelector.OpenFile()); if (BackTest.FeatureEvaluation) { while (Classification.ClassificationElectrodes.Count > 0) { SignalProcessor.IsBackTest = true; Classification.IsClassifier = cBoxClassification.Checked; Trainer.PredictorPointsTrainRaw.Clear(); Trainer.FrequencyLabelsRaw.Clear(); Classification.ClassificationElectrodes.RemoveAt(Classification.ClassificationElectrodes.Count - 1); BackTest.HandleRecords(BackTestSelector.OpenFile()); } } Utils.UserMessage("Backtesting Finished", messageType: Globals.MessageTypes.Status); }) { IsBackground = true }.Start(); }
private void button4_Click(object sender, EventArgs e) { //initialize the cursor to waiting while updating //Cursor = Cursors.WaitCursor; Cursor = Cursors.WaitCursor; string sourcePath = System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"]; string destPath = System.Configuration.ConfigurationManager.AppSettings["DestDirectory"]; string ticker = textBox1.Text; int holdDays = int.Parse(textBox3.Text); double cutoff = double.Parse(textBox4.Text); int rollingDays = int.Parse(textBox5.Text); //instantiate a new back test for the symbol BackTest test = new BackTest(ticker, sourcePath, cutoff); test.BackTestLongShort(holdDays, rollingDays); //update the database for the test results via Entity Framework try { using (NetEntities db = new NetEntities()) { //use a stored procedure to delete all the data in the database that matches the symbol db.DeleteData(ticker); } string sql = "Select * from Table5"; SQLConnection Test1 = new SQLConnection(); Test1.ExecuteSelect(sql, test.DT); } catch { Cursor = Cursors.Default; } Cursor = Cursors.Default; }
private void button1_Click(object sender, EventArgs e) { string sourcePath = System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"]; string destPath = System.Configuration.ConfigurationManager.AppSettings["DestDirectory"]; string ticker = textBox1.Text; int holdDays = 0; double cutoff = 0.00; int rollingDays = 0; try { holdDays = int.Parse(textBox3.Text); cutoff = double.Parse(textBox4.Text); rollingDays = int.Parse(textBox5.Text); } catch { MessageBox.Show("Inputs are in the wrong format - Try again!"); //Application.Run(new Test.Form1()); Application.ExitThread(); Application.Exit(); Application.Restart(); Environment.Exit(0); } Cursor = Cursors.WaitCursor; //instantiate a new back test for the symbol BackTest test = new BackTest(ticker, sourcePath, cutoff); test.BackTestLongShort(holdDays, rollingDays); //bind data to the data grid BindingSource bSource = new BindingSource(); bSource.DataSource = test.DT; dataGridView1.DataSource = bSource; DataRow last = test.DT.Rows[test.DT.Rows.Count - 1]; double zroll = Convert.ToDouble(last["ZscoreRolling"]); textBox6.Text = Convert.ToString(Math.Round((zroll * 1), 4)); double zstatic = Convert.ToDouble(last["ZscoreStatic"]); textBox2.Text = Convert.ToString(Math.Round((zstatic * 1), 4)); textBox7.Text = Convert.ToString(Math.Round((cutoff * 1), 4)); textBox8.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test.DT) * 1), 4)); textBox9.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreStaticCount(test.DT) * 1), 4)); textBox10.Text = Convert.ToString(Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000), 4)); double RealCum = Convert.ToDouble(last["CumRealPNLrollHold"]); textBox11.Text = Convert.ToString(Math.Round((RealCum * 100), 4)); textBox12.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test.DT) / holdDays), 0)); if (Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000), 4) > 0) { textBox13.Text = Convert.ToString(Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test.DT) / holdDays) / (MathFunctions.ZscoreRollCount(test.DT) / holdDays))) * 100, 4))); } if (Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000), 4) < 0) { textBox13.Text = Convert.ToString(-1 * Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test.DT) / holdDays) / (MathFunctions.ZscoreRollCount(test.DT) / holdDays))) * 100, 4))); } textBox14.Text = Convert.ToString(Math.Round((MathFunctions.SharpePNLrollHold(test.DT)), 4)); textBox15.Text = Convert.ToString(Math.Round((MathFunctions.StdDevAllPNLrollHold(test.DT) * Math.Sqrt(260) * 100), 4)); double aclose = Convert.ToDouble(last["AdjustedClose"]); textBox16.Text = Convert.ToString(Math.Round((aclose * 1), 2)); //double zroll = Convert.ToDouble(last["ZscoreRolling"]); textBox28.Text = Convert.ToString(Math.Round((zroll * 1), 4)); //double zstatic = Convert.ToDouble(last["ZscoreStatic"]); textBox27.Text = Convert.ToString(Math.Round((zstatic * 1), 4)); textBox26.Text = Convert.ToString(Math.Round((cutoff * 1), 4)); textBox25.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test.DT) * 1), 4)); textBox24.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreStaticCount(test.DT) * 1), 4)); textBox23.Text = Convert.ToString(Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000 * -1), 4)); //double RealCum = Convert.ToDouble(last["CumRealPNLrollHold"]); textBox22.Text = Convert.ToString(Math.Round((RealCum * -100), 4)); textBox21.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test.DT) / holdDays), 0)); if (Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000 * -1), 4) > 0) { textBox20.Text = Convert.ToString(Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test.DT) / holdDays) / (MathFunctions.ZscoreRollCount(test.DT) / holdDays))) * 100, 4))); } if (Math.Round((MathFunctions.AverageAllPNLrollHold(test.DT) * 26000 * -1), 4) < 0) { textBox20.Text = Convert.ToString(-1 * Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test.DT) / holdDays) / (MathFunctions.ZscoreRollCount(test.DT) / holdDays))) * 100, 4))); } textBox19.Text = Convert.ToString(Math.Round((MathFunctions.SharpePNLrollHold(test.DT) * -1), 4)); textBox18.Text = Convert.ToString(Math.Round((MathFunctions.StdDevAllPNLrollHold(test.DT) * Math.Sqrt(260) * 100), 4)); //double aclose = Convert.ToDouble(last["AdjustedClose"]); textBox17.Text = Convert.ToString(Math.Round((aclose * 1), 2)); /* * bind data to a chart using LINQ and the * data table property for the BackTest data table instance */ chart1.Series[0].Points.Clear(); var d = from data in test.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), ZscoreRolling = data.Field <Object>("ZscoreRolling") }; foreach (var item in d) { if (item.Date != null && item.ZscoreRolling != null) { chart1.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.ZscoreRolling); } } chart1.DataBind(); chart2.Series[0].Points.Clear(); chart2.Series[1].Points.Clear(); var dd = from data in test.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), AdjustedClose = data.Field <Object>("AdjustedClose"), RollingAverage = data.Field <Double?>("RollingAverage") }; foreach (var item in dd) { if (item.Date != null && item.AdjustedClose != null /*&& item.RollingAverage != null*/) { chart2.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.AdjustedClose); chart2.Series["Series2"].Points.AddXY(item.Date.Date.ToString("d"), item.RollingAverage); } } chart2.DataBind(); chart3.Series[0].Points.Clear(); var ddd = from data in test.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), CumRealPNLrollHold = data.Field <Object>("CumRealPNLrollHold") }; foreach (var item in ddd) { if (item.Date != null && item.CumRealPNLrollHold != null) { chart3.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.CumRealPNLrollHold); } } chart3.DataBind(); //chart3.ChartAreas[0].AxisY.LabelStyle.Format = "{0.00}" + "%"; Cursor = Cursors.Default; }
private void button3_Click(object sender, EventArgs e) { // BRUTE FORCE OPTIMIZE - LOOP THRU ALL COMBINATIONS OF PARAMETERS IN BACKTEST string sourcePath = System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"]; string destPath = System.Configuration.ConfigurationManager.AppSettings["DestDirectory"]; string ticker = textBox1.Text; //int[] holdDays = { 3, 5, 8 }; double[] cutoff = { 1, 2, 3, 4 }; //int[] rollingDays = { 30, 60, 90}; double lens = Math.Pow(3, (cutoff.Length)); int len = Convert.ToInt32(lens); double[,] table = new double[len, 4]; int count = 0; Cursor = Cursors.WaitCursor; Console.WriteLine(lens); var geneticsArray = new[] { new[] { 2, 3, 5, 8 }, new[] { 1, 2, -1, -2 }, new[] { 10, 20, 40, 60 } }; var perms = from a in geneticsArray[0] from b in geneticsArray[1] from c in geneticsArray[2] select new { a, b, c }; try { foreach (var value in perms) { //double result; BackTest test = new BackTest(ticker, sourcePath, value.b); test.BackTestLongShort(value.a, value.c); double sharpe = MathFunctions.SharpePNLrollHold(test.DT); table[count, 0] = sharpe; table[count, 1] = value.a; table[count, 2] = value.b; table[count, 3] = value.c; count = count + 1; } } catch { MessageBox.Show("Optimization Failed - Check parameters and try again!"); } double max = 0.00; int z = 0; for (int i = 0; i < len; i++) { if (table[i, 0] > max) { max = table[i, 0]; } if (max == table[i, 0]) { z = i; } } BackTest test1 = new BackTest(ticker, sourcePath, table[z, 2]); test1.BackTestLongShort(Convert.ToInt32(table[z, 1]), Convert.ToInt32(table[z, 3])); textBox3.Text = Convert.ToString(table[z, 1]); textBox4.Text = Convert.ToString(table[z, 2]); textBox5.Text = Convert.ToString(table[z, 3]); BindingSource bSource = new BindingSource(); bSource.DataSource = test1.DT; dataGridView1.DataSource = bSource; DataRow last = test1.DT.Rows[test1.DT.Rows.Count - 1]; double zroll = Convert.ToDouble(last["ZscoreRolling"]); textBox6.Text = Convert.ToString(Math.Round((zroll * 1), 4)); double zstatic = Convert.ToDouble(last["ZscoreStatic"]); textBox2.Text = Convert.ToString(Math.Round((zstatic * 1), 4)); textBox7.Text = Convert.ToString(Math.Round((table[z, 2] * 1), 4)); textBox8.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test1.DT) * 1), 4)); textBox9.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreStaticCount(test1.DT) * 1), 4)); textBox10.Text = Convert.ToString(Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000), 4)); double RealCum = Convert.ToDouble(last["CumRealPNLrollHold"]); textBox11.Text = Convert.ToString(Math.Round((RealCum * 100), 4)); textBox12.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]), 0)); if (Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000), 4) > 0) { textBox13.Text = Convert.ToString(Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test1.DT) / table[z, 1]) / (MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]))) * 100, 4))); } if (Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000), 4) < 0) { textBox13.Text = Convert.ToString(-1 * Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test1.DT) / table[z, 1]) / (MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]))) * 100, 4))); } textBox14.Text = Convert.ToString(Math.Round((MathFunctions.SharpePNLrollHold(test1.DT)), 4)); textBox15.Text = Convert.ToString(Math.Round((MathFunctions.StdDevAllPNLrollHold(test1.DT) * Math.Sqrt(260) * 100), 4)); double aclose = Convert.ToDouble(last["AdjustedClose"]); textBox16.Text = Convert.ToString(Math.Round((aclose * 1), 2)); //double zroll = Convert.ToDouble(last["ZscoreRolling"]); textBox28.Text = Convert.ToString(Math.Round((zroll * 1), 4)); //double zstatic = Convert.ToDouble(last["ZscoreStatic"]); textBox27.Text = Convert.ToString(Math.Round((zstatic * 1), 4)); textBox26.Text = Convert.ToString(Math.Round((table[z, 2] * 1), 4)); textBox25.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test1.DT) * 1), 4)); textBox24.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreStaticCount(test1.DT) * 1), 4)); textBox23.Text = Convert.ToString(Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000 * -1), 4)); //double RealCum = Convert.ToDouble(last["CumRealPNLrollHold"]); textBox22.Text = Convert.ToString(Math.Round((RealCum * -100), 4)); textBox21.Text = Convert.ToString(Math.Round((MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]), 0)); if (Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000 * -1), 4) > 0) { textBox20.Text = Convert.ToString(Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test1.DT) / table[z, 1]) / (MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]))) * 100, 4))); } if (Math.Round((MathFunctions.AverageAllPNLrollHold(test1.DT) * 26000 * -1), 4) < 0) { textBox20.Text = Convert.ToString(-1 * Math.Abs(Math.Round((((MathFunctions.CountPNLrollHold(test1.DT) / table[z, 1]) / (MathFunctions.ZscoreRollCount(test1.DT) / table[z, 1]))) * 100, 4))); } textBox19.Text = Convert.ToString(Math.Round((MathFunctions.SharpePNLrollHold(test1.DT) * -1), 4)); textBox18.Text = Convert.ToString(Math.Round((MathFunctions.StdDevAllPNLrollHold(test1.DT) * Math.Sqrt(260) * 100), 4)); //double aclose = Convert.ToDouble(last["AdjustedClose"]); textBox17.Text = Convert.ToString(Math.Round((aclose * 1), 2)); /* * bind data to a chart using LINQ and the * data table property for the BackTest data table instance */ chart1.Series[0].Points.Clear(); var d = from data in test1.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), ZscoreRolling = data.Field <Object>("ZscoreRolling") }; foreach (var item in d) { if (item.Date != null && item.ZscoreRolling != null) { chart1.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.ZscoreRolling); } } chart1.DataBind(); chart2.Series[0].Points.Clear(); var dd = from data in test1.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), AdjustedClose = data.Field <Object>("AdjustedClose") }; foreach (var item in dd) { if (item.Date != null && item.AdjustedClose != null) { chart2.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.AdjustedClose); } } chart2.DataBind(); chart3.Series[0].Points.Clear(); var ddd = from data in test1.DT.AsEnumerable() select new { Date = data.Field <DateTime>("Date"), CumRealPNLrollHold = data.Field <Object>("CumRealPNLrollHold") }; foreach (var item in ddd) { if (item.Date != null && item.CumRealPNLrollHold != null) { chart3.Series["Series1"].Points.AddXY(item.Date.Date.ToString("d"), item.CumRealPNLrollHold); } } chart3.DataBind(); //chart3.ChartAreas[0].AxisY.LabelStyle.Format = "{0.00}" + "%"; Cursor = Cursors.Default; }