Пример #1
0
def write_new_stocks():
    """
    从Tushare取每日新股数据,因Tushare数据限制,最多取到2016-04-26
    
    :return: None
    """
    ts.new_stocks(pause=0.1).to_csv(
        os.path.abspath("{}/{}.csv".format(other_dir, 'newstock')))
Пример #2
0
def ipo_rank():
    new_stk_df=ts.new_stocks()
    # print('info',new_stk_df.info())
    # new_stk_df.dropna(inplace=True,axis=0)
    # print('lens after drop ',len(new_stk_df))
    # new_stk_df['issue_date']=new_stk_df['issue_date'].astype('datetime64[ns]')
    new_stk_df['issue_date']=pd.to_datetime(new_stk_df['issue_date'])
    # new_stk_df['issue_date']=pd.to_datetime(new_stk_df['issue_date'])
    # new_stk_df=new_stk_df.set_index('issue_date')
    # print(new_stk_df2.info())
    # print(new_stk_df2)
    # print(new_stk_df2.truncate(after=date))
    # print(new_stk_df2['2017-11-01':])
    # print(len(new_stk_df))
    # print(new_stk_df.head())
    # print(new_stk_df.head())
    # print(new_stk_df.info())
    df_2017 = new_stk_df[new_stk_df['issue_date']>'2017-01-01']
    # df_2017.to_excel('2017_new_stock.xls')
    # print(new_stk_df.ix['2017-01-01':,:])
    pro=[]
    # print(df_2017.iloc[0]['issue_date'])
    # '''
    for i in range(len(df_2017)):
        s=df_2017.iloc[i]
        p=profit(s['code'],s['issue_date'].strftime('%Y-%m-%d'),'2017-12-29')
        pro.append(p)

    df_2017['raise']=pro

    df_2017.to_excel('2017newstockprofit.xls')
Пример #3
0
def new_stocks(request):

    try:
        data = ts.new_stocks()
        stocksData = np.array(data.values)
        for i in range(len(stocksData)):
            for x in range(len(stocksData[i])):

                if isinstance(stocksData[i][x], float):
                    if math.isnan(stocksData[i][x]):
                        stocksData[i][x] = 0

        res = {
            "columns": [
                'code', 'name', 'ipo_date', 'issue_date', 'amount', 'markets',
                'price', 'pe', 'limit', 'funds', 'ballot'
            ],
            "data":
            json.loads(json.dumps(stocksData, cls=DateEncoder))
        }

    except (BaseException):
        return HttpResponse(BaseException)
    else:
        return HttpResponse(json.dumps(res), content_type="application/json")
Пример #4
0
def ipo_rank():
    new_stk_df = ts.new_stocks()
    # print('info',new_stk_df.info())
    # new_stk_df.dropna(inplace=True,axis=0)
    # print('lens after drop ',len(new_stk_df))
    # new_stk_df['issue_date']=new_stk_df['issue_date'].astype('datetime64[ns]')
    new_stk_df['issue_date'] = pd.to_datetime(new_stk_df['issue_date'])
    # new_stk_df['issue_date']=pd.to_datetime(new_stk_df['issue_date'])
    # new_stk_df=new_stk_df.set_index('issue_date')
    # print(new_stk_df2.info())
    # print(new_stk_df2)
    # print(new_stk_df2.truncate(after=date))
    # print(new_stk_df2['2017-11-01':])
    # print(len(new_stk_df))
    # print(new_stk_df.head())
    # print(new_stk_df.head())
    # print(new_stk_df.info())
    df_2017 = new_stk_df[new_stk_df['issue_date'] > '2017-01-01']
    # df_2017.to_excel('2017_new_stock.xls')
    # print(new_stk_df.ix['2017-01-01':,:])
    pro = []
    # print(df_2017.iloc[0]['issue_date'])
    # '''
    for i in range(len(df_2017)):
        s = df_2017.iloc[i]
        p = profit(s['code'], s['issue_date'].strftime('%Y-%m-%d'),
                   '2017-12-29')
        pro.append(p)

    df_2017['raise'] = pro

    df_2017.to_excel('2017newstockprofit.xls')
Пример #5
0
def new_stocks():
    df = ts.new_stocks()
    df.to_sql('new_stocks',
              db_utils.engine,
              if_exists='append',
              index=False,
              index_label='code')
