//获取分钟线数据
 private void getMinuteData(string underlyingCode, List <DateTime> tradedays)
 {
     foreach (var date in tradedays)
     {
         if (minutelyKLine.ContainsKey(underlyingCode) == false)
         {
             try
             {
                 var minuteNow = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                 Dictionary <DateTime, List <StockTransaction> > data = new Dictionary <DateTime, List <StockTransaction> >();
                 data.Add(date, minuteNow);
                 minutelyKLine.Add(underlyingCode, data);
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
         }
         else if (minutelyKLine[underlyingCode].ContainsKey(date) == false)
         {
             try
             {
                 var minuteNow = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                 var data      = minutelyKLine[underlyingCode];
                 data.Add(date, minuteNow);
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
         }
     }
 }
        //将计算用的数据准备好
        private void dataPrepare(string underlyingCode, string indexCode, DateTime startDate, DateTime endDate, int N = 20)
        {
            //获取交易日信息
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取基本信息
            this.indexCode      = indexCode;
            this.underlyingCode = underlyingCode;
            //获取日线数据
            var indexData = stockDailyRepo.GetStockTransactionWithRedis(indexCode, startDate, endDate);

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var minuteKLine = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                underlyingKLine.Add(date, minuteKLine);
                var minuteKLine2 = stockMinutelyRepo.GetStockTransactionWithRedis(indexCode, date, date);
                indexKLine.Add(date, minuteKLine2);
            }
            for (int n = 10; n <= 30; n++)
            {
                Dictionary <DateTime, double> range = new Dictionary <DateTime, double>();
                foreach (var date in tradedays)
                {
                    var    index      = indexKLine[date];
                    var    underlying = underlyingKLine[date];
                    double HH         = 0;     //最高价的最高价
                    double HC         = 0;     //收盘价的最高价
                    double LC         = 99999; //收盘价的最低价
                    double LL         = 99999; //最低价的最低价
                    for (int i = 0; i < n; i++)
                    {
                        if (index[i].High > HH)
                        {
                            HH = index[i].High;
                        }
                        if (index[i].Close > HC)
                        {
                            HC = index[i].Close;
                        }
                        if (index[i].Close < LC)
                        {
                            LC = index[i].Close;
                        }
                        if (index[i].Low < LL)
                        {
                            LL = index[i].Low;
                        }
                    }
                    double rangeNow = Math.Max(HH - LC, HC - LL);
                    range.Add(date, rangeNow);
                }
                RangeDic.Add(n, range);
            }
        }
        private double getVolatilityMinutly(string code, DateTime today, int period)
        {
            double   vol       = 0;
            int      num       = 0;
            DateTime start     = DateUtils.PreviousTradeDay(today, period);
            DateTime end       = DateUtils.PreviousTradeDay(today, 1);
            var      tradedays = dateRepo.GetStockTransactionDate(start, end);

            foreach (var date in tradedays)
            {
                var data = stockMinuteRepo.GetStockTransactionWithRedis(code, date, date);
                if (data.Count == 0)
                {
                    continue;
                }
                List <double> priceList = new List <double>();
                for (int i = 1; i < data.Count() - 1; i++)
                {
                    priceList.Add(data[i].Close);
                }
                double volToday = getVolatility(priceList);
                vol += volToday;
                num += 1;
            }
            if (num > 0)
            {
                vol = vol / num;
            }
            return(vol);
        }
        public void record(DateTime startDate, DateTime endDate)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);

            //CreateDBOrTableIfNecessary(startDate);
            //CreateDBOrTableIfNecessary(startDate.AddYears(1));
            //var start = startDate;
            //while (start < endDate)
            //{
            //    if (!ExistInSqlServer(start))
            //    {
            //        CreateDBOrTableIfNecessary(start);
            //    }
            //    start = start.AddYears(1);
            //}
            //if (!ExistInSqlServer(endDate))
            //{
            //    CreateDBOrTableIfNecessary(endDate);
            //}

            foreach (var date in tradedays)
            {
                var etf = stockRepo.GetStockTransactionWithRedis(underlying, date, date);
            }
        }
        public void compute(DateTime startDate, DateTime endDate, int steps = 40)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            var etfall    = stockMinutelyRepo.GetStockTransactionWithRedis(code, tradedays.First(), tradedays.Last());
            int duration  = 5;
            int minutes   = 240;

            //var distribution0 = getDistribution(etfall, 500, tradedays.Count()-1, 240);
            //ListToCSV.SaveDataToCSVFile<double>(distribution0, ListToCSV.CreateFile("E:\\result\\vd\\", "distribution"), "distribution");
            for (int i = steps + 1; i < tradedays.Count(); i++)
            {
                List <double> bigVolume         = new List <double>();
                int           endDateNum        = i - 1;
                int           startDateNum      = Math.Max((i - steps - 1), 0);
                var           distribution      = getDistribution(etfall, startDateNum, endDateNum, minutes);
                var           fluctuation       = getFluctuation(etfall, startDateNum, endDateNum, minutes, duration);
                var           distributionToday = getDistributionToday(etfall, distribution, i, minutes);
                for (int j = 0; j < minutes - duration; j++)
                {
                    if (distributionToday[j] - distribution[j] > 0.002)
                    {
                        bigVolume.Add((etfall[i * minutes + j + duration].Close / etfall[i * minutes + j].Close - 1));
                    }
                }
                var all   = ListExtension.mean(fluctuation);
                var today = ListExtension.mean(bigVolume);
                Console.WriteLine("Date:{0},all:{1},  today:{2}!", etfall[i * minutes].DateTime.Date.ToString(), Math.Round(all, 5), Math.Round(today, 5));
            }
        }
