Exemplo n.º 1
0
        private void button9_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null || tsd.DayKLine == null || tsd.DayKLine.Count <= 0)
                {
                    continue;
                }
                showText(code + "...");
                tsd.CubeCreate(Utility.Collections.Time.TimeUnit.month);
                tsd.FundTrendCreate(Utility.Collections.Time.TimeUnit.month);
                num += 1;
            }
            showText("");
            MessageBox.Show("生成完成,共有" + num.ToString() + "个股票生成数据");
        }
Exemplo n.º 2
0
        /// <summary>
        /// 月k
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null || tsd.DayKLine == null || tsd.DayKLine.Count <= 0)
                {
                    continue;
                }
                showText(code + "...");


                KLine monthKline = (KLine)tsd.Create("kline", TimeUnit.month, checkBox2.Checked);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }

            List <SecurityProperties> sps = null;

            if (radioButton1.Checked)
            {
                sps = new SHTrader().LoadStockAInfo(this.textBox1.Text);
            }
            else if (radioButton2.Checked)
            {
                sps = new SZTrader().LoadStockInfo(this.textBox1.Text, "主板");
            }
            else if (radioButton3.Checked)
            {
                sps = new SZTrader().LoadStockInfo(this.textBox1.Text, "创业板");
            }
            else if (radioButton4.Checked)
            {
                sps = new SZTrader().LoadStockInfo(this.textBox1.Text, "中小板");
            }
            else
            {
                MessageBox.Show("需选择导入类型");
                return;
            }
            if (sps == null)
            {
                MessageBox.Show("没有需要导入的数据");
                return;
            }

            SecurityPropertiesSet securities = repository.Securities;

            securities.Merge(sps);
            repository.SaveSecuritiesInfo();
            MessageBox.Show("导入完成");
        }
Exemplo n.º 4
0
 /// <summary>
 /// 生成指标数据
 /// </summary>
 /// <returns></returns>
 public bool doGenerateIndicator()
 {
     showBeginMessage("开始生成指标...");
     if (repository == null)
     {
         repository = new IndicatorRepository(FileUtils.GetDirectory(props.Get <String>("repository")));
         repository.Initilization();
     }
     try
     {
         List <String> codes = repository.Securities.Codes;
         foreach (String code in codes)
         {
             TimeSerialsDataSet ds = repository[code];
             if (ds == null)
             {
                 continue;
             }
             showProgressMessage(code);
             KLine       kline     = ds.DayKLine;
             TradingLine tradeLine = ds.DayTradeLine;
             ds.Create("kline", TimeUnit.week);
             ds.Create("kline", TimeUnit.month);
             ds.CubeCreate();
             ds.CubeCreate(TimeUnit.week);
             ds.CubeCreate(TimeUnit.month);
             ds.FundTrendCreate(TimeUnit.day);
             ds.FundTrendCreate(TimeUnit.week);
             ds.FundTrendCreate(TimeUnit.month);
             ds.FundTrendCrossCreate(TimeUnit.day);
             ds.FundTrendCrossCreate(TimeUnit.week);
             ds.FundTrendCrossCreate(TimeUnit.month);
         }
         showResultMessage("");
         return(true);
     }
     catch (Exception e)
     {
         showResultMessage("生成指标失败", -1, e.Message);
         return(false);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// 生成MACD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null)
                {
                    continue;
                }
                KLine dayLine = tsd.DayKLine;
                if (dayLine != null)
                {
                    tsd.Create("macd", TimeUnit.day, checkBox1.Checked);
                }
                KLine weekLine = tsd.WeekKLine;
                if (weekLine != null)
                {
                    tsd.Create("macd", TimeUnit.week, checkBox1.Checked);
                }
                if (tsd == null || tsd.DayKLine == null || tsd.DayKLine.Count <= 0)
                {
                    continue;
                }
                showText(code + "...");
            }
        }
Exemplo n.º 6
0
        private void button11_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }
            SecurityPropertiesSet securities = repository.Securities;
            List <String>         codes      = securities.Codes;
            int num = 0;

            foreach (String code in codes)
            {
                if (code == null || code == "")
                {
                    continue;
                }
                TimeSerialsDataSet tsd = repository[code];
                if (tsd == null)
                {
                    continue;
                }

                KLine dayLine = tsd.DayKLine;
                if (dayLine == null)
                {
                    continue;
                }

                MACD macd = (MACD)tsd.Create("macd", TimeUnit.day, false);
                if (macd == null)
                {
                    continue;
                }
            }
        }