Пример #6
0
 def get_new_stocks(retry_count=RETRY_COUNT, pause=PAUSE):
     logger.info('Begin get new stocks.')
     try:
         data_df = ts.new_stocks(retry_count, pause)
     except Exception:
         logger.exception('Error get new stocks.')
         return None
     else:
         data_dicts = []
         if data_df is None or data_df.empty:
             logger.warn('Empty get get new stocks.')
         else:
             data_dicts = [{
                 'code': row[0],
                 'xcode': row[1],
                 'name': row[2],
                 'ipo_date': row[3],
                 'issue_date': row[4],
                 'amount': row[5],
                 'markets': row[6],
                 'price': row[7],
                 'pe': row[8],
                 'limit': row[9],
                 'funds': row[10],
                 'ballot': row[11],
                 'insert_date': today_line
             } for row in data_df.values]
             logger.info('Success get get new stocks.')
         return data_dicts
Пример #7
0
 def setNewStocks(self,  isSave = False,tableName = REFERENCE_NEW_STOCKS):
     try:
         df = ts.new_stocks()
         if isSave is True:
             df.to_sql(tableName,self.engine_sql, if_exists='append')
     except IOError,e:
             print e
Пример #8
0
    def __init__(self):

        self.ipo = ts.new_stocks()

        # 日期转化
        self.ipo['ipo_date'] = self.ipo['ipo_date'].astype('datetime64')
        self.start = self.ipo['ipo_date'].iloc[-1]
        self.end = self.ipo['ipo_date'].values[0]
Пример #9
0
def get_new_stock_info():
    df = ts.new_stocks()
    # print(df)
    if df is not None:
        res = df.to_sql(all_new_stock_table, engine, if_exists='replace')
        msg = 'ok' if res is None else res
        print('获取新股数据: ' + msg + '\n')
    else:
        print('获取新股数据: ' + 'None' + '\n')
Пример #10
0
    def __init__(self):
        self.ipo=ts.new_stocks()
        #print ipo.info()

        #日期转化
        self.ipo['ipo_date']=self.ipo['ipo_date'].astype('datetime64')
        #print ipo.info()
        self.start=self.ipo['ipo_date'].values[-1]
        self.end=self.ipo['ipo_date'].values[0]
        print type(self.end)
Пример #11
0
    def __init__(self, init=True):
        """
        初始化,筛除688,300,ST,退市股,新股,低价股,下跌股
        """
        if init:
            self.data = ts.get_today_all()  #今日复盘
            self.updateNMC(self.data)
            # data = ts.get_day_all(date='2021-02-18')   #历史复盘
            filt = self.data['code'].str.contains('^(?!688|605|300|301|8|43)')
            self.data = self.data[filt]
            filt = self.data['name'].str.contains('^(?!S|退市|\*ST|N)')
            self.data = self.data[filt]
            self.data = self.data.drop_duplicates()
            data = self.data[self.data['trade'] >= 2]
            data = data[data['changepercent'] > -3]
            data = data.to_json(orient='records')
            db.get_collection('today').remove()
            base = db.get_collection('base').find()
            industry = {i['code']: i['industry'] for i in base}
            self.intersect = {}
            for i in eval(data):
                db.get_collection('today').insert(i)
            res = db.get_collection('today').find()
            for i in res:
                try:
                    db.get_collection('today').update_many(
                        {'code': i['code']},
                        {'$set': {
                            'industry': industry[i['code']]
                        }})
                except:
                    pass

            # 剔除新股
            try:
                newStock = ts.new_stocks()
                if not newStock.empty:
                    newStock = newStock[newStock.ipo_date > '2020-01-01']
                    for i in newStock['code'].tolist():
                        db.get_collection('today').remove({'code': i},
                                                          multi=True)
            except Exception as e:
                print('newStock Error', e)

            # 剔除停牌
            db.get_collection('today').remove({'open': 0})

            # 龙虎榜
            if not (10 < time.localtime().tm_hour < 18):
                db.get_collection('topList').remove()
                longhu = ts.top_list()
                longhu = longhu.to_json(orient='index', )
                longhu = json.loads(longhu)
                for k, v in longhu.items():
                    db.get_collection('topList').insert(v)