Esempio n. 6
0
        private void prepare(string code, DateTime startDate, DateTime endDate)
        {
            //获取交易日信息
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取基本信息
            this.code = code;
            //获取日线数据
            var dailyData = stockDailyRepo.GetStockTransactionWithRedis(code, startDate, endDate);

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var minuteKLine = stockMinutelyRepo.GetStockTransactionWithRedis(code, date, date);
                underlyingKLine.Add(date, minuteKLine);
            }
            foreach (var item in dailyData)
            {
                var KLines = underlyingKLine[item.DateTime];
                foreach (var KLine in KLines)
                {
                    KLine.AdjFactor = item.AdjFactor;
                }
            }
            for (int n = 3; n < 50; n++)
            {
                var dic = getMA(underlyingKLine, n);
                MADic.Add(n, dic);
            }
        }
        public void compute(DateTime startDate, DateTime endDate)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            List <StockTransaction> codeDaily           = new List <StockTransaction>();
            List <StockTransaction> underlyingCodeDaily = new List <StockTransaction>();

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var underlyingToday = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                underlyingCodeDaily.AddRange(underlyingToday);
                var codeToday = stockMinutelyRepo.GetStockTransactionWithRedis(code, date, date);
                codeDaily.AddRange(codeToday);
            }
            double k1 = 0, k2 = 0, trailParameter = 0;

            getParameter(tradedays, underlyingCodeDaily, codeDaily, ref k1, ref k2, ref trailParameter);
            //k1 = 2.8;k2 = 2.8;trailParameter = 0.004;
            double sharpe = computeChoiceParameter(tradedays, underlyingCodeDaily, codeDaily, k1, k2, trailParameter);
        }
Esempio n. 8
0
        /// <summary>
        /// 获取每个交易日的全部期货
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        private void getAllData(DateTime startDate, DateTime endDate)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);

            foreach (var date in tradedays)
            {
                var dataDaily = new Dictionary <string, List <StockTransaction> >();
                var list      = getFutureList(date, 4);
                var indexData = stockMinutelyRepo.GetStockTransactionWithRedis(indexCode, date, date);
                dataDaily.Add(indexCode, indexData);
                foreach (var item in list)
                {
                    var data = stockMinutelyRepo.GetStockTransactionWithRedis(item.Key, date, date);
                    data.RemoveAt(241);
                    data.RemoveAt(0);
                    dataDaily.Add(item.Key, data);
                }
                allData.Add(date, dataDaily);
            }
        }