Exemplo n.º 7
0
        public void Execute()
        {
            List <String> codes = new List <string>();

            System.IO.File.ReadAllLines(FileUtils.GetDirectory() + "test.csv")
            .ToList().ForEach(x => codes.Add(x.Split(',')[1]));


            IndicatorRepository repository = new IndicatorRepository("d:\\repository\\");

            repository.Initilization();


            foreach (String code in codes)
            {
                //生成数据
                TimeSerialsDataSet ds = repository[code];
                KLine dayLine         = ds.DayKLine;
                KLine weekLine        = dayLine.CreateWeek();
                ds.WeekKLine = weekLine;

                TimeSeries <ITimeSeriesItem <double> > dayClose  = dayLine.Select <double>("close", 0, 0);
                TimeSeries <ITimeSeriesItem <double> > weekClose = weekLine.Select <double>("close", 0, 0);

                TradingLine dayTradeLine  = ds.CubeCreateOrLoad(TimeUnit.day);
                TradingLine weekTradeLine = ds.CubeCreateOrLoad(TimeUnit.week);

                TimeSeries <ITimeSeriesItem <List <double> > > dayFunds  = ds.FundTrendCreate(TimeUnit.day);
                TimeSeries <ITimeSeriesItem <List <double> > > weekFunds = ds.FundTrendCreate(TimeUnit.week);

                TimeSeries <ITimeSeriesItem <double> > dayCross  = ds.FundTrendCrossCreateOrLoad(TimeUnit.day);
                TimeSeries <ITimeSeriesItem <double> > weedCross = ds.FundTrendCrossCreateOrLoad(TimeUnit.week);

                //测试买入

                List <TradeBout> bouts = new List <TradeBout>();
                TimeSeries <ITimeSeriesItem <char> > dayTradePt = dayTradeLine.buysellPoints;
                for (int i = 0; i < dayTradePt.Count; i++)
                {
                    ITimeSeriesItem <char> item = dayTradePt[i];
                    if (item.Value == 'S')
                    {
                        continue;
                    }
                    if (item.Date < begin || item.Date > end)
                    {
                        continue;
                    }
                    DateTime buyPtDate = item.Date;
                    int      index     = dayFunds.IndexOf(buyPtDate);
                    while (index <= dayFunds.Count)
                    {
                        ITimeSeriesItem <List <double> > fundItem = dayFunds[index];
                        if (fundItem == null)
                        {
                            index += 1;
                            continue;
                        }
                        if (fundItem.Value[0] <= fundItem.Value[1])
                        {
                            index += 1;
                            continue;
                        }
                        TradeBout bout      = new TradeBout(code);
                        KLineItem klineItem = dayLine.GetNearest(fundItem.Date, false);
                        if (klineItem == null)
                        {
                            index += 1;
                            continue;
                        }
                        bout.RecordTrade(1, klineItem.Date, TradeDirection.Buy, klineItem.CLOSE, (int)(funds / klineItem.CLOSE), 0, 0, "发出B点且主力=" + fundItem.Value[0].ToString("F3") + "大于散户" + fundItem.Value[1].ToString("F3") + ",日期=" + fundItem.Date.ToString("yyyyMMdd"));
                        bouts.Add(bout);
                        break;
                    }
                }
                //测试卖出
                for (int i = 0; i < bouts.Count; i++)
                {
                    DateTime buyDate  = bouts[i].BuyInfo.TradeDate;
                    int      buyIndex = dayLine.IndexOf(buyDate);
                    int      index    = buyIndex + 1;
                    while (index <= dayLine.Count - 1)
                    {
                        KLineItem item = dayLine[index];
                        if (index - buyIndex >= maxdays)
                        {
                            bouts[i].RecordTrade(2, item.Date, TradeDirection.Sell, item.CLOSE, bouts[i].BuyInfo.Amount, 0, 0, "大于" + maxdays.ToString() + "天卖出");
                            break;
                        }
                        else
                        {
                            double profile = (item.HIGH - bouts[i].BuyInfo.TradePrice) / bouts[i].BuyInfo.TradePrice;
                            if (profile >= maxProfilt)
                            {
                                bouts[i].RecordTrade(2, item.Date, TradeDirection.Sell, (bouts[i].BuyInfo.TradePrice * (1 + maxProfilt)), bouts[i].BuyInfo.Amount, 0, 0, "利润大于" + maxdays.ToString() + "天卖出");
                                break;
                            }
                        }
                        index += 1;
                    }
                }
                //去掉未完成的
                for (int i = 0; i < bouts.Count; i++)
                {
                    if (!bouts[i].Completed)
                    {
                        bouts.RemoveAt(i--);
                    }
                }

                TradeRecords tradeRecords = new TradeRecords();
                tradeRecords.Bouts.AddRange(bouts);
                //打印结果
                for (int i = 0; i < bouts.Count; i++)
                {
                    Console.WriteLine(bouts[i].ToString());
                }
                Console.WriteLine(tradeRecords.ToString());
            }
        }