Пример #12
0
def getvrdata(isinit='no'):
    mylogger = getmylogger()
    curday = datetime.date.today()
    print(curday)
    curyear = curday.year
    curmonth = curday.month
    quarter = (curmonth - 1) // 3 + 1
    # prdict = {'profitdivi': '分配预案', 'forecast': '业绩预告', 'xsg': '限售股解禁', 'fundholdings': '基金持股', 'newstocks': '新股'}
    prdict = {'fundholdings': '基金持股'}
    for dv in prdict:
        vrtbname = dv
        vrinfo = prdict[vrtbname]
        try:
            if dv == "profitdivi":
                df = ts.profit_data(year=curyear, top=100)
                if isinit == 'no' and df is not None:
                    df = df[df['report_date'] >= str(curday)]
            elif dv == "forecast":
                df = ts.forecast_data(curyear, quarter)
                if isinit == 'no' and df is not None:
                    # print(df[df['report_date'].isin(['2019-12-28'])])
                    df = df[df['report_date'] >= str(curday)]
            elif dv == "xsg":
                df = ts.xsg_data()
                if isinit == 'no' and df is not None:
                    curym = datetime.date.today().strftime("%Y-%m")
                    df = df[df['date'].str.contains(curym)]
            elif dv == "fundholdings":
                if quarter == 1:
                    quarter = 4
                    curyear -= 1
                else:
                    quarter -= 1
                df = ts.fund_holdings(curyear, quarter)
                if isinit == 'no' and df is not None:
                    lastyq = str(curyear) + '-' + str(quarter)
                    df = df[df['date'].str.contains(lastyq)]
                if df is not None:
                    newcolumns = ['nums', 'count', 'nlast', 'name', 'amount', 'date', 'ratio', 'code', 'clast']
                    df.columns = newcolumns
            elif dv == "newstocks":
                df = ts.new_stocks()
                if isinit == 'no' and df is not None:
                    df = df[df['ipo_date'] >= str(curday)]
            else:
                mylogger.info("没有执行命令。")
            if df is not None:
                tosql(df, vrtbname, "append", vrinfo, mylogger)
            else:
                mylogger.info("没有%s数据。" % vrinfo)
        except Exception:
            tracelog = traceback.format_exc()
            mylogger.info("获取数据异常。")
            mylogger.info(tracelog)
Пример #13
0
def get_new_stock_list():
    stock_list = []
    top_stocks_info = ts.new_stocks().head(STOCK_NUM)
    stocks_info = top_stocks_info[[IPO_CODE_HEAD,IPO_DATE_HEAD,IPO_PRICE_HEAD]]
    for i in xrange(STOCK_NUM):
        stock_date = stocks_info.at[i, IPO_DATE_HEAD]
        if pd.to_datetime(stock_date).strftime('%Y-%m-%d') == datetime.datetime.now().strftime('%Y-%m-%d'):
            stock_code = stocks_info.at[i, IPO_CODE_HEAD]
            stock_price = stocks_info.at[i, IPO_PRICE_HEAD]
            stock_list.append(Stock(stock_code, name = "", price = stock_price))
    return stock_list
Пример #14
0
def get_ipo(f, reset_flag=False):
    """
    获取ipo数据
    """
    df = ts.new_stocks(pause=conf.REQUEST_BLANK)
    df = df.drop("name", axis=1)
    df = df.sort_values(by=["ipo_date"])
    if reset_flag is False:
        tool.merge_df_dataset(f, conf.HDF5_FUNDAMENTAL_IPO, df)
    else:
        tool.create_df_dataset(f, conf.HDF5_FUNDAMENTAL_IPO, df)
    return
Пример #15
0
def get_stock_codes(markets=['zz500s'],ipo_date=None):
    '''
    markets: list
    e.g.['sme','gem','st','hs300s','sz50s','zz500s','general'];
    ipo_date: str
    e.g.'2015-03-30'
    '''
    code_list=[]
    if 'sme' in markets:#中小板
        path='/Users/xuegeng/StockCodes/sme.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    if 'gem' in markets:#创业板
        path='/Users/xuegeng/StockCodes/gem.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    if 'st' in markets:#风险板
        path='/Users/xuegeng/StockCodes/st.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    if 'hs300s' in markets:#沪深300
        path='/Users/xuegeng/StockCodes/hs300s.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    if 'sz50s' in markets:#上证50
        path='/Users/xuegeng/StockCodes/sz50s.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    if 'zz500s' in markets:#中证500
        path='/Users/xuegeng/StockCodes/zz500s.csv'
        sr1=pd.read_csv(path,names=['n','code'])
        codes=list(sr1['code'])
        code_list.extend(codes)
    
    if ipo_date:
        new_stock_df=ts.new_stocks()
        new_stock_df=new_stock_df[new_stock_df['ipo_date']>ipo_date]
        new_stock_codes=list(new_stock_df.code)
    #得到输入时间之后发行的股票
    
        code_list=list(set(code_list))
        desired_codes=list(set(code_list)-set(new_stock_codes))
    #剔除新股
    
    desired_codes=list(set(code_list))
    
    return desired_codes