Esempio n. 9
0
        private void prepare(string underlyingCode, string indexCode, DateTime startDate, DateTime endDate)
        {
            //获取交易日信息
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取基本信息
            this.indexCode      = indexCode;
            this.underlyingCode = underlyingCode;
            //获取日线数据
            var indexData = stockDailyRepo.GetStockTransactionWithRedis(indexCode, startDate, endDate);

            volatilityDaily = getDailyVolatility(indexData);
            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var minuteKLine = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                underlyingKLine.Add(date, minuteKLine);
                var minuteKLine2 = stockMinutelyRepo.GetStockTransactionWithRedis(indexCode, date, date);
                indexKLine.Add(date, minuteKLine2);
            }
            volatilityMinutely = getMinutelyVolatility(indexKLine, 1);
        }
        //将计算用的数据准备好
        private void dataPrepare(string underlyingCode, DateTime startDate, DateTime endDate, int N = 20)
        {
            //获取交易日信息
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取基本信息
            this.underlyingCode = underlyingCode;
            //获取日线数据
            var underlyingData = stockDailyRepo.GetStockTransactionWithRedis(underlyingCode, startDate, endDate);

            for (int n = 1; n <= N; n++)
            {
                Dictionary <DateTime, double> range = new Dictionary <DateTime, double>();
                for (int i = n; i < underlyingData.Count() - 1; i++)
                {
                    double HH = 0;     //最高价的最高价
                    double HC = 0;     //收盘价的最高价
                    double LC = 99999; //收盘价的最低价
                    double LL = 99999; //最低价的最低价
                    for (int k = i - n; k <= i - 1; k++)
                    {
                        if (underlyingData[k].High > HH)
                        {
                            HH = underlyingData[k].High;
                        }
                        if (underlyingData[k].Close > HC)
                        {
                            HC = underlyingData[k].Close;
                        }
                        if (underlyingData[k].Close < LC)
                        {
                            LC = underlyingData[k].Close;
                        }
                        if (underlyingData[k].Low < LL)
                        {
                            LL = underlyingData[k].Low;
                        }
                    }
                    double lastClose = underlyingData[i - 1].Close;
                    double rangeNow  = Math.Max(HH - LC, HC - LL);
                    range.Add(underlyingData[i].DateTime, rangeNow);
                }
                RangeDic.Add(n, range);
            }

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var minuteKLine = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                underlyingKLine.Add(date, minuteKLine);
            }
        }
 private void getAllStocks(List <stockInfo> info)
 {
     foreach (var stock in info)
     {
         DateTime startDate = stock.startDate;
         DateTime endDate   = stock.endDate;
         string   code      = stock.code;
         var      tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
         Dictionary <DateTime, List <StockTransaction> > thisStock = new Dictionary <DateTime, List <StockTransaction> >();
         foreach (var date in tradedays)
         {
             var stockMinuteData0 = stockMinutelyRepo.GetStockTransactionWithRedis(code, date, date);
             thisStock.Add(date, stockMinuteData0);
         }
         allStocks.Add(code, thisStock);
     }
 }
Esempio n. 12
0
        public void getStockData(string index, DateTime startDate, DateTime endDate)
        {
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            var dic = getStockList(tradedays, index);

            foreach (var stock in dic)
            {
                if (stock.Value.IPODate > startDate)
                {
                    startDate = stock.Value.IPODate;
                }
                if (stock.Value.DelistDate < endDate)
                {
                    endDate = stock.Value.DelistDate;
                }
                var data = stockMinutelyRepo.GetStockTransactionWithRedis(stock.Key, startDate, endDate);
                Console.WriteLine("code:{0} complete!", stock.Key);
            }
        }