Exemplo n.º 8
0
        public void DoTest(String strategyName = "")
        {
            IndicatorRepository repository = new IndicatorRepository(backtestParam.Datapath);

            repository.Initilization();
            backtestParam.Put("repository", repository);


            if (strategyName == null || strategyName == "")
            {
                strategyName = backtestParam.Get <String>("strategy");
            }
            KeyValuePair <IStrategyMeta, Properties> kv = this.GetStrateMetaAndParam(strategyName);

            if (kv.Key == null)
            {
                return;
            }

            IStrategyMeta     meta     = kv.Key;
            Properties        props    = kv.Value;
            String            version  = props.Get <String>("version", "");
            IStrategyInstance instance = meta.CreateInstance("1", props, version);

            if (instance == null)
            {
                return;
            }

            if (backtestParam.Optimization != null && backtestParam.Optimization.ToLower().Contains("ga"))
            {
                new EvolutionComputer(backtestParam.Optimization).Start(this);
                return;
            }

            List <Properties> instanceParamSet = spiltStrategyParams(props);

            int             taskCount            = this.backtestParam.TaskCount;
            List <Task>     tasks                = new List <Task>();
            List <Executor> executors            = new List <Executor>();
            int             instanceCountPerTask = instanceParamSet.Count / taskCount;

            List <ExecuteParam> execParams = new List <ExecuteParam>();

            int    batchno    = backtestParam.BatchNo;
            String resultPath = backtestParam.Resultpath;

            for (int i = 0; i < instanceParamSet.Count; i++)
            {
                int backtestxh = batchno + i + 1; //回测序号
                                                  //结果文件已经有了,跳过

                /*String resultfilename = resultPath + backtestxh + ".result";
                 * if (System.IO.File.Exists(resultfilename))
                 *  continue;
                 */

                Properties instanceProp = instanceParamSet[i];
                Properties backtestProp = backtestParam.Clone();
                backtestProp["serialno"] = backtestxh.ToString();
                backtestProp["batchno"]  = batchno.ToString();

                execParams.Add(new ExecuteParam(backtestxh.ToString(), instanceProp, backtestProp));
                if (execParams.Count >= instanceCountPerTask)
                {
                    Executor executor = new Executor(this, meta, "", execParams);
                    executors.Add(executor);
                    execParams.Clear();
                }
            }
            if (execParams.Count > 0)
            {
                Executor executor = new Executor(this, meta, "", execParams);
                executors.Add(executor);
                execParams.Clear();
            }


            System.IO.File.WriteAllText(resultPath + batchno + ".result", meta.GetBatchResultTitle() + System.Environment.NewLine);

            logger.Info("准备执行任务...,(任务数=" + executors.Count.ToString() + ")");
            executors.ForEach(x => tasks.Add(x.Go()));
            Task.WaitAll(tasks.ToArray());
        }