def load_data():
    #下载公司基本信息,包括股票代码、pe、市盈率等数据
    try:
        rs = ts.new_stocks()
        pd.DataFrame.to_sql(rs,
                            table_name,
                            con=conn,
                            flavor='mysql',
                            if_exists='replace',
                            index=True)
    except Exception as e:
        print(e.message)
        print("加载新股数据出错")
Пример #17
0
def new_stock(engine):
    tbl = "invest_new_stock"
    tsl.log(tbl + " start...")
    try:
        df = ts.new_stocks()
        df['date'] = datetime.date.today()
        df = df.set_index('code', drop='true')
        df.to_sql(tbl, engine, if_exists='append')
        print
        tsl.log(tbl + " done")
    except BaseException, e:
        print
        print e
        tsl.log(tbl + " error")
Пример #18
0
def reference(year_to_start=2010):
    def profit_data(year):
        profit_data = ts.profit_data(year=year, top=100)
        profit_data.sort('shares', ascending=False)
        if profit_data is not None:
            profit_data.to_sql('reference_profit_data',
                               engine,
                               flavor='mysql',
                               if_exists='append')

    def forecast_data(year):
        for i in range(4):
            predts = ts.forecast_data(year, i + 1)
            if predts is not None:
                predts.to_sql('reference_forecast_data',
                              engine,
                              flavor='mysql',
                              if_exists='append')

    def fund_holdings(year):
        for i in range(4):
            predts = ts.fund_holdings(year, i + 1)
            if predts is not None:
                predts.to_sql('reference_fund_holdings',
                              engine,
                              flavor='mysql',
                              if_exists='append')

    starttime = datetime.datetime.today()
    year = [
        year_to_start + i for i in range(starttime.year - year_to_start + 1)
    ]
    thread_pool.map(profit_data, year)
    thread_pool.map(forecast_data, year)
    thread_pool.map(fund_holdings, year)
    thread_pool.join()

    xsg_data = ts.xsg_data()
    if xsg_data is not None:
        xsg_data.to_sql('reference_xsg_data',
                        engine,
                        flavor='mysql',
                        if_exists='replace')

    new_stocks = ts.new_stocks()
    if new_stocks is not None:
        new_stocks.to_sql('reference_new_stocks',
                          engine,
                          flavor='mysql',
                          if_exists='replace')
def new_stock():
    """
    新股数据
    retry_count:当网络异常后重试次数,默认为3
    pause:重试时停顿秒数,默认为0

    code:股票代码           name:股票名称
    ipo_date:上网发行日期    issue_date:上市日期
    amount:发行数量(万股)    markets:上网发行数量(万股)
    price:发行价格(元)       pe:发行市盈率
    limit:个人申购上限(万股)  funds:募集资金(亿元)
    ballot:网上中签率(%)
    """
    df = ts.new_stocks()
    print(df.head(10))
    print(df)
    print(datetime.datetime.today())
def get_stock_codes(markets=['zz500s'], ipo_date=None):
    '''
    markets: list
    e.g.['sme','gem','st','hs300s','sz50s','zz500s','general'];
    ipo_date: str
    e.g.'2015-03-30'
    '''
    code_list = []
    if 'sme' in markets:  #中小板
        df = ts.get_sme_classified()
        codes = list(df.code)
        code_list.extend(codes)
    if 'gem' in markets:  #创业板
        df = ts.get_gem_classified()
        codes = list(df.code)
        code_list.extend(codes)
    if 'st' in markets:  #风险板
        df = ts.get_st_classified()
        codes = list(df.code)
        code_list.extend(codes)
    if 'hs300s' in markets:  #沪深300
        df = ts.get_hs300s()
        codes = list(df.code)
        code_list.extend(codes)
    if 'sz50s' in markets:  #上证50
        df = ts.get_sz50s()
        codes = list(df.code)
        code_list.extend(codes)
    if 'zz500s' in markets:  #中证500
        df = ts.get_zz500s()
        codes = list(df.code)
        code_list.extend(codes)

    if ipo_date:
        new_stock_df = ts.new_stocks()
        new_stock_df = new_stock_df[new_stock_df['ipo_date'] > ipo_date]
        new_stock_codes = list(new_stock_df.code)
        #得到输入时间之后发行的股票

        code_list = list(set(code_list))
        desired_codes = list(set(code_list) - set(new_stock_codes))
    #剔除新股

    desired_codes = list(set(code_list))

    return desired_codes