Esempio n. 13
0
        //将计算用的数据准备好
        private void dataPrepare(string underlyingCode, DateTime startDate, DateTime endDate, int N = 20)
        {
            //获取交易日信息
            this.tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取基本信息
            this.underlyingCode = underlyingCode;
            //获取日线数据
            var underlyingData = stockDailyRepo.GetStockTransactionWithRedis(underlyingCode, startDate, endDate);

            for (int n = 1; n <= N; n++)
            {
                Dictionary <DateTime, double> vol = new Dictionary <DateTime, double>();
                for (int i = n; i < underlyingData.Count() - 1; i++)
                {
                    List <double> openToClose = new List <double>();
                    for (int j = Math.Max(0, i - n); j < i; j++)
                    {
                        if (underlyingData[j].Volume > 0)
                        {
                            openToClose.Add(underlyingData[j].Close / underlyingData[j].Open - 1);
                        }
                    }
                    if (openToClose.Count() > n / 2)
                    {
                        double volNow = getVol(openToClose);
                        if (volNow > 0)
                        {
                            vol.Add(underlyingData[i].DateTime, volNow);
                        }
                    }
                }
                volDic.Add(n, vol);
            }

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var minuteKLine = stockMinutelyRepo.GetStockTransactionWithRedis(underlyingCode, date, date);
                underlyingKLine.Add(date, minuteKLine);
            }
        }
        public void compute(DateTime startDate, DateTime endDate, int delaynum = 5, int startnum = 3, int calculatornum = 6)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            var etfall    = stockMinutelyRepo.GetStockTransactionWithRedis(code, tradedays.First(), tradedays.Last());

            modifyData(ref etfall);
            var netvalue         = new double[etfall.Count()];
            var signal           = new double[etfall.Count()];
            var buyStart         = new double[etfall.Count()];
            var buyCalculator    = new double[etfall.Count()];
            var longSignal       = new double[etfall.Count()];
            var sellStart        = new double[etfall.Count()];
            var sellCalculator   = new double[etfall.Count()];
            var shortSignal      = new double[etfall.Count()];
            int startnumNow      = 0;
            int calculatornumNow = 0;


            //买入启动
            startnumNow = 0;
            for (int i = delaynum; i < etfall.Count() - delaynum; i++)
            {
                if (etfall[i].Close < etfall[i - delaynum].Close)
                {
                    startnumNow += 1;
                }
                else
                {
                    startnumNow = 0;
                }
                if (startnumNow >= startnum)
                {
                    buyStart[i] = 1;
                }
            }
            //买入计数
            calculatornumNow = 0;
            double buyCalculatorStartPrice = 0;
            bool   buyCalculatorStart      = false;

            for (int i = delaynum; i < etfall.Count() - delaynum; i++)
            {
                if (buyStart[i - 1] == 1)
                {
                    buyCalculatorStart      = true;
                    buyCalculatorStartPrice = 0;
                    calculatornumNow        = 0;
                }
                if (buyCalculatorStart == true && etfall[i].Close >= etfall[i - 2].High && etfall[i].High > etfall[i - 1].High)
                {
                    if (calculatornumNow > 0 && etfall[i].Close > buyCalculatorStartPrice)
                    {
                        calculatornumNow += 1;
                        buyCalculator[i]  = calculatornumNow;
                        if (calculatornumNow == calculatornum)
                        {
                            longSignal[i + 1]  = 1;
                            buyCalculatorStart = false;
                        }
                        buyCalculatorStartPrice = etfall[i].Close;
                    }
                    if (calculatornumNow == 0)
                    {
                        calculatornumNow       += 1;
                        buyCalculatorStartPrice = etfall[i].Close;
                    }
                }
                if (calculatornumNow > 0)
                {
                    buyCalculator[i] = calculatornumNow;
                }
            }

            //卖出启动
            startnumNow = 0;
            for (int i = delaynum; i < etfall.Count() - delaynum; i++)
            {
                if (etfall[i].Close > etfall[i - delaynum].Close)
                {
                    startnumNow += 1;
                }
                else
                {
                    startnumNow = 0;
                }
                if (startnumNow >= startnum)
                {
                    sellStart[i] = 1;
                }
            }
            //卖出计数
            calculatornumNow = 0;
            double sellCalculatorStartPrice = 99999999;
            bool   sellCalculatorStart      = false;

            for (int i = delaynum; i < etfall.Count() - delaynum; i++)
            {
                if (sellStart[i - 1] == 1)
                {
                    sellCalculatorStart      = true;
                    sellCalculatorStartPrice = 99999999;
                    calculatornumNow         = 0;
                }
                if (sellCalculatorStart == true && etfall[i].Close <= etfall[i - 2].Low && etfall[i].Low < etfall[i - 1].Low)
                {
                    if (calculatornumNow > 0 && etfall[i].Close < sellCalculatorStartPrice)
                    {
                        calculatornumNow += 1;
                        if (calculatornumNow == calculatornum)
                        {
                            shortSignal[i + 1]  = -1;
                            sellCalculatorStart = false;
                        }
                        sellCalculatorStartPrice = etfall[i].Close;
                    }
                    if (calculatornumNow == 0)
                    {
                        calculatornumNow        += 1;
                        sellCalculatorStartPrice = etfall[i].Close;
                    }
                }
                if (calculatornumNow > 0)
                {
                    sellCalculator[i] = calculatornumNow;
                }
            }
            // storeSignal(etfall, longSignal, shortSignal,delaynum,startnum,calculatornum);
            netvalue = computeNetValue(etfall, longSignal, shortSignal, ref transactionData);
            var    nv     = getNetValueDaily(etfall, netvalue);
            double sharpe = Utilities.strategyPerformance.sharpeRatioByDailyNetValue(nv);

            storeTransctionData(transactionData, delaynum, startnum, calculatornum);
            statisticDataOfTransaction(transactionData, tradedays);
        }
        public void compute(DateTime startDate, DateTime endDate)
        {
            var    tradedays   = dateRepo.GetStockTransactionDate(startDate, endDate);
            var    choice      = new Dictionary <DateTime, List <CFEFuturesChoice> >();
            string myHoldStr   = "";
            var    tradeRecord = new List <CFEFuturesTradeRecord>();
            var    parameters  = startDate.ToShortDateString() + '_' + endDate.ToShortDateString() + "_treshold" + treshold.ToString() + "_slip" + slip.ToString();

            if (!ExistInSqlServer(code, parameters))
            {
                CreateDBOrTableIfNecessary(code, parameters);
            }
            DataTable dt = new DataTable();

            dt.Columns.Add("code");
            dt.Columns.Add("tdatetime", typeof(DateTime));
            dt.Columns.Add("expiredate", typeof(DateTime));
            dt.Columns.Add("indexPrice");
            dt.Columns.Add("price");
            dt.Columns.Add("annulizedBasis");

            foreach (var date in tradedays)
            {
                var list        = getFutureList(date);
                var index       = stockMinutelyRepo.GetStockTransactionWithRedis(indexCode, date, date);
                var dataList    = new Dictionary <string, List <StockTransaction> >();
                var holdNow     = new CFEFutures();
                var choiceToday = new List <CFEFuturesChoice>();

                if (myHoldStr != "")
                {
                    holdNow = list[myHoldStr];
                }
                foreach (var item in list)
                {
                    var data = stockMinutelyRepo.GetStockTransactionWithRedis(item.Key, date, date);
                    dataList.Add(item.Key, data);
                }
                for (int i = 5; i < 235; i++)
                {
                    DateTime         expireDate = new DateTime();
                    CFEFuturesChoice record     = new CFEFuturesChoice();
                    double           basis      = -10000;
                    if (myHoldStr == "")
                    {
                        var transaction = new CFEFuturesTradeRecord();
                        foreach (var item in list)
                        {
                            double basisNow = getAnuualizedBasis(item.Value, date, dataList[item.Value.code][i].Close, index[i].Close);
                            if (basisNow > basis)
                            {
                                holdNow                = item.Value;
                                basis                  = basisNow;
                                expireDate             = item.Value.expireDate;
                                myHoldStr              = item.Key;
                                transaction.code       = item.Key;
                                transaction.indexPrice = index[i].Close;
                                transaction.price      = dataList[item.Value.code][i].Close;
                                transaction.time       = index[i].DateTime;
                                transaction.direction  = -1;
                                transaction.expireDate = item.Value.expireDate;
                            }
                        }
                        //第一次开仓
                        tradeRecord.Add(transaction);
                    }
                    else
                    {
                        double modify               = 0;
                        var    closeRecord          = new CFEFuturesTradeRecord();
                        var    transaction          = new CFEFuturesTradeRecord();
                        var    latestBasis          = tradeRecord.Last().price - tradeRecord.Last().indexPrice;
                        var    latestTime           = tradeRecord.Last().time;
                        var    latestExpireDate     = tradeRecord.Last().expireDate;
                        var    latestAnnulizedBasis = getAnuualizedBasis2(latestBasis, latestTime, latestExpireDate);
                        closeRecord.time       = index[i].DateTime;
                        closeRecord.indexPrice = index[i].Close;
                        closeRecord.direction  = 1;
                        closeRecord.code       = holdNow.code;
                        closeRecord.price      = dataList[holdNow.code][i].Close;
                        closeRecord.expireDate = holdNow.expireDate;
                        basis = getAnuualizedBasis(holdNow, date, dataList[holdNow.code][i].Close, index[i].Close);
                        foreach (var item in list)
                        {
                            if (item.Value != holdNow)
                            {
                                modify = slip;
                            }
                            double basisNow          = getAnuualizedBasis(item.Value, date, dataList[item.Value.code][i].Close - modify, index[i].Close);
                            double annulizedBasisNow = getAnuualizedBasis2(dataList[item.Value.code][i].Close - modify + latestBasis - dataList[holdNow.code][i].Close, latestTime, item.Value.expireDate);
                            if ((annulizedBasisNow > latestAnnulizedBasis + treshold && DateUtils.GetSpanOfTradeDays(date, item.Value.expireDate) > 10) || DateUtils.GetSpanOfTradeDays(date, holdNow.expireDate) < 5)
                            //if (DateUtils.GetSpanOfTradeDays(date, holdNow.expireDate) < 5)
                            {
                                holdNow                = item.Value;
                                basis                  = basisNow;
                                expireDate             = item.Value.expireDate;
                                myHoldStr              = item.Key;
                                transaction.code       = item.Key;
                                transaction.indexPrice = index[i].Close;
                                transaction.price      = dataList[item.Value.code][i].Close;
                                transaction.time       = index[i].DateTime;
                                transaction.direction  = -1;
                                transaction.expireDate = expireDate;
                            }
                        }
                        if (transaction.code != null)
                        {
                            tradeRecord.Add(closeRecord);
                            tradeRecord.Add(transaction);
                        }
                    }
                    record.code           = holdNow.code;
                    record.expireDate     = holdNow.expireDate;
                    record.annulizedBasis = basis;
                    record.indexPrice     = index[i].Close;
                    record.price          = dataList[holdNow.code][i].Close;
                    choiceToday.Add(record);
                    DataRow dr = dt.NewRow();
                    dr["code"]           = record.code;
                    dr["tdatetime"]      = index[i].DateTime;//etf[i].TransactionDateTime;
                    dr["expiredate"]     = record.expireDate;
                    dr["indexPrice"]     = record.indexPrice;
                    dr["price"]          = record.price;
                    dr["annulizedBasis"] = record.annulizedBasis;
                    dt.Rows.Add(dr);
                }
                choice.Add(date, choiceToday);
            }
            var pnl      = getPnL(tradeRecord);
            var netValue = getNetValue(tradeRecord, tradedays);

            Console.WriteLine(pnl);
            SaveResultToMssql(dt, code, parameters);

            DataTable dt2 = new DataTable();

            dt2.Columns.Add("code");
            dt2.Columns.Add("tdatetime", typeof(DateTime));
            dt2.Columns.Add("expiredate", typeof(DateTime));
            dt2.Columns.Add("indexPrice");
            dt2.Columns.Add("price");
            dt2.Columns.Add("direction");
            for (int i = 0; i < tradeRecord.Count(); i++)
            {
                DataRow dr     = dt2.NewRow();
                var     record = tradeRecord[i];
                dr["code"]       = record.code;
                dr["tdatetime"]  = record.time;
                dr["expiredate"] = record.expireDate;
                dr["indexPrice"] = record.indexPrice;
                dr["price"]      = record.price;
                dr["direction"]  = record.direction;
                dt2.Rows.Add(dr);
            }
            if (!ExistInSqlServer2(code, parameters))
            {
                CreateDBOrTableIfNecessary2(code, parameters);
            }
            SaveResultToMssql2(dt2, code, parameters);

            DataTable dt3 = new DataTable();

            dt3.Columns.Add("code");
            dt3.Columns.Add("tdatetime", typeof(DateTime));
            dt3.Columns.Add("expiredate", typeof(DateTime));
            dt3.Columns.Add("basis");
            dt3.Columns.Add("annulizedBasis");
            dt3.Columns.Add("basisWithSlip");
            dt3.Columns.Add("annulizedBasisWithSlip");
            for (int i = 0; i < netValue.Count(); i++)
            {
                DataRow dr     = dt3.NewRow();
                var     record = netValue[i];
                dr["code"]                   = record.code;
                dr["tdatetime"]              = record.time;
                dr["expiredate"]             = record.expireDate;
                dr["basis"]                  = record.basis;
                dr["annulizedBasis"]         = record.annulizedBasis;
                dr["basisWithSlip"]          = record.basisWithSlip;
                dr["annulizedBasisWithSlip"] = record.annulizedBasisWithSlip;
                dt3.Rows.Add(dr);
            }
            if (!ExistInSqlServer3(code, parameters))
            {
                CreateDBOrTableIfNecessary3(code, parameters);
            }
            SaveResultToMssql3(dt3, code, parameters);
        }