Exemplo n.º 9
0
        /// <summary>
        /// 导入数据
        /// </summary>
        public bool doMergeToRepository()
        {
            showBeginMessage("开始合并数据...");
            if (repository == null)
            {
                repository = new IndicatorRepository(FileUtils.GetDirectory(props.Get <String>("repository")));
                repository.Initilization();
            }
            String datapath = FileUtils.GetDirectory(props.Get <String>("datapath"));

            DirectoryInfo dInfo = new DirectoryInfo(datapath);

            FileInfo[] fInfos = dInfo.GetFiles("*.scv");
            if (fInfos == null || fInfos.Length <= 0)
            {
                showResultMessage("没有需要导入的新文件", 1);
                return(false);
            }
            try
            {
                foreach (FileInfo fInfo in fInfos)
                {
                    String             code = fInfo.Name.Substring(3, 6);
                    TimeSerialsDataSet ds   = repository[code];
                    KLine kline             = ds.DayKLine;
                    if (ds == null)
                    {
                        continue;
                    }
                    showProgressMessage(code);
                    CSVFile csvFile = new CSVFile();
                    csvFile.Load(fInfo.FullName, Encoding.UTF8, false, ",");
                    List <String> lines = csvFile.Lines;
                    for (int i = lines.Count - 1; i >= 0; i--)
                    {
                        if (lines[i] == null || lines[i].Trim() == "")
                        {
                            continue;
                        }
                        String[] ss = lines[i].Split(',');
                        if (ss == null || ss.Length < 7)
                        {
                            continue;
                        }

                        DateTime  d    = DateUtils.Parse(ss[0]);
                        KLineItem item = kline[d];
                        if (item != null)
                        {
                            break;
                        }

                        double[] v = new double[6];
                        for (int j = 0; j < v.Length; j++)
                        {
                            v[j] = double.Parse(ss[j + 1]);
                        }
                        item      = new KLineItem();
                        item.Date = d;
                        item.SetValue <double>("OPEN", v[0]);
                        item.SetValue <double>("HIGH", v[1]);
                        item.SetValue <double>("LOW", v[2]);
                        item.SetValue <double>("CLOSE", v[3]);
                        item.SetValue <double>("VOLUME", v[4]);
                        item.SetValue <double>("TURNOVER", v[5]);
                        kline.Add(item);
                    }

                    ds.Save("kline", TimeUnit.day);
                }
                showResultMessage("");
                return(true);
            }
            catch (Exception e)
            {
                showResultMessage("导入失败", -1, e.Message);
                return(false);
            }
        }
Exemplo n.º 10
0
        private void createTrainTestData()
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }

            String   filename = textBox7.Text;
            FileInfo fInfo    = new FileInfo(filename);


            String[] lines = File.ReadAllLines(filename);
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i] == null || lines[i].Trim() == "")
                {
                    continue;
                }

                int index = lines[i].IndexOf("\"");
                if (index < 0)
                {
                    continue;
                }
                index = lines[i].IndexOf("\"", index + 1);
                if (index < 0)
                {
                    continue;
                }
                index = lines[i].IndexOf("\"", index + 1);
                if (index < 0)
                {
                    continue;
                }

                String label = lines[i].substring(index - 1, "\"", "\"");
                //"[-6.4500000000000002, '2007-05-17', 6]"
                String[] ss = label.Split(',');
                if (ss == null || ss.Length < 3)
                {
                    continue;
                }
                String sDate = ss[1].Trim().Substring(1, 10);
                String code  = ss[2].Substring(0, ss[2].Length - 2).Trim();
                int    len   = code.Length;
                for (int j = 0; j < 6 - len; j++)
                {
                    code = "0" + code;
                }

                DateTime d = DateTime.ParseExact(sDate, "yyyy-MM-dd", null);

                TimeSerialsDataSet ds = repository[code];
                if (ds == null)
                {
                    lines[i] = lines[i].Substring(0, index) + "\"[0.0,'" + sDate + "'," + code + "]\"";
                    continue;
                }

                KLine     kline = ds.DayKLine;
                KLineItem item  = kline[d];
                if (item == null)
                {
                    lines[i] = lines[i].Substring(0, index) + "\"[0.0,'" + sDate + "'," + code + "]\"";
                    continue;
                }
                double maxprofilt = -100;
                int    itemIndex  = kline.IndexOf(item);
                for (int k = itemIndex + 1; k < itemIndex + 5; k++)
                {
                    if (k >= kline.Count)
                    {
                        break;
                    }
                    double p = (kline[k].CLOSE - item.CLOSE) / item.CLOSE;
                    if (maxprofilt < p)
                    {
                        maxprofilt = p;
                    }
                }
                if (maxprofilt == -100)
                {
                    lines[i] = lines[i].Substring(0, index) + "\"[0.0,'" + sDate + "'," + code + "]\"";
                    continue;
                }
                lines[i] = lines[i].Substring(0, index) + "\"[" + maxprofilt.ToString("F3") + ",'" + sDate + "'," + code + "]\"";
            }

            File.WriteAllLines(filename + "2", lines);
        }
