Exemplo n.º 1
0
        private static void strategyCloseIn(int quarter, decimal threshold, int buyinpower, decimal bate, DateTime lastdate)
        {
            #region get symbols & spy hedge pnl
            FileHelperEngine EngineOut = new FileHelperEngine(typeof(DailyDataout));

            DailyDataout[] FinalDB = (DailyDataout[])EngineOut.ReadFile("Daily\\temp.csv");

            #region definition var
            List<DailyDataout> ReportEaring = new List<DailyDataout>();
            List<AdjustEaringdata> adjE = new List<AdjustEaringdata>();

            Queue<decimal> Beta5Ds = new Queue<decimal>();
            decimal avgBeta = 777;

            string symbol = "";
            decimal spyearingdate = 0;

            decimal highEaring = 0;
            decimal lowEaring = 0;

            decimal pricein = 0;
            decimal priceout = 0;

            decimal enterhigh = 0;
            decimal enterlow = 0;

            bool findin = false;
            bool findout = false;
            bool entrydate = false;
            bool exitdate = false;

            int size = 0;

            decimal spyin = 0;
            // decimal spyout = 0;
            int spysize = 0;
            #endregion

            foreach (var item in FinalDB)
            {

                DailyDataout tempitem = new DailyDataout();
                tempitem = item;
                AdjustEaringdata adjear = new AdjustEaringdata();
                if (tempitem.threshold > 0)
                {
                    #region long
                    if (item.symbol == symbol)
                    {

                        if ((findin && !findout) || exitdate)
                        {
                            #region get pnl

                            #region entry pnl
                            if (entrydate)
                            {
                                //pricein = Math.Max(pricein, item.open);
                                size = Convert.ToInt32(buyinpower / pricein);
                                tempitem.pnl = size * (item.close - pricein);
                                tempitem.daypnl = size * (item.close - item.open);
                                tempitem.overnightpnl = size * (item.open - pricein);
                                enterlow = item.low;
                                tempitem.pricein = pricein;
                                #region short spy hedge worst condition
                                spysize = Convert.ToInt32(buyinpower / spyin);
                                tempitem.spypnl = -spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = -spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = -spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.1)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                #region 5 days beta array
                                Beta5Ds.Enqueue(tempitem.beta);
                                #endregion

                                ReportEaring.Add(tempitem);
                                pricein = item.close;
                                spyin = item.spyclose;
                                entrydate = false;
                            }
                            #endregion

                            #region exit pnl
                            else if (exitdate)
                            {
                                priceout = Math.Min(priceout, item.close);
                                priceout = item.open;

                                tempitem.pnl = size * (priceout - pricein);
                                tempitem.daypnl = size * (priceout - item.open);
                                tempitem.overnightpnl = size * (item.open - pricein);
                                tempitem.priceout = priceout;
                                #region short spy hedge on close
                                spysize = Convert.ToInt32(buyinpower / spyin);
                                tempitem.spypnl = -spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = -spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = -spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.1)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                ReportEaring.Add(tempitem);
                                exitdate = false;
                            }
                            #endregion

                            #region regular pnl
                            else
                            {
                                tempitem.pnl = size * (item.close - pricein);
                                tempitem.daypnl = size * (item.close - item.open);
                                tempitem.overnightpnl = size * (item.open - pricein);
                                tempitem.priceout = item.close;
                                #region short spy hedge
                                spysize = Convert.ToInt32(buyinpower / spyin);
                                tempitem.spypnl = -spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = -spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = -spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.1)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                #region 5 days beta array
                                if (Beta5Ds.Count == 5)
                                {
                                    avgBeta = Beta5Ds.Average();
                                    Beta5Ds.Dequeue();
                                    Beta5Ds.Enqueue(tempitem.beta);
                                }
                                else
                                {
                                    Beta5Ds.Enqueue(tempitem.beta);
                                }

                                #endregion

                                ReportEaring.Add(tempitem);
                                pricein = item.close;
                                spyin = item.spyclose;
                            }
                            #endregion

                            #endregion

                            #region exit logic
                            if (!findout && (item.close < (lowEaring * item.spyclose / spyearingdate)
                                //|| avgBeta<(decimal)-2
                                 || item.date == lastdate
                                ))
                            {
                                priceout = lowEaring * item.spyclose / spyearingdate;
                                findout = true;
                                exitdate = true;
                            }
                            #endregion
                        }

                        #region entry logic

                        if (!findin && item.close > (highEaring * item.spyclose / spyearingdate))
                        {
                            //pricein = (highEaring * item.spyclose / spyearingdate);
                            findin = true;
                            entrydate = true;
                            spyin = item.spyclose;
                            pricein = item.close;
                            //if (item.symbol == "MTW")
                            //    Console.WriteLine(item.date);
                            tempitem.close = pricein;
                           // ReportEaring.Add(tempitem);

                            adjear.symbol = item.symbol;
                            adjear.date = item.date;
                            adjear.threshold = item.threshold;
                            adjear.adjearninghigh = highEaring * item.spyclose / spyearingdate;
                            adjE.Add(adjear);

                        }

                        #endregion

                        #region adj
                        if (!findin)
                        {
                            adjear.symbol = item.symbol;
                            adjear.date = item.date;
                            adjear.threshold = item.threshold;
                            adjear.adjearninghigh = highEaring * item.spyclose / spyearingdate;
                            adjE.Add(adjear);
                        }
                        #endregion

                    }
                    else
                    {
                        #region earnign date

                        symbol = item.symbol;
                        spyearingdate = item.spyclose;
                        highEaring = item.high;
                        lowEaring = item.low;
                        enterhigh = 0;
                        enterlow = 0;
                        pricein = 0;
                        priceout = 0;
                        findin = false;
                        findout = false;
                        entrydate = false;
                        exitdate = false;
                        size = 0;

                        spyin = 0;
                        spysize = 0;
                        avgBeta = 10000000;
                        Beta5Ds.Clear();

                        #endregion
                    }
                    #endregion
                }
                if (tempitem.threshold < 0)
                {
                    #region short

                    if (item.symbol == symbol)
                    {

                        if ((findin && !findout) || exitdate)
                        {

                            #region get pnl

                            #region entry pnl
                            if (entrydate)
                            {
                                pricein = Math.Min(pricein, item.open);
                                size = Convert.ToInt32(buyinpower / pricein);
                                tempitem.pnl = size * (-item.close + pricein);
                                tempitem.daypnl = size * (-item.close + item.open);
                                tempitem.overnightpnl = size * (-item.open + pricein);
                                enterhigh = item.high;
                                tempitem.pricein = pricein;
                                #region long spy hedge worst condition
                                spysize = Convert.ToInt32(buyinpower / item.spyopen);
                                tempitem.spypnl = spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.1)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                #region 5 days beta array
                                Beta5Ds.Enqueue(tempitem.beta);
                                #endregion

                                ReportEaring.Add(tempitem);
                                pricein = item.close;
                                entrydate = false;
                                spyin = item.spyclose;
                            }
                            #endregion

                            #region exit pnl
                            else if (exitdate)
                            {
                                priceout = Math.Max(priceout, item.close);
                                priceout = item.open;

                                tempitem.pnl = size * (-priceout + pricein);
                                tempitem.daypnl = size * (-priceout + item.open);
                                tempitem.overnightpnl = size * (-item.open + pricein);
                                tempitem.priceout = priceout;

                                #region long spy hedge on close
                                spysize = Convert.ToInt32(buyinpower / spyin);
                                tempitem.spypnl = spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.1)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                ReportEaring.Add(tempitem);
                                exitdate = false;
                            }
                            #endregion

                            #region regual pnl

                            else
                            {

                                tempitem.pnl = size * (-item.close + pricein);
                                tempitem.daypnl = size * (-item.close + item.open);
                                tempitem.overnightpnl = size * (-item.open + pricein);
                                tempitem.priceout = item.close;
                                #region long spy hedge
                                spysize = Convert.ToInt32(buyinpower / spyin);
                                tempitem.spypnl = spysize * (item.spyclose - spyin);
                                tempitem.dayspypnl = spysize * (item.spyclose - item.spyopen);
                                tempitem.overnightspypnl = spysize * (item.spyopen - spyin);
                                #endregion

                                #region win10 or lose10
                                if (tempitem.pnl / (pricein * size) >= (decimal)0.1)
                                {
                                    tempitem.win10 = 1;
                                }
                                else
                                {
                                    tempitem.win10 = 0;
                                }
                                if (tempitem.pnl / (pricein * size) <= -(decimal)0.5)
                                {
                                    tempitem.lose10 = 1;
                                }
                                else
                                {
                                    tempitem.lose10 = 0;
                                }
                                #endregion

                                #region 5 days beta array
                                if (Beta5Ds.Count == 5)
                                {
                                    avgBeta = Beta5Ds.Average();
                                    Beta5Ds.Dequeue();
                                    Beta5Ds.Enqueue(tempitem.beta);
                                }
                                else
                                {
                                    Beta5Ds.Enqueue(tempitem.beta);
                                }

                                #endregion

                                ReportEaring.Add(tempitem);
                                pricein = item.close;
                                spyin = item.spyclose;
                            }
                            #endregion

                            #endregion

                            #region exit logic
                            if (!findout && (item.close > (highEaring * item.spyclose / spyearingdate)
                                //||avgBeta > (decimal)2
                                 || item.date == lastdate
                                ))
                            {
                                priceout = highEaring * item.spyclose / spyearingdate;
                                findout = true;
                                exitdate = true;
                            }
                            #endregion
                        }

                        #region entry logic
                        if (!findin && item.close < (lowEaring * item.spyclose / spyearingdate))
                        {
                            //pricein = (lowEaring* item.spyclose / spyearingdate);
                            findin = true;
                            entrydate = true;
                            spyin = item.spyclose;
                            pricein = item.close;

                            tempitem.close = pricein;
                        //    ReportEaring.Add(tempitem);

                            adjear.symbol = item.symbol;
                            adjear.date = item.date;
                            adjear.threshold = item.threshold;
                            adjear.adjearninglow = lowEaring * item.spyclose / spyearingdate;
                            adjE.Add(adjear);
                        }
                        #endregion

                        #region adj
                        if (!findin)
                        {
                            adjear.symbol = item.symbol;
                            adjear.date = item.date;
                            adjear.threshold = item.threshold;
                            adjear.adjearninglow = lowEaring * item.spyclose / spyearingdate;
                            adjE.Add(adjear);
                        }
                        #endregion
                    }
                    else
                    {
                        #region earning date

                        symbol = item.symbol;
                        spyearingdate = item.spyclose;
                        highEaring = item.high;
                        lowEaring = item.low;
                        enterhigh = 0;
                        enterlow = 0;
                        pricein = 0;
                        priceout = 0;
                        findin = false;
                        findout = false;
                        entrydate = false;
                        exitdate = false;
                        size = 0;

                        spyin = 0;
                        spysize = 0;
                        avgBeta = -10000000;
                        Beta5Ds.Clear();
                        #endregion
                    }

                    #endregion
                }

            }

            #region write to file
            FileHelperEngine enginDR = new FileHelperEngine(typeof(DailyDataout));
            enginDR.HeaderText = "symbol,date,open,high,low,close,volume,Exist signal price,pricein,priceout,threshold,spy close,spy open,spy high, spy low,adv,win10,lose10,overnight pnl,day pnl,pnl,spy overnight pnl,spy day pnl, spy pnl,bp,beta";
            enginDR.WriteFile(string.Format("DailyReport\\{0}.{1}.D.csv", quarter, Convert.ToInt32(threshold * new decimal(100))), ReportEaring);

            FileHelperEngine enginadj = new FileHelperEngine(typeof(AdjustEaringdata));
            enginadj.HeaderText = "symbol,date,threshold,adj earning high, adj earing low";
            enginadj.WriteFile(string.Format("DailyReport\\{0}.{1}.E.csv", quarter, Convert.ToInt32(threshold * new decimal(100))), adjE);
            #endregion

            #endregion
        }