Esempio n. 16
0
        public void compute(DateTime startDate, DateTime endDate)
        {
            var tradedays = dateRepo.GetStockTransactionDate(startDate, endDate);
            //获取日线数据
            var underlyingDaily = stockDailyRepo.GetStockTransactionWithRedis(code, tradedays.First(), tradedays.Last());

            //获取分钟线数据
            foreach (var date in tradedays)
            {
                var underlyingToday = stockMinutelyRepo.GetStockTransactionWithRedis(code, date, date);
                underlying.Add(date, underlyingToday);
                minutes = underlyingToday.Count();
                underlyingAll.AddRange(underlyingToday);
            }
            double bestSharpe = 0;
            double bestf1     = 0.64;
            double bestf2     = 0.48;
            double bestf3     = 0.08;
            double step       = 0.04;

            //for (int i = 1; i <= 1/step; i=i+1)
            //{
            //    for (int j = 1; j <= 1 / step; j = j + 1)
            //    {
            //        for (int k = 1; k <= 1 / step; k = k + 1)
            //        {
            //            double f1 = i * step;
            //            double f2 = j * step;
            //            double f3 = k * step;
            //            double[] netvalue0 = getPerformance(startDate, endDate, tradedays, underlyingDaily, f1, f2, f3);
            //            var nv = getNetValueCurveDaily(getNetValueDaily(underlyingAll, netvalue0));
            //            double sharpe = Utilities.strategyPerformance.sharpeRatioByDailyNetValue(nv);
            //            if (sharpe>bestSharpe)
            //            {
            //                bestf1 = f1;
            //                bestf2 = f2;
            //                bestf3 = f3;
            //                bestSharpe = sharpe;
            //                Console.WriteLine("Best parameters:f1={0}, f2={1}, f3={2}, sharpe={3}", f1, f2, f3, sharpe);
            //            }
            //        }
            //    }
            //}

            double[] netvalue = getPerformance(startDate, endDate, tradedays, underlyingDaily, bestf1, bestf2, bestf3);
            var      nvDaily  = getNetValueDaily(underlyingAll, netvalue);

            DataTableExtension.SaveCSV(DataTableExtension.ToDataTable <netvalueDaily>(nvDaily), "E:\\result\\break\\netvalue.csv");
            statisticDataOfTransaction(transactionData, tradedays);
            double mean = 0;
            double num  = 0;

            for (int i = -5; i <= 5; i = i + 1)
            {
                for (int j = -5; j <= 5; j = j + 1)
                {
                    for (int k = -5; k <= 5; k = k + 1)
                    {
                        double f1 = bestf1 + i * step * 0.25;
                        double f2 = bestf2 + j * step * 0.25;
                        double f3 = bestf3 + k * step * 0.25;
                        if (f1 <= 0 || f2 <= 0 || f3 <= 0)
                        {
                            continue;
                        }
                        double[] netvalue0 = getPerformance(startDate, endDate, tradedays, underlyingDaily, f1, f2, f3);
                        var      nv        = getNetValueCurveDaily(getNetValueDaily(underlyingAll, netvalue0));
                        double   sharpe    = Utilities.strategyPerformance.sharpeRatioByDailyNetValue(nv);
                        mean += sharpe;
                        num  += 1;
                        Console.WriteLine("parameters around best:f1={0}, f2={1}, f3={2}, sharpe={3}", f1, f2, f3, sharpe);
                    }
                }
            }
            Console.WriteLine("mean:{0}", mean / num);
        }