Exemplo n.º 11
0
        private void button12_Click(object sender, EventArgs e)
        {
            String   code  = textBox4.Text;
            DateTime begin = dateTimePicker3.Value;
            DateTime end   = dateTimePicker4.Value;
            int      days  = int.Parse(textBox5.Text);

            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }

            TimeSerialsDataSet ds = repository[code];

            if (ds == null || ds.DayKLine == null)
            {
                MessageBox.Show("代码" + code + "缺少K线数据");
            }

            KLine     klineDay = ds.DayKLine;
            KLineItem item     = null;

            List <double[]> datas = new List <double[]>();

            for (int i = 0; i < klineDay.Count; i++)
            {
                item = klineDay[i];
                if (item.Date < begin)
                {
                    continue;
                }
                if (item.Date > end)
                {
                    break;
                }

                double maxprofilt = -100;
                for (int j = i + 1; j <= i + 1 + days; j++)
                {
                    if (j >= klineDay.Count)
                    {
                        break;
                    }
                    double p = (klineDay[j].CLOSE - item.CLOSE) / item.CLOSE;
                    if (maxprofilt < p)
                    {
                        maxprofilt = p;
                    }
                }
                if (maxprofilt == -100)
                {
                    continue;
                }
                double[] values = new double[2];
                values[0] = item.CLOSE;
                values[1] = maxprofilt;
                datas.Add(values);
            }

            if (datas.Count <= 0)
            {
                MessageBox.Show("没有有效数据");
                return;
            }
            String[] lines = datas.ConvertAll(x => x[0].ToString("F2") + "," + x[1].ToString("F3")).ToArray();
            File.WriteAllLines("d:\\" + code + ".csv", lines);
        }
Exemplo n.º 12
0
 private void button4_Click_1(object sender, EventArgs e)
 {
     repository = new IndicatorRepository(textBox2.Text);
     repository.Initilization();
 }
Exemplo n.º 13
0
        private void button5_Click(object sender, EventArgs e)
        {
            if (repository == null)
            {
                repository = new IndicatorRepository(textBox2.Text);
                repository.Initilization();
            }

            if (radioButton5.Checked)//飞狐交易师CSV格式
            {
                DirectoryInfo dInfo  = new DirectoryInfo(textBox3.Text);
                FileInfo[]    fInfos = dInfo.GetFiles("*.csv");
                int           num    = 0;
                for (int i = 0; i < fInfos.Length; i++)
                {
                    FileInfo x     = fInfos[i];
                    KLine    kline = new KLine(x.Name.Substring(2, 6), Utility.Collections.Time.TimeUnit.day);
                    kline.Load(x.FullName, false, ",", new String[] { "时间", "开盘", "最高", "最低", "收盘", "成交量", "成交额" });

                    toolStripStatusLabel1.Text = "导入" + kline.Code + "...";
                    Application.DoEvents();
                    TimeSerialsDataSet ds = repository[kline.Code];
                    if (ds == null)
                    {
                        continue;
                    }

                    ds.DayKLine = kline;
                    num        += 1;
                }
                MessageBox.Show("导入完成,共有" + num + "个日线完成导入");
            }
            else if (radioButton6.Checked)//通达信金融终端TXT格式
            {
                String[]      columns = { "时间", "开盘", "最高", "最低", "收盘", "成交量", "成交额" };
                DirectoryInfo dInfo   = new DirectoryInfo(textBox3.Text);
                FileInfo[]    fInfos  = dInfo.GetFiles("*.txt");
                int           num     = 0;
                for (int i = 0; i < fInfos.Length; i++)
                {
                    FileInfo x     = fInfos[i];
                    String   code  = x.Name.Substring(3, 6);
                    KLine    kline = new KLine(code, Utility.Collections.Time.TimeUnit.day);
                    String[] lines = File.ReadAllLines(x.FullName);
                    if (lines == null || lines.Length <= 0)
                    {
                        continue;
                    }
                    List <String> strs = lines.ToList();
                    strs.RemoveAt(0);
                    strs.RemoveAt(0);
                    strs.RemoveAt(strs.Count - 1);
                    kline.Load(strs.ToArray(), columns);
                    kline.ForEach(y => y["code"] = code);

                    toolStripStatusLabel1.Text = "导入" + kline.Code + "...";
                    Application.DoEvents();
                    TimeSerialsDataSet ds = repository[kline.Code];
                    if (ds == null)
                    {
                        continue;
                    }

                    ds.DayKLine = kline;
                    num        += 1;
                }
                MessageBox.Show("导入完成,共有" + num + "个日线完成导入");
            }
        }