Exemplo n.º 2
0
        private static void backtest(int quarter,decimal threshold, int buyinpower)
        {
            TimeSpan st = DateTime.Now.TimeOfDay;
             #region hoilday dictionary
              bool flag3;
               Dictionary<string, DateTime> strs3 = new Dictionary<string, DateTime>();
            List<EarningData> earningDatas = new List<EarningData>();
            FileStream fileStream1 = new FileStream("holiday.txt", FileMode.Open);
            StreamReader streamReader1 = new StreamReader(fileStream1);
            do
            {
                string str1 = streamReader1.ReadLine();
                if (!(str1 == ""))
                {
                    strs3[str1] = DateTime.ParseExact(str1, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                    flag3 = (str1 == null ? false : str1 != "");
                }
                else
                {
                    break;
                }
            } while (flag3);

            streamReader1.Close();
            streamReader1.Dispose();
            fileStream1.Close();
            fileStream1.Dispose();
               #endregion

            #region get the quarter

            int year = quarter / 10;
            string begindate = year.ToString();
            string enddate = year.ToString();
            if (quarter % 10 == 1)
            {
                begindate = string.Concat(begindate, "0101");
                enddate = string.Concat(enddate, "0315");
            }
            if (quarter % 10 == 2)
            {

                begindate = string.Concat(begindate, "0401");
                enddate = string.Concat(enddate, "0615");
            }
            if (quarter % 10 == 3)
            {

                begindate = string.Concat(begindate, "0701");
                enddate = string.Concat(enddate, "0915");
            }
            if (quarter % 10 == 4)
            {

                begindate = string.Concat(begindate, "1001");
                enddate = string.Concat(enddate, "1215");
            }

            #endregion

            #region create bio tech symbols Dic

            bool flag2;
            Dictionary<string, string> bioArry = new Dictionary<string, string>();
            FileStream fileStream = new FileStream("bio.csv", FileMode.Open);
            StreamReader streamReader = new StreamReader(fileStream);
            streamReader.BaseStream.Seek((long)0, SeekOrigin.Begin);
            string str2 = streamReader.ReadLine();
            while (true)
            {
                flag2 = (str2 == null ? false : str2 != "");
                if (!flag2)
                {
                    break;
                }
                bioArry[str2] = str2;
                str2 = streamReader.ReadLine();
            }
            streamReader.Close();
            streamReader.Dispose();
            fileStream.Close();
            fileStream.Dispose();

            #endregion

            #region get right the earingdata

            FileHelperEngine EngineDBq = new FileHelperEngine(typeof(DailyData1));
            DailyData1[] resDB = (DailyData1[])EngineDBq.ReadFile(string.Format("Daily\\DailyQua\\{0}.csv", quarter));
            FileHelperEngine EngineEarning = new FileHelperEngine(typeof(unionearingdate));
            unionearingdate[] unionearingdateArray = (unionearingdate[])EngineEarning.ReadFile("Daily\\final.csv");

            var selectEarningdata = unionearingdateArray.Where(d =>
                d.date >= DateTime.ParseExact(begindate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None) &&
                d.date <= DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None)).
                Where(d => Math.Abs(d.threshold) >= threshold).
                Where(d => (d.high >= d.maxhigh && d.threshold > 0) || (d.low <= d.minlow && d.threshold < 0)).
                Where(d => {
                    bool symbolExit;
                    symbolExit = !bioArry.ContainsKey(d.symbol);
                    return symbolExit;
                }).
                Where(d=>d.high>=5)
                ;

            EngineEarning.WriteFile("Daily\\temp.csv", selectEarningdata);
            unionearingdate[] earningdata = (unionearingdate[])EngineEarning.ReadFile("Daily\\temp.csv");

            #endregion

            #region combin earning and spy in daily report

            #region select data from DB
            var spy=resDB.Where(d=>d.symbol=="SPY");

            var selectDB = from db in resDB
                           from e in earningdata
                           where (db.symbol == e.symbol) && (db.date >= e.date)
                           select new DailyDataout
                           {
                               symbol=db.symbol,
                               open=db.open,
                               high=db.high,
                               low=db.low,
                               close=db.close,
                               volume=db.volume,
                               adv=db.adv,
                               threshold=e.threshold,
                               date=db.date
                           };

            selectDB = selectDB.Where(dd => dd.date <= DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None));

            FileHelperEngine EngineOut = new FileHelperEngine(typeof(DailyDataout));
            EngineOut.HeaderText = "symbol,date,open,high,low,close,volume,Exist signal price,pricein,priceout,threshold,spy close,spy open,spy high, spy low,adv,win10,lose10,overnight pnl,day pnl,pnl,spy overnight pnl,spy day pnl, spy pnl,bp,beta";
            EngineOut.WriteFile("Daily\\temp.csv", selectDB);
            #endregion

            #region combine spy
            DailyDataout[] selectD = (DailyDataout[])EngineOut.ReadFile("Daily\\temp.csv");

            var combinspy = from db in selectD
                            join e in spy on db.date equals e.date
                            select new DailyDataout
                            {
                                symbol = db.symbol,
                                open = db.open,
                                high = db.high,
                                low = db.low,
                                close = db.close,
                                volume = db.volume,
                                adv = db.adv,
                                threshold = db.threshold,
                                date = db.date,
                                spyclose=e.close,
                                spyopen=e.open,
                                spylow=e.low,
                                spyhigh=e.high
                            };
            #endregion

            bool yc2tc = false;

            #region add beta
            if (yc2tc)
            {

                #region get beta close to close

                List<DailyDataout> newcombinspy = new List<DailyDataout>();
                string symbol = "";
                decimal beta = 0;
                decimal yesterdayClose = 0;
                decimal yesterdaySPYClose = 0;
                foreach (var data in combinspy)
                {
                    DailyDataout tempdailyout = new DailyDataout();
                    tempdailyout = data;

                    if (tempdailyout.symbol == symbol)
                    {
                        beta = ((tempdailyout.close / yesterdayClose) / (tempdailyout.spyclose / yesterdaySPYClose) - 1) * 100;
                        tempdailyout.beta = beta;
                        yesterdayClose = tempdailyout.close;
                        yesterdaySPYClose = tempdailyout.spyclose;
                    }
                    else
                    {
                        symbol = tempdailyout.symbol;
                        yesterdayClose = tempdailyout.close;
                        yesterdaySPYClose = tempdailyout.spyclose;
                    }
                    newcombinspy.Add(tempdailyout);
                }

            #endregion

                EngineOut.WriteFile("Daily\\temp.csv", newcombinspy);
            }
            else
            {

              #region get beta close to open

            List<DailyDataout> newcombinspy = new List<DailyDataout>();
            string symbol = "";
            decimal beta = 0;
            foreach (var data in combinspy)
            {
                DailyDataout tempdailyout = new DailyDataout();
                tempdailyout = data;

                if (tempdailyout.symbol == symbol)
                {
                    beta = ((tempdailyout.close / tempdailyout.open) / (tempdailyout.spyclose / tempdailyout.spyopen) - 1) * 100;
                    tempdailyout.beta = beta;
                }
                else
                {
                    symbol = tempdailyout.symbol;
                    beta = ((tempdailyout.close / tempdailyout.open) / (tempdailyout.spyclose / tempdailyout.spyopen) - 1) * 100;
                }
                newcombinspy.Add(tempdailyout);
            }

            #endregion

              EngineOut.WriteFile("Daily\\temp.csv", newcombinspy);
            }
            #endregion

            #endregion

            #region date thrshold

            DateTime lastDate = DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

            if (lastDate.DayOfWeek == DayOfWeek.Sunday)
            {
                if (strs3.ContainsKey(lastDate.AddDays(-2).ToString("yyyyMMdd")) || strs3.ContainsKey(lastDate.AddDays(-3).ToString("yyyyMMdd")))
                {
                    lastDate = lastDate.AddDays(-4);
                }
                else
                lastDate = lastDate.AddDays(-3);
            }
            else if (lastDate.DayOfWeek == DayOfWeek.Saturday)
            {
                if (strs3.ContainsKey(lastDate.AddDays(-1).ToString("yyyyMMdd")) || strs3.ContainsKey(lastDate.AddDays(-2).ToString("yyyyMMdd")))
                {
                    lastDate = lastDate.AddDays(-3);
                }
                else
                    lastDate = lastDate.AddDays(-2);
            }
            else if (lastDate.DayOfWeek == DayOfWeek.Monday)
            {
                if (strs3.ContainsKey(lastDate.ToString("yyyyMMdd")) || strs3.ContainsKey(lastDate.AddDays(-3).ToString("yyyyMMdd")))
                {
                    lastDate = lastDate.AddDays(-4);
                }
                    else
                lastDate = lastDate.AddDays(-3);
            }
            else if (lastDate.DayOfWeek == DayOfWeek.Tuesday)
            {
                if (strs3.ContainsKey(lastDate.ToString("yyyyMMdd")) || strs3.ContainsKey(lastDate.AddDays(-1).ToString("yyyyMMdd")))
                {
                    lastDate = lastDate.AddDays(-4);
                }
                else
                    lastDate = lastDate.AddDays(-1);

            }
            else
            {
                if (strs3.ContainsKey(lastDate.ToString("yyyyMMdd")) || strs3.ContainsKey(lastDate.AddDays(-1).ToString("yyyyMMdd")))
                {
                    lastDate = lastDate.AddDays(-2);
                }
                else
                    lastDate = lastDate.AddDays(-1);

            }

            #endregion

            strategy2ExitbySumBeta(quarter, threshold, buyinpower, (decimal)5, lastDate);

            DailyGroupbysymbol(quarter, threshold);

            #region create daily report

            //FileHelperEngine enginDR = new FileHelperEngine(typeof(DailyDataout));
            //enginDR.WriteFile(string.Format("DailyReport\\{0}.{1}.D.csv", quarter, Convert.ToInt32(threshold * new decimal(100))), ReportEaring);

            DailyDataout[] ReportEaring = (DailyDataout[])EngineOut.ReadFile(string.Format("DailyReport\\{0}.{1}.D.csv", quarter, Convert.ToInt32(threshold * new decimal(100))));

            var DailyReport = ReportEaring.GroupBy(d => d.date).Select(d => new DailyReport
            {
              date=d.Key,
              pnl=d.Sum(dd=>dd.pnl)+d.Sum(dd=>dd.spypnl),
              pnlovernight=d.Sum(dd=>dd.overnightpnl)+d.Sum(dd=>dd.overnightspypnl),
              pnlday=d.Sum(dd=>dd.daypnl)+d.Sum(dd=>dd.dayspypnl),
              longcount=d.Where(dd=>dd.threshold>0).Count(),
              shortcount=d.Where(dd=>dd.threshold<0).Count(),
              longpnl=d.Where(dd=>dd.threshold>0).Sum(dd=>dd.pnl),
              shortpnl = d.Where(dd => dd.threshold < 0).Sum(dd => dd.pnl),
              qua=quarter,
              lose10=d.Sum(dd=>dd.lose10),
              win10=d.Sum(dd=>dd.win10),
              hspypnl = d.Sum(dd => dd.spypnl),

            }).OrderBy(d=>d.date);
            #endregion

            #region get the bp and accpnl daily
            List<DailyReport> newDailyReport = new List<DailyReport>();
            decimal accPnl = 0;
            foreach(var date in DailyReport)
            {
                DailyReport tempdailyreport = new DailyReport();
                tempdailyreport = date;

                accPnl = accPnl + date.pnl;
                tempdailyreport.accPnl = accPnl;
                tempdailyreport.bp = Math.Max(date.longcount, date.shortcount) * 2 * buyinpower;
                newDailyReport.Add(tempdailyreport);
            }
            #endregion

            #region get the dollar sharpe
            decimal avgPnl = newDailyReport.Select(d => d.accPnl).Last() / newDailyReport.Where(d => d.pnl != 0).Count();

            List<DailyReport> finalDailyReport = new List<DailyReport>();
            decimal SD = 0;
            int count = 1;
            foreach(var date in newDailyReport)
            {
                DailyReport tempdailyreport = new DailyReport();
                tempdailyreport = date;

                SD = SD + (date.pnl - avgPnl) * (date.pnl - avgPnl);

                if (count != 1)
                    date.dollarSharp = avgPnl / (decimal)(Math.Sqrt(Convert.ToDouble(SD) / ((count - 1)*252)));
                finalDailyReport.Add(tempdailyreport);
                count++;
            }

            FileHelperEngine fileHelperEngine5 = new FileHelperEngine(typeof(DailyReport));
            fileHelperEngine5.HeaderText = "date,longpnl,shortpnl,longcount,shortcount,quarter,dollarsharp,bp,win10,lose10,spy hedge pnl,pnl overnight, pnl day,pnl,acc pnl";
            if (!File.Exists("DailyReport\\R.csv"))
            {
                fileHelperEngine5.WriteFile(string.Format("DailyReport\\R.csv", quarter, Convert.ToInt32(threshold * new decimal(100))), finalDailyReport);
            }
            else
            {
                fileHelperEngine5.AppendToFile(string.Format("DailyReport\\R.csv", quarter, Convert.ToInt32(threshold * new decimal(100))), finalDailyReport);
            }

            #endregion

            TimeSpan en = DateTime.Now.TimeOfDay;
            Console.WriteLine(en-st);
        }