Esempio n. 17
0
        public void compute(DateTime startDate, DateTime endDate)
        {
            var tradedays  = dateRepo.GetStockTransactionDate(startDate, endDate);
            var parameters = startDate.ToShortDateString() + '_' + endDate.ToShortDateString() + "frontNext";

            if (!ExistInSqlServer(code, parameters))
            {
                CreateDBOrTableIfNecessary(code, parameters);
            }
            DataTable dt = new DataTable();

            dt.Columns.Add("tdatetime", typeof(DateTime));
            dt.Columns.Add("future1");
            dt.Columns.Add("future2");
            dt.Columns.Add("expiredate1", typeof(DateTime));
            dt.Columns.Add("expiredate2", typeof(DateTime));
            dt.Columns.Add("duration1");
            dt.Columns.Add("duration2");
            dt.Columns.Add("indexPrice");
            dt.Columns.Add("price1");
            dt.Columns.Add("price2");
            dt.Columns.Add("basis1");
            dt.Columns.Add("basis2");
            dt.Columns.Add("basis12");

            foreach (var date in tradedays)
            {
                //var list = getSpecialFutureList(date);
                var list          = getFutureList(date);
                var index         = stockMinutelyRepo.GetStockTransactionWithRedis(indexCode, date, date);
                var dataList      = new Dictionary <string, List <StockTransaction> >();
                var basisDataList = new List <specialBasis>();
                foreach (var item in list)
                {
                    var data = stockMinutelyRepo.GetStockTransactionWithRedis(item.Key, date, date);
                    dataList.Add(item.Key, data);
                }
                for (int i = 5; i <= 235; i = i + 5)
                {
                    var data0    = new specialBasis();
                    var indexNow = index[i];
                    var future1  = dataList[list.Keys.First()][i];
                    var future2  = dataList[list.Keys.Last()][i];
                    data0.future1     = future1.Code;
                    data0.future2     = future2.Code;
                    data0.time        = indexNow.DateTime;
                    data0.expireDate1 = list[list.Keys.First()].expireDate;
                    data0.expireDate2 = list[list.Keys.Last()].expireDate;
                    data0.indexPrice  = indexNow.Close;
                    data0.price1      = future1.Volume == 0?future1.Close: (future1.Amount / future1.Volume) / 200;
                    data0.price2      = future2.Volume == 0?future2.Close: (future2.Amount / future2.Volume) / 200;
                    data0.basis1      = data0.price1 - data0.indexPrice;
                    data0.basis2      = data0.price2 - data0.indexPrice;
                    data0.basis12     = data0.price2 - data0.price1;
                    data0.duration1   = DateUtils.GetSpanOfTradeDays(date, data0.expireDate1) / 252.0;
                    data0.duration2   = DateUtils.GetSpanOfTradeDays(date, data0.expireDate2) / 252.0;
                    basisDataList.Add(data0);
                }
                foreach (var item in basisDataList)
                {
                    DataRow dr = dt.NewRow();
                    dr["tdatetime"]   = item.time;
                    dr["future1"]     = item.future1;
                    dr["future2"]     = item.future2;
                    dr["expireDate1"] = item.expireDate1;
                    dr["expireDate2"] = item.expireDate2;
                    dr["indexPrice"]  = item.indexPrice;
                    dr["price1"]      = item.price1;
                    dr["price2"]      = item.price2;
                    dr["basis1"]      = item.basis1;
                    dr["basis2"]      = item.basis2;
                    dr["basis12"]     = item.basis12;
                    dr["duration1"]   = item.duration1;
                    dr["duration2"]   = item.duration2;
                    dt.Rows.Add(dr);
                }
            }
            SaveResultToMssql(dt, code, parameters);
        }