Пример #21
0
 def download_new_stocks(self):
     """
     """
     #print('downloading the new_stocks info...')
     total = 0
     new_stocks = ts.new_stocks()
     if new_stocks is not None:
         filename = 'new_stocks'
         new_stocks.to_excel(self.working_folder + filename + '.xlsx',
                             encoding='GBK')
     else:
         warning_code = pd.DataFrame({
             'return code': ['for all stocks'],
             'description': ['new_stocks download failed']
         })
         self.warning_list = self.warning_list.append(warning_code)
     return
Пример #22
0
def job_2():
    try:
        print("I'm working......投资参考数据")
        # 分配预案
        profit_data = ts.profit_data(year, top=1000)
        data = pd.DataFrame(profit_data)
        data.to_sql('profit_data',engine,index=True,if_exists='replace')
        print("分配预案......done")

        # 业绩预告
        forecast_data = ts.forecast_data(year,1)
        data = pd.DataFrame(forecast_data)
        data.to_sql('forecast_data',engine,index=True,if_exists='replace')
        print("业绩预告......done")

        # 限售股解禁
        xsg_data = ts.xsg_data()
        data = pd.DataFrame(xsg_data)
        data.to_sql('xsg_data',engine,index=True,if_exists='replace')
        print("限售股解禁......done")

        # 基金持股
        fund_holdings = ts.fund_holdings(year, 1)
        data = pd.DataFrame(fund_holdings)
        data.to_sql('fund_holdings',engine,index=True,if_exists='replace')
        print("基金持股......done")
    
        # 新股数据
        new_stocks = ts.new_stocks()
        data = pd.DataFrame(new_stocks)
        data.to_sql('new_stocks',engine,index=True,if_exists='replace')
        print("新股数据......done")

        # 融资融券(沪市)
        sh_margins = ts.sh_margins()
        data = pd.DataFrame(sh_margins)
        data.to_sql('sh_margins',engine,index=True,if_exists='replace')
        print("融资融券(沪市)......done")

        # 融资融券(深市)
        sz_margins = ts.sz_margins()
        data = pd.DataFrame(sz_margins)
        data.to_sql('sz_margins',engine,index=True,if_exists='replace')
        print("融资融券(深市)......done")
    except Exception as e:
        print(e)
Пример #23
0
def get_stock_info(stock_pandas):
    concept = ts.get_concept_classified()
    stock_basics = ts.get_stock_basics()
    new_stocks = ts.new_stocks()

    stock_info = pd.merge(stock_pandas, stock_basics, how="left", on="name")
    stock_info = pd.merge(stock_info, concept, how="left", on="code")

    stock_info = stock_info.rename(columns={
        "name_x": "stock_name",
        "c_name": "concept"
    })

    return stock_info[[
        "code", "stock_name", "changepercent", "concept", "industry", "area",
        "timeToMarket", "per", "pb_x", "nmc", "turnoverratio", "amount", "rev",
        "profit", "gpr", "npr", "holders"
    ]]
Пример #24
0
    def __init__(self,init=True):
        """
        初始化,筛除688,300,ST,退市股,新股,低价股,下跌股
        """
        if init:
            self.data = ts.get_today_all() #今日复盘
            # data = ts.get_day_all(date='2021-02-18')   #历史复盘
            filt = self.data['code'].str.contains('^(?!688|605|300)')
            self.data = self.data[filt]
            filt = self.data['name'].str.contains('^(?!S|退市|\*ST)')
            self.data = self.data[filt]
            self.data = self.data.drop_duplicates()
            data = self.data[self.data['trade']>=2]
            data = data[data['changepercent']>0]
            data = data.to_json(orient='records')
            db.get_collection('today').remove()
            base = db.get_collection('base').find()
            industry = {i['code']: i['industry'] for i in base}
            self.intersect = {}
            for i in eval(data):
                db.get_collection('today').insert(i)
            res = db.get_collection('today').find()
            for i in res:
                try:
                    db.get_collection('today').update_many({'code':i['code']},{'$set':{'industry':industry[i['code']]}})
                except :
                    pass

            # 剔除新股
            try:
                newStock = ts.new_stocks()
                if not newStock.empty:
                    for i in newStock['code'].tolist():
                        db.get_collection('today').remove({'code':i},multi=True)
            except Exception as e:
                print('newStock Error',e)

            # 剔除停牌
            db.get_collection('today').remove({'open': 0})
