Beispiel #1
0
 public TechCalculate(ObjectType objectType, TechCycle cycle, string objectCode, IList <PriceInfo> priceList)
 {
     this.ObjectType = objectType;
     this.Cycle      = cycle;
     this.PriceList  = priceList;
     this.ObjectCode = objectCode;
 }
        public void AddPriceInfo(string categoryCode, PriceInfo info, TechCycle cycle)
        {
            using (var entity = new StockManDBEntities())
            {
                switch (cycle)
                {
                case TechCycle.day:
                    entity.data_category_day_latest.Add(new data_category_day_latest()
                    {
                        object_code = categoryCode,
                        code        = categoryCode + "_" + info.date.ToString("yyyyMMdd"),
                        date        = info.date,
                        high        = info.high,
                        low         = info.low,
                        open        = info.open,
                        price       = info.price,
                        yestclose   = info.yestclose,
                        volume      = info.volume
                    });
                    break;

                case TechCycle.week:
                    entity.data_category_week_latest.Add(new data_category_week_latest()
                    {
                        object_code = categoryCode,
                        code        = categoryCode + "_" + info.date.ToString("yyyyMMdd"),
                        date        = info.date,
                        high        = info.high,
                        low         = info.low,
                        open        = info.open,
                        price       = info.price,
                        yestclose   = info.yestclose,
                        volume      = info.volume
                    });
                    break;

                case TechCycle.month:
                    entity.data_category_month_latest.Add(new data_category_month_latest()
                    {
                        object_code = categoryCode,
                        code        = categoryCode + "_" + info.date.ToString("yyyyMMdd"),
                        date        = info.date,
                        high        = info.high,
                        low         = info.low,
                        open        = info.open,
                        price       = info.price,
                        yestclose   = info.yestclose,
                        volume      = info.volume
                    });
                    break;
                }
                entity.SaveChanges();
            }
        }
        public void Send(IMessageSender sender)
        {
            this.Log().Info("开始计算个股形态");

            DateTime StartDate0 = stockService.GetLatestDate(ObjectType.Stock, "0601988");
            DateTime StartDate1 = stockService.GetLatestDate(ObjectType.Stock, "0601318");

            var StartDate = StartDate0.CompareTo(StartDate1) >= 0 ? StartDate0 : StartDate1;

            IList <stockcategory> cateList = cateService.FindAll();

            TechCycle[] cycleList = new TechCycle[] { TechCycle.day, TechCycle.week, TechCycle.month };
            var         log       = this.Log();

            foreach (var category in cateList)
            {
                if (StartDate.ToString("yyyyMMdd") == DateTime.Now.ToString("yyyyMMdd"))
                {
                    log.Info(string.Format("导入今天日线数据,分类:{1}:从日期{0}", StartDate.ToString("yyyy-MM-dd"), category.name));

                    var task1 = new PriceUpdate
                    {
                        StartDate = StartDate,
                        CateCode  = category.code
                    };
                    sender.Send(JsonConvert.SerializeObject(task1));
                    //ImportTodayPrice(stockList);
                }
                else
                {
                    IList <data.stock> stockList = stockService.GetStockByCategory(category.code);

                    foreach (var stock in stockList)
                    {
                        var task1 = new PriceUpdate
                        {
                            StartDate = StartDate,
                            StockCode = stock.code
                        };
                        sender.Send(JsonConvert.SerializeObject(task1));
                        //log.Info(string.Format("导入日线开始,股票:{1}:从日期{0}", StartDate.ToString("yyyy-MM-dd"), stock.name));
                        //ImportDay(stock, StartDate);
                        //log.Info(string.Format("导入周线开始,股票:{1}:从日期{0}", StartDate.ToString("yyyy-MM-dd"), stock.name));
                        //ImportWeek(stock, StartDate);
                        //log.Info(string.Format("导入月线开始,股票:{1}:从日期{0}", StartDate.ToString("yyyy-MM-dd"), stock.name));
                        //ImportMonth(stock, StartDate);
                        //log.Info(string.Format("导入结束,股票:{1}:从日期{0}", StartDate.ToString("yyyy-MM-dd"), stock.name));
                    }
                }
            }
        }
        private IList <TaskMessage> ComputeStockState(Task.Interface.IMessageSender sender)
        {
            this.Log().Info("开始计算个股形态");
            IList <stockcategory> cateList = cateService.FindAll();


            IList <TaskMessage> msgList = new List <TaskMessage>();

            TechCycle[] cycleList = new TechCycle[] { TechCycle.day, TechCycle.week, TechCycle.month };
            foreach (var category in cateList)
            {
                IList <stock> stockList = stockService.GetStockByCategory(category.code);

                foreach (var stock in stockList)
                {
                    this.Log().Info("计算股票:" + stock.name);

                    foreach (var cycle in cycleList)
                    {
                        var task1 = new IndexTask
                        {
                            type  = ObjectType.Stock,
                            code  = stock.code,
                            cycle = cycle
                        };
                        sender.Send(JsonConvert.SerializeObject(task1));
                        Thread.Sleep(100);
                    }
                }
            }

            //string[] list = new string[] { "0600265" };
            //foreach (var code in list)
            //{
            //    foreach (var cycle in cycleList)
            //    {
            //        var task1 = new IndexTask
            //        {
            //            type = ObjectType.Stock,
            //            code = code,
            //            cycle = cycle
            //        };
            //        sender.Send(JsonConvert.SerializeObject(task1));
            //    }
            //}

            return(msgList);
        }
        public PriceInfo GetCurrentData(ObjectType objType, TechCycle cycle, string code)
        {
            string tableName = string.Format("data_{0}_day_latest", objType.ToString());

            switch (cycle)
            {
            case TechCycle.day:
                if (objType == ObjectType.Stock)
                {
                    tableName = "stock";
                }
                else if (objType == ObjectType.Object)
                {
                    tableName = "customobject";
                }
                else if (objType == ObjectType.Category)
                {
                    tableName = "stockcategory";
                }
                string statisSql = string.Format("select code,open,price,yestclose,high,low,percent,updown,volume,turnover from {0} a where a.code = @p0", tableName);

                using (var entity = new StockManDBEntities())
                {
                    var racentPrice = entity.Database.SqlQuery <PriceInfo>(statisSql, code);

                    //return getDataByRange(code, tableName, endDate, startDate);
                    return(racentPrice.FirstOrDefault());
                }

            //break;
            case TechCycle.week:
                DateTime endDate   = DateTime.Now.AddDays(DayOfWeek.Sunday - DateTime.Now.DayOfWeek);
                DateTime startDate = endDate.AddDays(-7);
                return(getDataByRange(code, tableName, endDate, startDate));

            //break;
            case TechCycle.month:

                DateTime nextMonthData = DateTime.Now.AddMonths(1);
                DateTime endDate0      = new DateTime(nextMonthData.Year, nextMonthData.Month, 1);
                DateTime startDate0    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                return(getDataByRange(code, tableName, endDate0, startDate0));
                //break;
            }


            return(null);
        }
        protected IList <IndexDefinitionInfo> index_definition_infos(TechCycle cycle)
        {
            var list = indexService.FindAll();

            this.Log().Info(list.Count + "");
            IList <IndexDefinitionInfo> defineList = list.Select(define => new IndexDefinitionInfo
            {
                code             = define.code,
                name             = define.name,
                fields           = JsonConvert.DeserializeObject <IList <Field> >(define.fields),
                parameter        = define.parameter,
                table_name       = "Tech_Stock_" + define.table_name + "_" + cycle.ToString(),
                algorithm_script = define.algorithm_script
            }).ToList();

            return(defineList);
        }
        public IList <PriceInfo> GetPriceInfo(string categoryCode, TechCycle type, DateTime date)
        {
            string sql = string.Format(@"SELECT code
                      ,date
                      ,open
                      ,low
                      ,price
                      ,updown                   
                      ,yestclose                    
                      ,volume
                      ,high
                      ,percent
                    ,turnover
                  FROM Data_Category_{0}_Latest where object_code='{1}' and date='{2}'", type, categoryCode, date.ToString("yyyy-MM-dd"));

            using (var entity = new StockManDBEntities())
            {
                return(entity.Database.SqlQuery <PriceInfo>(sql).ToList());
            }
        }
        public IList <PriceInfo> GetObjectData(string entityType, TechCycle cycle, string objCode)
        {
            //data_object_day_latest
            using (StockManDBEntities entity = new StockManDBEntities())
            {
                string sql = string.Format(@"SELECT  code
                      ,date
                      ,open
                      ,low
                      ,price
                      ,updown                  
                      ,yestclose                    
                      ,volume
                      ,high
                      ,percent
                      ,turnover
                  FROM Data_{0}_{1}_Latest where object_code='{2}' order by code", entityType, cycle, objCode);


                return(entity.Database.SqlQuery <PriceInfo>(sql).ToList());
            }
        }
        public string[][] GetIndexData(string entityType, string techName, TechCycle cycle, string dataId)
        {
            using (StockManDBEntities entity = new StockManDBEntities())
            {
                var indexDefine = entity.indexdefinition.FirstOrDefault(p => p.name == techName);

                if (indexDefine == null)
                {
                    return(null);
                }

                var    fields    = JsonConvert.DeserializeObject <IList <Field> >(indexDefine.fields);
                string tableName = "Tech_" + entityType + "_" + indexDefine.table_name + "_" + cycle;
                string sql       = @"select * from " + tableName + " where f_code='" + dataId + "' order by date desc limit 500";

                entity.Database.Connection.Open();
                using (entity.Database.Connection)
                {
                    System.Data.IDbCommand commond = entity.Database.Connection.CreateCommand();
                    commond.CommandText = sql;
                    IDataReader reader = commond.ExecuteReader();

                    List <string[]> indexData = new List <string[]>();
                    while (reader.Read())
                    {
                        var data = new List <string>();
                        data.Add(DateTime.Parse(reader["date"] + "").ToString("yyyyMMdd"));

                        data.AddRange(fields.Select(filed => reader[filed.name] + ""));

                        indexData.Add(data.ToArray());
                    }
                    entity.Database.Connection.Close();
                    indexData.Reverse();
                    return(indexData.ToArray());
                }
            }
        }
        private void ComputeCategoryState(Task.Interface.IMessageSender sender)
        {
            IList <stockcategory> cateList = cateService.FindAll();

            TechCycle[] cycleList = new TechCycle[] { TechCycle.day, TechCycle.week, TechCycle.month };
            this.Log().Info("开始计算行业形态");
            foreach (var category in cateList)
            {
                this.Log().Info("计算行业:" + category.name);

                foreach (var cycle in cycleList)
                {
                    var task1 = new IndexTask
                    {
                        type  = ObjectType.Category,
                        code  = category.code,
                        cycle = cycle
                    };
                    sender.Send(JsonConvert.SerializeObject(task1));
                    Thread.Sleep(100);
                }
            }
        }
        private void ComputeMarketState(Task.Interface.IMessageSender sender)
        {
            var objList = objService.FindAll();

            TechCycle[] cycleList = new TechCycle[] { TechCycle.day, TechCycle.week, TechCycle.month };

            this.Log().Info("开始计算大盘形态");
            foreach (var obj in objList)
            {
                this.Log().Info("计算大盘:" + obj.name);

                foreach (var cycle in cycleList)
                {
                    var task1 = new IndexTask
                    {
                        type  = ObjectType.Object,
                        code  = obj.code,
                        cycle = cycle
                    };
                    sender.Send(JsonConvert.SerializeObject(task1));
                    Thread.Sleep(100);
                }
            }
        }
Beispiel #12
0
        private void Calculate(IndexDefinitionInfo define, TechCycle cycle)
        {
            IIndex indexGener = new Dma();// CodeHelper.GetIEvaluator(define.server_algorithm_code);

            IList <stockcategory> cateList = cateService.GetCategoryList("tencent");

            int tatol = 0;

            foreach (var category in cateList)
            {
                IList <stock> stockList = stockService.GetStockByCategory(category.code);

                foreach (stock stock in stockList)
                {
                    IList <PriceInfo> list          = stockService.GetStockPriceDayInfo(stock);
                    IList <IndexData> listIndexData = GetLastIndexData(stock, define);

                    var result = indexGener.GetState(listIndexData);
                    this.Log().Info(stock.name + "_" + result);
                    using (StockManDBEntities entity = new StockManDBEntities())
                    {
                        var cate        = "1";
                        var code        = cate + "_" + stock.code + "_" + define.code;
                        var objectState = entity.objectstate.FirstOrDefault(p => p.code == code);
                        if (objectState == null)
                        {
                            var temp = new objectstate()
                            {
                                code          = code,
                                category_code = cate,
                                object_code   = stock.code,
                                index_code    = define.code,
                                date          = DateTime.Now
                            };

                            switch (cycle)
                            {
                            case TechCycle.day:
                                temp.day = (int)result;
                                break;

                            case TechCycle.week:
                                temp.week = (int)result;
                                break;

                            default:
                                temp.month = (int)result;
                                break;
                            }
                            entity.objectstate.Add(temp);
                        }
                        else
                        {
                            switch (cycle)
                            {
                            case TechCycle.day:
                                objectState.last_day = objectState.day;
                                objectState.day      = (int)result;
                                break;

                            case TechCycle.week:
                                objectState.last_week = objectState.week;
                                objectState.week      = (int)result;
                                break;

                            default:
                                objectState.last_month = objectState.month;
                                objectState.month      = (int)result;
                                break;
                            }
                        }

                        entity.SaveChanges();
                    }

                    if (++tatol > 3)
                    {
                        break;
                    }
                }
                if (tatol > 3)
                {
                    break;
                }
            }
        }
Beispiel #13
0
        private void InitCategoryIndexByMonth(string categoryCode)
        {
            //获取某只股票的所有价格列表
            TechCycle cycle = TechCycle.day;

            //获取日线数据
            var dayList = cateService.GetPriceInfo(categoryCode, TechCycle.day);

            if (dayList.Count == 0)
            {
                return;
            }

            var weekList = new List <PriceInfo>();

            DateTime startTime = dayList[0].date;

            PriceInfo lastWeekPrice = null;

            while (startTime < DateTime.Now)
            {
                DateTime nextDate   = startTime.AddMonths(1);
                DateTime endTime    = new DateTime(nextDate.Year, nextDate.Month, 1);
                var      rangePrice = dayList.Where(p => p.date >= startTime && p.date < endTime).OrderBy(p => p.date).ToList();

                if (rangePrice.Count == 0)
                {
                    startTime = endTime;
                    continue;
                }
                var lastPrice = rangePrice[rangePrice.Count - 1];

                decimal?open     = rangePrice[0].price;
                decimal?close    = lastPrice.price;
                decimal?high     = rangePrice.Max(p => p.price);
                decimal?low      = rangePrice.Min(p => p.price);
                decimal?volume   = rangePrice.Sum(p => p.volume);
                decimal?turnover = rangePrice.Sum(p => p.turnover);

                decimal?percent   = 0;
                decimal?updown    = 0;
                decimal?yestclose = 0;
                if (lastWeekPrice != null)
                {
                    yestclose = lastWeekPrice.price;
                    updown    = close - yestclose;
                    if (yestclose != 0)
                    {
                        percent = updown / yestclose;
                    }
                }
                var currentPrice = new PriceInfo
                {
                    code      = categoryCode,
                    open      = open,
                    price     = close,
                    low       = low,
                    high      = high,
                    date      = lastPrice.date,
                    percent   = Math.Round(percent ?? 0, 2),
                    turnover  = turnover,
                    updown    = updown,
                    volume    = volume,
                    yestclose = yestclose
                };
                weekList.Add(currentPrice);

                lastWeekPrice = currentPrice;
                startTime     = endTime;
            }

            try
            {
                cateService.AddPriceByMonth <data_category_month_latest>(weekList, false);

                this.Log().Info(string.Format("行业指数计算完成:周期:{0},类别:{1}", TechCycle.month, categoryCode));
            }
            catch (Exception ex)
            {
                //(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.Data.Entity.Validation.DbEntityValidationResult>(((System.Data.Entity.Validation.DbEntityValidationException)(ex)).EntityValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbEntityValidationResult>)).Items[0].ValidationErrors
                this.Log().Error(ex.Message);
            }
        }
Beispiel #14
0
        private void InitCategoryIndexByDay(string categoryCode)
        {
            //获取某只股票的所有价格列表
            TechCycle cycle     = TechCycle.day;
            var       stocks    = stockService.GetPriceInfo("0600000", cycle);
            decimal   yestclose = 0;
            decimal   baseIndex = 100;
            decimal   baseValue = 0;

            //计算每个周期的指数值
            for (int i = 0; i < stocks.Count; i++)
            {
                var stock     = stocks[i];
                var priceList = stockService.GetStockPriceByDate(categoryCode, cycle, stock.date);
                if (priceList == null || priceList.Count == 0)
                {
                    continue;
                }
                decimal total = 0, vol = 0, turnover = 0, index = 0;
                foreach (var priceInfo in priceList)
                {
                    total    += priceInfo.price ?? 1 * priceInfo.volume ?? 1;
                    vol      += priceInfo.volume ?? 1;
                    turnover += priceInfo.turnover ?? 1;
                }

                if (baseValue == 0)
                {
                    baseValue = total;
                    index     = 100;
                }
                else
                {
                    index = (total / baseValue) * 100;
                }

                var info = new data.PriceInfo
                {
                    code      = categoryCode,
                    date      = stock.date,
                    price     = Math.Round(index, 2),
                    high      = 0,
                    low       = 0,
                    yestclose = yestclose,
                    volume    = vol,
                    turnover  = turnover,
                    open      = Math.Round(index, 2),
                };

                yestclose = index;

                try
                {
                    //cateService.AddPriceInfo(categoryCode, info, cycle);
                    //if (cycle == TechCycle.day)
                    //{
                    cateService.AddPriceByDay <data_category_day_latest>(new List <PriceInfo>()
                    {
                        info
                    }, true);
                    //}
                    //else if (cycle == TechCycle.week)
                    //{
                    //    cateService.AddPriceByWeek<data_category_week_latest>(new List<PriceInfo>() { info }, true);

                    //}
                    //else if (cycle == TechCycle.month)
                    //{
                    //    cateService.AddPriceByMonth<data_category_month_latest>(new List<PriceInfo>() { info }, true);

                    //}

                    this.Log().Info(string.Format("行业指数:周期:{0},日期:{1},类别:{2},数值:{3}", cycle, info.date, categoryCode, info.price));
                }
                catch (Exception ex)
                {
                    //(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.Data.Entity.Validation.DbEntityValidationResult>(((System.Data.Entity.Validation.DbEntityValidationException)(ex)).EntityValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbEntityValidationResult>)).Items[0].ValidationErrors


                    this.Log().Error(ex.Message);
                }
            }
        }
        public string GetHistoryData(ObjectType objType, TechCycle cycle, string code)
        {
            //e[0],//日期
            //e[1],//开盘
            //e[2],//收盘
            //e[3],//最高
            //e[4],//最低
            //e[5],//成交量
            //e[6],//涨跌额
            //e[7],//涨跌幅
            using (var entity = new StockManDBEntities())
            {
                string tableName = string.Format("data_{0}_{1}_latest", objType.ToString(), cycle);
                string where = string.Empty;
                switch (cycle)
                {
                case TechCycle.day:
                    //where = string.Format("and date < (select max(date) from {0} where object_code='{1}')", tableName, code);
                    break;

                case TechCycle.week:
                    DateTime endDate   = DateTime.Now.AddDays(DayOfWeek.Sunday - DateTime.Now.DayOfWeek);
                    DateTime startDate = endDate.AddDays(-7);
                    //return getDataByRange(code, tableName, endDate, startDate);
                    where = string.Format(" and date < '{0}'", startDate.ToString("yyyy-MM-dd"));
                    break;

                case TechCycle.month:

                    DateTime startDate0 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);

                    where = string.Format(" and date <= '{0}'", startDate0.ToString("yyyy-MM-dd"));
                    break;
                }
                string sql = string.Format(@"SELECT * FROM ( SELECT  
                      date
                      ,open
                      ,price
                      ,high
                      ,low
                      ,volume
                      ,updown 
                      ,percent                  
                      ,yestclose                      
                      ,turnover
                  FROM {0} where object_code='{1}' {2} order by date desc limit 150) a order by a.date ASC", tableName, code, where);


                entity.Database.Connection.Open();
                using (entity.Database.Connection)
                {
                    System.Data.IDbCommand commond = entity.Database.Connection.CreateCommand();
                    commond.CommandText = sql;
                    IDataReader reader = commond.ExecuteReader();

                    string dataStr = "";
                    while (reader.Read())
                    {
                        string fstr = string.Format("\"{0}\"", DateTime.Parse(reader["date"] + "").ToString("yyyyMMdd"));
                        for (var i = 1; i < reader.FieldCount; i++)
                        {
                            if (string.IsNullOrEmpty(reader[i] + ""))
                            {
                                fstr += "," + "0";
                            }
                            else
                            {
                                fstr += "," + reader[i];
                            }
                        }
                        fstr = "[" + fstr + "]";

                        if (dataStr.Length == 0)
                        {
                            dataStr = fstr;
                        }
                        else
                        {
                            dataStr += "," + fstr;
                        }
                    }
                    dataStr = "[" + dataStr + "]";
                    entity.Database.Connection.Close();
                    return(dataStr);
                }
            }
        }