Exemplo n.º 3
0
        private static void readdaily2(decimal threshold, int buyinpower, string date)
        {
            bool flag2;
            bool flag3;
            bool flag4;
            bool flag5;
            bool flag6;
            bool flag7;
            bool flag8;
            bool flag9;
            bool flag10;
            TimeSpan timeOfDay = DateTime.Now.TimeOfDay;
            string str1 = "20140401";
            Dictionary<string, string> strs = new Dictionary<string, string>();
            FileStream fileStream = new FileStream("bio.csv", FileMode.Open);
            StreamReader streamReader = new StreamReader(fileStream);
            streamReader.BaseStream.Seek((long)0, SeekOrigin.Begin);
            string str2 = streamReader.ReadLine();
            while (true)
            {
                flag2 = (str2 == null ? false : str2 != "");
                if (!flag2)
                {
                    break;
                }
                strs[str2] = str2;
                str2 = streamReader.ReadLine();
            }
            streamReader.Close();
            streamReader.Dispose();
            fileStream.Close();
            fileStream.Dispose();
            FileHelperEngine fileHelperEngine = new FileHelperEngine(typeof(DailyData1));
            //FileHelperEngine fileHelperEngine1 = new FileHelperEngine(typeof(DailyDataReport));
            DailyData1[] dailyData1Array = (DailyData1[])fileHelperEngine.ReadFile(string.Format("Daily\\DailyQua\\20141.csv", new object[0]));
            FileHelperEngine fileHelperEngine2 = new FileHelperEngine(typeof(unionearingdate));
            unionearingdate[] unionearingdateArray = (unionearingdate[])fileHelperEngine2.ReadFile("Daily\\finalall.csv");
            IEnumerable<unionearingdate> unionearingdates1 = unionearingdateArray.Where<unionearingdate>((unionearingdate data) =>
            {
                bool flag = data.date >= DateTime.ParseExact(str1, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                return flag;
            }).Where<unionearingdate>((unionearingdate data) =>
            {
                bool flag;
                if (Math.Abs(data.threshold) < threshold)
                {
                    flag = false;
                }
                else if (!(data.threshold > new decimal(0)) || !(data.high >= data.maxhigh))
                {
                    flag = (data.threshold >= new decimal(0) ? false : data.low <= data.minlow);
                }
                else
                {
                    flag = true;
                }
                bool flag1 = flag;
                return flag1;
            });
            fileHelperEngine2.WriteFile("Daily\\test1.csv", unionearingdates1.Where<unionearingdate>((unionearingdate dd) =>
            {
                bool flag = dd.high >= new decimal(5);
                return flag;
            }));
            unionearingdate[] unionearingdateArray1 = (unionearingdate[])fileHelperEngine2.ReadFile("Daily\\test1.csv");
            List<unionearingdate> unionearingdates2 = new List<unionearingdate>();
            unionearingdate[] unionearingdateArray2 = unionearingdateArray1;
            for (int i = 0; i < (int)unionearingdateArray2.Length; i++)
            {
                unionearingdate _unionearingdate = unionearingdateArray2[i];
                if (!strs.ContainsKey(_unionearingdate.symbol))
                {
                    unionearingdates2.Add(_unionearingdate);
                }
            }
            DailyData1[] dailyData1Array1 = dailyData1Array;
            Func<DailyData1, IEnumerable<unionearingdate>> func = (DailyData1 db) =>
            {
                IEnumerable<unionearingdate> unionearingdates = unionearingdates2;
                return unionearingdates;
            };
            var collection = ((IEnumerable<DailyData1>)dailyData1Array1).SelectMany(func, (DailyData1 db, unionearingdate e) =>
            {
                var variable = new { db = db, e = e };
                return variable;
            });
            var collection1 = collection.Where((argument0) =>
            {
                bool flag;
                flag = (argument0.db.symbol != argument0.e.symbol ? false : argument0.db.date >= argument0.e.date);
                bool flag1 = flag;
                return flag1;
            });
            IEnumerable<DailyDataout> dailyDataouts = collection1.Select((argument1) =>
            {
                DailyDataout dailyDataout = new DailyDataout();
                dailyDataout.symbol = argument1.db.symbol;
                dailyDataout.date = argument1.db.date;
                dailyDataout.open = argument1.db.open;
                dailyDataout.high = argument1.db.high;
                dailyDataout.low = argument1.db.low;
                dailyDataout.close = argument1.db.close;
                dailyDataout.volume = argument1.db.volume;
                dailyDataout.threshold = argument1.e.threshold;
                dailyDataout.adv = argument1.db.adv;
                DailyDataout dailyDataout1 = dailyDataout;
                return dailyDataout1;
            });
            DailyData1[] dailyData1Array2 = dailyData1Array;
            IEnumerable<DailyData1> dailyData1s = ((IEnumerable<DailyData1>)dailyData1Array2).Where<DailyData1>((DailyData1 d) =>
            {
                bool flag = d.symbol == "SPY";
                return flag;
            });
            IEnumerable<DailyDataout> dailyDataouts1 = dailyDataouts;
            IEnumerable<DailyData1> dailyData1s1 = dailyData1s;

            var dailyDataouts2 = from db in dailyDataouts1
                                 join x in dailyData1s on db.date equals x.date
                                 select new DailyDataout
                                 {
                                      symbol = db.symbol,
               date = db.date,
               open = db.open,
               high = db.high,
                low = db.low,
               close = db.close,
               volume = db.volume,
               threshold = db.threshold,
               adv = db.adv,
                spyclose = x.close,
               spyopen = x.open,
                                 };

            //var func1 = (DailyDataout db) =>
            //{
            //    var variable = new { date = db.date };
            //    return variable;
            //};
            //var func2 = (DailyData1 x) =>
            //{
            //    var variable = new { date = x.date };
            //    return variable;
            //};
            //IEnumerable<DailyDataout> dailyDataouts2 = dailyDataouts1.Join(dailyData1s1, func1, func2, (DailyDataout db, DailyData1 x) =>
            //{
            //    DailyDataout dailyDataout = new DailyDataout();
            //    dailyDataout.symbol = db.symbol;
            //    dailyDataout.date = db.date;
            //    dailyDataout.open = db.open;
            //    dailyDataout.high = db.high;
            //    dailyDataout.low = db.low;
            //    dailyDataout.close = db.close;
            //    dailyDataout.volume = db.volume;
            //    dailyDataout.threshold = db.threshold;
            //    dailyDataout.adv = db.adv;
            //    dailyDataout.spyclose = x.close;
            //    dailyDataout.spyopen = x.open;
            //    DailyDataout dailyDataout1 = dailyDataout;
            //    return dailyDataout1;
            //});
            FileHelperEngine fileHelperEngine3 = new FileHelperEngine(typeof(DailyDataout));
            fileHelperEngine3.WriteFile("Daily\\test.csv", dailyDataouts2);
            DailyDataout[] dailyDataoutArray = (DailyDataout[])fileHelperEngine3.ReadFile("Daily\\test.csv");
            IOrderedEnumerable<DailyDataout> dailyDataouts3 = ((IEnumerable<DailyDataout>)dailyDataoutArray).OrderBy<DailyDataout, string>((DailyDataout d) =>
            {
                string str = d.symbol;
                return str;
            });
            IOrderedEnumerable<DailyDataout> dailyDataouts4 = dailyDataouts3.ThenBy<DailyDataout, DateTime>((DailyDataout d) =>
            {
                DateTime dateTime = d.date;
                return dateTime;
            });
            List<livedataReport> livedataReports = new List<livedataReport>();
            string str3 = "";
            decimal num = new decimal(0);
            decimal num1 = new decimal(0);
            decimal num2 = new decimal(0);
            decimal num3 = new decimal(0);
            decimal num4 = new decimal(0);
            bool flag11 = false;
            bool flag12 = false;
            int num5 = 0;
            string str4 = "NO";
            int num6 = 0;
            foreach (DailyDataout dailyDataout2 in dailyDataouts4)
            {
                livedataReport _livedataReport = new livedataReport();
                _livedataReport.date = dailyDataout2.date;
                _livedataReport.adv = dailyDataout2.adv;
                if (!(dailyDataout2.symbol == str3))
                {
                    str3 = dailyDataout2.symbol;
                    num = dailyDataout2.spyclose;
                    num5 = 0;
                    num1 = new decimal(0);
                    num2 = new decimal(0);
                    num3 = dailyDataout2.high;
                    num4 = dailyDataout2.low;
                    flag12 = false;
                    flag11 = false;
                    if (dailyDataout2.threshold > new decimal(0))
                    {
                        flag4 = (flag11 ? true : !(dailyDataout2.close > num3 * dailyDataout2.spyclose / num));
                        if (!flag4)
                        {
                            num1 = Math.Max(dailyDataout2.open, (num3 * dailyDataout2.spyclose) / num);
                            num5 = Convert.ToInt32(buyinpower / num1);
                            str4 = "Yes";
                            num6 = num5;
                            flag11 = true;
                        }
                        _livedataReport.symbol = str3;
                        _livedataReport.side = "Long";
                        _livedataReport.pricein = (num3 * dailyDataout2.spyclose) / num;
                        _livedataReport.priceout = (dailyDataout2.low * dailyDataout2.spyclose) / num;
                        _livedataReport.size = Convert.ToInt32(buyinpower / _livedataReport.pricein);
                        _livedataReport.AlreadyOpenSize = num6;
                        _livedataReport.AlreadyOpen = str4;
                    }
                    else if (dailyDataout2.threshold < new decimal(0))
                    {
                        flag3 = (flag11 ? true : !(dailyDataout2.close < num4 * dailyDataout2.spyclose / num));
                        if (!flag3)
                        {
                            num1 = Math.Min(dailyDataout2.open, (num4 * dailyDataout2.spyclose) / num);
                            num5 = Convert.ToInt32(buyinpower / num1);
                            flag11 = true;
                            str4 = "Yes";
                            num6 = num5;
                        }
                        _livedataReport.symbol = str3;
                        _livedataReport.side = "Short";
                        _livedataReport.pricein = (num4 * dailyDataout2.spyclose) / num;
                        _livedataReport.priceout = (dailyDataout2.high * dailyDataout2.spyclose) / num;
                        _livedataReport.size = Convert.ToInt32(buyinpower / _livedataReport.pricein);
                        _livedataReport.AlreadyOpenSize = num6;
                        _livedataReport.AlreadyOpen = str4;
                    }
                    livedataReports.Add(_livedataReport);
                }
                else if (dailyDataout2.threshold > new decimal(0))
                {
                    flag8 = (!flag11 ? true : flag12);
                    if (!flag8)
                    {
                        if (dailyDataout2.close < ((dailyDataout2.low * dailyDataout2.spyclose) / num))
                        {
                            num2 = (dailyDataout2.low * dailyDataout2.spyclose) / num;
                            flag12 = true;
                        }
                    }
                    flag9 = (!flag11 ? true : flag12);
                    if (!flag9)
                    {
                        num1 = new decimal(-1);
                    }
                    flag10 = (flag11 ? true : !(dailyDataout2.close > num3 * dailyDataout2.spyclose / num));
                    if (!flag10)
                    {
                        num1 = (num3 * dailyDataout2.spyclose) / num;
                        num5 = Convert.ToInt32(buyinpower / num1);
                        str4 = "Yes";
                        num6 = num5;
                        flag11 = true;
                    }
                    _livedataReport.symbol = str3;
                    _livedataReport.side = "Long";
                    if (flag11)
                    {
                        _livedataReport.pricein = num1;
                    }
                    else
                    {
                        _livedataReport.pricein = (num3 * dailyDataout2.spyclose) / num;
                    }
                    if (flag12)
                    {
                        _livedataReport.priceout = num2;
                    }
                    else
                    {
                        _livedataReport.priceout = (dailyDataout2.low * dailyDataout2.spyclose) / num;
                    }
                    _livedataReport.size = Convert.ToInt32(buyinpower / _livedataReport.pricein);
                    _livedataReport.AlreadyOpenSize = num6;
                    _livedataReport.AlreadyOpen = str4;
                    if (!flag12)
                    {
                        livedataReports.Add(_livedataReport);
                    }
                }
                else if (dailyDataout2.threshold < new decimal(0))
                {
                    flag5 = (!flag11 ? true : flag12);
                    if (!flag5)
                    {
                        if (dailyDataout2.close > ((dailyDataout2.high * dailyDataout2.spyclose) / num))
                        {
                            num2 = (dailyDataout2.high * dailyDataout2.spyclose) / num;
                            flag12 = true;
                        }
                    }
                    flag6 = (!flag11 ? true : flag12);
                    if (!flag6)
                    {
                        num1 = new decimal(-1);
                    }
                    flag7 = (flag11 ? true : !(dailyDataout2.close < num4 * dailyDataout2.spyclose / num));
                    if (!flag7)
                    {
                        num1 = (num4 * dailyDataout2.spyclose) / num;
                        num5 = Convert.ToInt32(buyinpower / num1);
                        flag11 = true;
                        str4 = "Yes";
                        num6 = num5;
                    }
                    _livedataReport.symbol = str3;
                    _livedataReport.side = "Short";
                    if (flag11)
                    {
                        _livedataReport.pricein = num1;
                    }
                    else
                    {
                        _livedataReport.pricein = (num4 * dailyDataout2.spyclose) / num;
                    }
                    if (flag12)
                    {
                        _livedataReport.priceout = num2;
                    }
                    else
                    {
                        _livedataReport.priceout = (dailyDataout2.high * dailyDataout2.spyclose) / num;
                    }
                    _livedataReport.size = Convert.ToInt32(buyinpower / _livedataReport.pricein);
                    _livedataReport.AlreadyOpenSize = num6;
                    _livedataReport.AlreadyOpen = str4;
                    if (!flag12)
                    {
                        livedataReports.Add(_livedataReport);
                    }
                }
            }
            IEnumerable<livedataReport> livedataReports1 = livedataReports.Where<livedataReport>((livedataReport d) =>
            {
                bool flag = d.date == DateTime.Parse(date);
                return flag;
            });
            FileHelperEngine fileHelperEngine4 = new FileHelperEngine(typeof(livedataReport));
            fileHelperEngine4.HeaderText="Symbol,date,AlreadyOpen,AlreadyOpenSize,Side,EnterPrice,ExitPrice,size,adv";
            fileHelperEngine4.WriteFile("Daily\\Update.D.csv", livedataReports1);
            TimeSpan timeSpan = DateTime.Now.TimeOfDay;
            Console.WriteLine(timeSpan - timeOfDay);
        }