Пример #25
0
    def crawl_new_stocks(self):
        df_stocks = ts.new_stocks()

        update_list = []
        for index in df_stocks.index:
            raw = dict(df_stocks.loc[index])
            doc = {
                'code': raw['code'],
                'ipo_date': raw['issue_date'],
                'price': raw['price']
            }

            update_list.append(
                UpdateOne({'code': doc['code']}, {'$set': doc}, upsert=True))

        if len(update_list) > 0:
            update_db = collection_dict['NEW_STOCK_COLLECTION'][1].bulk_write(
                update_list, ordered=False)
            print(
                'update new stocks, --> [collection: %s] inserted:%4d, modified:%4d'
                % (collection_dict['NEW_STOCK_COLLECTION'][0],
                   update_db.upserted_count, update_db.modified_count),
                flush=True)
Пример #26
0
import tushare as ts
from sqlalchemy import create_engine
engine = create_engine(
    'mysql+pymysql://root:[email protected]/packageing?charset=utf8')

df = ts.new_stocks()
#df.to_sql('new_stocks',engine)
df.to_sql('new_stocks', engine, if_exists='append')

holdings = ts.fund_holdings(2015, 1)
#holdings.to_sql('fund_holdings',engine)
holdings.to_sql('fund_holdings', engine, if_exists='append')
Пример #27
0
    def fill_high_limit_low_limit(begin_date, end_date):
        """
        为daily数据集填充涨停价和跌停价
        :param begin_date: 开始日期
        :param end_date: 结束日期
        """
        # 从tushare获取新股数据
        df_new_stocks = ts.new_stocks()
        print(df_new_stocks)
        code_ipo_price_dict = dict()
        code_ipo_date_set = set()
        for index in df_new_stocks.index:
            ipo_price = df_new_stocks.loc[index]['price']
            code = df_new_stocks.loc[index]['code']
            ipo_date = df_new_stocks.loc[index]['ipo_date']
            code_ipo_price_dict[code + '_' + ipo_date] = ipo_price
            code_ipo_date_set.add(code + '_' + ipo_date)

        all_codes = get_all_codes()

        basic_cursor = DB_CONN['basic'].find(
            {'date': {
                '$gte': begin_date,
                '$lte': end_date
            }},
            projection={
                'code': True,
                'date': True,
                'name': True,
                '_id': False
            },
            batch_size=1000)

        code_date_basic_dict = dict([(x['code'] + '_' + x['date'], x['name'])
                                     for x in basic_cursor])
        code_date_key_sets = set(code_date_basic_dict.keys())

        print(code_date_basic_dict)

        for code in all_codes:
            daily_cursor = DB_CONN['daily'].find(
                {
                    'code': code,
                    'date': {
                        '$lte': end_date,
                        '$gte': begin_date
                    },
                    'index': False
                },
                sort=[('date', ASCENDING)],
                projection={
                    'date': True,
                    'pre_close': True
                })

            update_requests = []
            for daily in daily_cursor:
                date = daily['date']
                code_date_key = code + '_' + daily['date']
                try:
                    high_limit = -1
                    low_limit = -1
                    pre_close = daily['pre_close']

                    if code_date_key in code_ipo_date_set:
                        high_limit = round(
                            code_ipo_price_dict[code_date_key] * 1.44, 2)
                        low_limit = round(
                            code_ipo_price_dict[code_date_key] * 0.64, 2)
                    elif code_date_key in code_date_key_sets and code_date_basic_dict[code_date_key][0:2]\
                            in ['ST', '*S'] and pre_close > 0:
                        high_limit = round(pre_close * 1.04, 2)
                        low_limit = round(pre_close * 0.95, 2)
                    elif pre_close > 0:
                        high_limit = round(pre_close * 1.10, 2)
                        low_limit = round(pre_close * 0.9, 2)

                    print(
                        'pre_close: %6.2f, high_limit: %6.2f, low_limit: %6.2f'
                        % (pre_close, high_limit, low_limit),
                        flush=True)

                    if high_limit > 0 and low_limit > 0:
                        update_requests.append(
                            UpdateOne(
                                {
                                    'code': code,
                                    'date': date,
                                    'index': False
                                }, {
                                    '$set': {
                                        'high_limit': high_limit,
                                        'low_limit': low_limit
                                    }
                                }))
                except:
                    print('填充涨跌停时发生错误,股票代码:%s,日期:%s' % (code, date),
                          flush=True)

            if len(update_requests) > 0:
                update_result = DB_CONN['daily'].bulk_write(update_requests,
                                                            ordered=False)
                print('填充涨跌停,股票:%s,更新:%4d条' %
                      (code, update_result.modified_count),
                      flush=True)
Пример #28
0
def getNewStock():
    df = ts.new_stocks()
    df.to_excel('new_stock.xls', 'gbk')
Пример #29
0
 def Get_new_stocks(self):
     # 获取新股数据
     df = ts.new_stocks()
     #df = df.sort_values(by=['shares'], ascending=False)
     print(df)
Пример #30
0
 def new_stocks(self, conns):
     self.base = Base()
     self.financial_data = conns['financial_data']
     self.df = ts.new_stocks()
     self.base.batchwri(self.df, 'xingushuju', self.financial_data)
Пример #31
0
def dump_ipo_data():
    df = ts.new_stocks()
    folder = os.path.dirname(__file__)
    filepath = os.path.join(folder, "ipodata")
    df.to_csv(filepath, encoding="utf-8")
Пример #32
0
def new_stocks():
    DTS=ts.new_stocks()
    DTS.to_csv('new_stocks.csv',encoding='gbk')
Пример #33
0
ts.get_hist_data('600848',ktype='M') #获取月k线数据
ts.get_hist_data('600848',ktype='5') #获取5分钟k线数据
ts.get_hist_data('600848',ktype='15') #获取15分钟k线数据
ts.get_hist_data('600848',ktype='30') #获取30分钟k线数据
ts.get_hist_data('600848',ktype='60') #获取60分钟k线数据
ts.get_hist_data('sh')#获取上证指数k线数据,其它参数与个股一致,下同
ts.get_hist_data('sz')#获取深圳成指k线数据
ts.get_hist_data('hs300')#获取沪深300指数k线数据
ts.get_hist_data('sz50')#获取上证50指数k线数据
ts.get_hist_data('zxb')#获取中小板指数k线数据
ts.get_hist_data('cyb')#获取创业板指数k线数据

ts.get_today_all()#当天实时数据

df = ts.get_index()#大盘指数
ts.new_stocks()#新股数据

#基本面数据
ts.get_stock_basics()
#获取2015年第1季度的业绩报表数据
ts.get_report_data(2015,1)
#获取2015年第1季度的盈利能力数据
ts.get_profit_data(2015,1)
#获取2015年第1季度的营运能力数据
ts.get_operation_data(2015,1)
#获取2015年第1季度的成长能力数据
ts.get_growth_data(2015,1)
#获取2015年第1季度的偿债能力数据
ts.get_debtpaying_data(2015,1)
#获取2015年第1季度的现金流量数据
ts.get_cashflow_data(2015,1)
Пример #34
0
#coding=utf-8
'''
Created on 2015年6月4日

@author: Administrator
'''
import tushare as ts

# 分配预案
#每到季报、年报公布的时段,就经常会有上市公司利润分配预案发布,而一些高送转高分红的股票往往会成为市场炒作的热点。
df = ts.profit_data(top=60)
df.sort('shares',ascending=False)
df[df.shares>=10]#选择每10股送转在10以上的

# 业绩预告
ts.forecast_data(2014,2)#获取2014年中报的业绩预告数据

# 限售股解禁
# 以月的形式返回限售股解禁情况,通过了解解禁股本的大小,判断股票上行的压力。可通过设定年份和月份参数获取不同时段的数据。
ts.xsg_data()

# 新股数据
ts.new_stocks()

# 融资融券
ts.sh_margins(start='2015-01-01', end='2015-04-19')
ts.sz_margins(start='2015-01-01', end='2015-04-19')
#如果不设symbol参数或者开始和结束日期时段设置过长,数据获取可能会比较慢,建议分段分步获取,比如一年为一个周期
ts.sh_margin_details(start='2015-01-01', end='2015-04-19', symbol='601989')
ts.sz_margin_details('2015-04-20')