def gp(): print(ts.get_index()[:1]) print(ts.get_index()[12:13]) print(ts.get_index()[17:18]) df = ts.get_realtime_quotes([ '002291', '002939', '002475', '000034', '601607', '000100', '002241', '601099', '600728', '000998', '601800' ])[['code', 'name', 'price', 'bid', 'ask', 'volume', 'amount', 'time']] print(df, end='\n{0}\n'.format('-' * 50)) sh = ts.get_index()[:1][['amount']].values[0][0] sz = ts.get_index()[12:13][['amount']].values[0][0] print('沪深成交额:{:.2f}亿'.format(float(sh) + float(sz)))
def notrealdata(): cursor.execute( """SELECT distinct(tradeDate) FROM mkt_mktindex group by tradeDate order by tradeDate desc """) tradetimesql = cursor.fetchone() count = cursor.rowcount if count == 0: dfindex = ts.get_index() inserttable(dfindex, '15:00') elif inputtradetime != tradetimesql[0]: dfindex = ts.get_index() #dfindex.insert(2,'tradeTimehm','15:00') inserttable(dfindex, '15:00')
def notrealdatanoon(): cursor.execute( """SELECT distinct(tradeTimehm) FROM mkt_mktindex where tradeDate=%s order by tradeTimehm desc """, (inputtradetime)) tradetimesql = cursor.fetchone() count = cursor.rowcount print count print tradetimesql[0] if count == 0: dfindex = ts.get_index() inserttable(dfindex, '11:30') elif (tradetimesql[0] != '11:30'): dfindex = ts.get_index() inserttable(dfindex, '11:30')
def notrealdatanight(): cursor.execute( """SELECT distinct(tradeTimehm) FROM mkt_mktindex where tradeDate=%s order by tradeTimehm desc """, (inputtradetime)) tradetimesql = cursor.fetchone() print tradetimesql[0] count = cursor.rowcount if count == 0: dfindex = ts.get_index() inserttable(dfindex, '15:00') if (tradetimesql[0] != '15:00'): dfindex = ts.get_index() #dfindex.insert(2,'tradeTimehm','15:00') inserttable(dfindex, '15:00')
def get_last_exchange_day(): from datetime import datetime, date, timedelta print 'entering get_last_exchange_day' import sys reload(sys) sys_temp = sys sys_temp.setdefaultencoding('utf-8') date_time= datetime.now().strftime("%Y-%m-%d %H:%M:%S") hour = int(date_time[11:13]) minute = int(date_time[14:16]) try: print 'entering try1' file_changetime,file_date = get_FileModifyTime(data_const.My_Store_Dir+'sh.csv') file_hour = int(file_changetime[11:13]) file_minute= int(file_changetime[14:16]);time_thresh=5 if file_date == getDatetimeToday().strftime("%Y-%m-%d") and (hour-file_hour)*60+minute-file_minute <time_thresh: data_sh_index = pd.read_csv(data_const.My_Store_Dir+'sh.csv')[data_const.Meta_Index_Needing]#避免下面重复计算 prep_d.compute_item(data_sh_index,'MACD_d').to_csv(data_const.My_Store_Dir+'sh'+data_const.Suffix) last_date = data_sh_index.loc[len(data_sh_index)-1]['date'] print 'today:',hour ,minute,'file_changetime:',file_hour,file_minute,'time_thresh:',time_thresh,'minutes' print 'within timethresh needing file not need change,leaving get_last_exchange_day',last_date return last_date except : pass try: print 'entering try 2' #环境数据,股票基本资料 basic = 'basic.csv' ts.get_stock_basics().to_csv(data_const.My_Store_Dir+basic) print basic ,'ok' #实时行情数据 realtime = 'realtime_data.csv' ts.get_today_all().to_csv(data_const.My_Store_Dir+realtime) print '\n',realtime,'ok' wholeindex = 'whole_index.csv' ts.get_index().to_csv(data_const.My_Store_Dir+wholeindex) print wholeindex,'ok' for item,_ in data_const.INDEX_LIST.items(): prep_d.compute_item(ts.get_k_data(item),'MACD_d').to_csv(data_const.My_Store_Dir+item+data_const.Suffix) print item,'ok' data_sh_index = pd.read_csv(data_const.My_Store_Dir+'sh.csv') last_date = data_sh_index.loc[len(data_sh_index)-1]['date'] print 'leaving get_last_exchange_day',last_date return last_date except Exception,e: print e time.sleep(25) return get_last_exchange_day()
def dump_index(): df = ts.get_index() df.to_sql('index_data', engine, if_exists='append', index=False, index_label='code')
def get_code1(conn): """ 使用常规存储方式存储大盘指数行情数据获取 可获得上证指数、深证指数 :return: """ df_index = ts.get_index() sql_market = """ INSERT INTO middle_news_market( code, name, change_market, open_market, preclose, close_market, high, low, volume, amount ) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ for i in range(0, 25): code = df_index['code'][i] name = df_index['name'][i] change_market = str('%.2f' % df_index['change'][i]) open_market = str('%.4f' % df_index['open'][i]) preclose = str('%.4f' % df_index['preclose'][i]) close = str('%.4f' % df_index['close'][i]) high = str('%.4f' % df_index['high'][i]) low = str('%.4f' % df_index['low'][i]) volume = str(df_index['volume'][i]) amount = str('%.4f' % df_index['amount'][i]) sql_params = [ code, name, change_market, open_market, preclose, close, high, low, volume, amount ] logger.debug(sql_market) logger.debug(sql_params) # 存入数据库 execute_sql(conn, sql_market, sql_params)
def save_big_index_data(): """获取大盘指数实时行情列表,以表格的形式展示大盘指数实时行情。""" logger.info('Begin get and save big index data, date is: %s.' % today_line) try: data_df = ts.get_index() except Exception as e: logger.exception('Error get big index data, date is: %s.' % today_line) else: if data_df is not None and not data_df.empty: data = data_df.values data_dicts = [{ 'date': today_line, 'code': row[0], 'name': row[1], 'change': row[2], 'open': row[3], 'preclose': row[4], 'close': row[5], 'high': row[6], 'low': row[7], 'volume': row[8], 'amount': row[9] } for row in data] try: BigIndexData.insert_many(data_dicts).execute() except Exception as e: logger.exception('Error save big index data, date is: %s.' % today_line) logger.error('Error data is: %s.' % data) else: logger.info('Success save big index data, date is: %s.' % today_line) else: logger.warn('Empty save big index data, date is: %s.' % today_line)
def get_rel_price(self): df_index = ts.get_index() # 上证指数 df_sh = df_index[df_index["code"] == '000001'] df_sz = df_index[df_index["code"] == '399001'] df_hs300 = df_index[df_index["code"] == '000300'] df_zz500 = df_index[df_index["code"] == '000905'] hsi_price, hsi_pre_close = yahoo_finance_api.get_real_price('^HSI') gspc_price, gspc_pre_close = yahoo_finance_api.get_real_price('^GSPC') ixic_price, ixic_pre_close = yahoo_finance_api.get_real_price('^IXIC') dict = [{ 'sh_direction': cal_direction(float(df_sh["change"].values[0])), 'sz_direction': cal_direction(float(df_sz["change"].values[0])), 'hs300_direction': cal_direction(float(df_hs300["change"].values[0])), 'zz500_direction': cal_direction(float(df_zz500["change"].values[0])), 'hsi_direction': cal_direction(hsi_price - hsi_pre_close), 'gspc_direction': cal_direction(gspc_price - gspc_pre_close), 'ixic_direction': cal_direction(ixic_price - ixic_pre_close) }] df = pd.DataFrame(dict) return df
def daily(engine, session, cdate): if not tsu.is_holiday(cdate): tsl.log("trade_index_today start...") try: df = ts.get_index() df = df.set_index('code', drop='true') df['date'] = cdate df.to_sql('trade_index_today', engine, if_exists='append') tsl.log("trade_index_today done") except BaseException, e: print e tsl.log("trade_index_today error") tsl.log("trade_market_today start...") try: df = ts.get_today_all() df = df.set_index('code', drop='true') df['date'] = cdate df.to_sql('trade_market_today', engine, if_exists='append') print tsl.log("trade_market_today done") except BaseException, e: print print e tsl.log("trade_market_today error")
def stat_today_all(tmp_datetime): datetime_str = (tmp_datetime).strftime("%Y-%m-%d") datetime_int = (tmp_datetime).strftime("%Y%m%d") print("datetime_str:", datetime_str) print("datetime_int:", datetime_int) data = ts.get_today_all() # 处理重复数据,保存最新一条数据。最后一步处理,否则concat有问题。 if not data is None and len(data) > 0: # 插入数据库。 # del data["reason"] data["date"] = datetime_int # 修改时间成为int类型。 data = data.drop_duplicates(subset="code", keep="last") data.head(n=1) common.insert_db(data, "ts_today_all", False, "`date`,`code`") else: print("no data .") time.sleep(5) # 停止5秒 data = ts.get_index() # 处理重复数据,保存最新一条数据。最后一步处理,否则concat有问题。 if not data is None and len(data) > 0: # 插入数据库。 # del data["reason"] data["date"] = datetime_int # 修改时间成为int类型。 data = data.drop_duplicates(subset="code", keep="last") data.head(n=1) common.insert_db(data, "ts_index_all", False, "`date`,`code`") else: print("no data .") print(datetime_str)
def get_index_data(starttime): sql = "REPLACE INTO algo_today_stock(CODE,changepercent,trade,OPEN,high,low,settlement,TYPE,time,volume,amount) VALUES" try: result = ts.get_index() except Exception, e: print(e) return
def work(): db = db_init() """ stock_id = "601899" log_debug("stock: %s", stock_id) k_index_day_one_stock(stock_id, db) """ # step1: get from web stocks = ts.get_index() # step2: to db begin = get_micro_second() # to db for row_index, row in stocks.iterrows(): stock_id = row['code'] log_debug("stock: %s", stock_id) # import to DB k_index_day_one_stock(stock_id, db) log_info("save-all costs %d us", get_micro_second()-begin) db_end(db)
def get_info(): df = ts.get_index() new_df = df[['name', 'change', 'open', 'preclose', 'close', 'high', 'low', 'volume', 'amount']] index_name = new_df.columns.values info = { '名称': '', '涨跌幅': 0, '今日开盘': 0, '昨日收盘': 0, '今日收盘': 0, '今日最高': 0, '今日最低': 0, '成交量(手)': 0, '成交金额(亿元)': 0, } seq = 0 for num in range(1): # num=0 => A股指数, 表示目前只取A股指数信息 for k in list(info.keys()): info[k] = new_df[index_name[seq]][num] seq += 1 # 显示文本内容 content = '时间:%s\n\n' % datetime.now().time().strftime('%H:%M:%S') # 字符串输出+显示当日涨幅 for k, v in info.items(): if k == '今日收盘': if float(v) <= float(info['昨日收盘']): tip = '📉' else: tip = '📈' v = '%s %s' % (v, tip) content += '%s: %s\n' % (k, v) return content, info
def getDataRelateLessWithCode(self, mongo, func): if (func == "stock_basics"): df = ts.get_stock_basics() date = df.ix['600848']['timeToMarket'] # 上市日期YYYYMMDD # ts.get_h_data('002337') # 前复权 # ts.get_h_data('002337', autype='hfq') # 后复权 # ts.get_h_data('002337', autype=None) # 不复权 # ts.get_h_data('002337', start='2015-01-01', end='2015-03-16') # 两个日期之间的前复权数据 # # ts.get_h_data('399106', index=True) # 深圳综合指数 print(date) elif (func == "today_all"): df = ts.get_today_all() tmpJson = json.loads(df.to_json(orient='records')) coll = mongo.trading[func] for i in range(len(tmpJson)): tmpJson[i][u'now'] = str(self.now) coll.insert(tmpJson[i]) return elif (func == "index"): df = ts.get_index() else: df = {} insert_string = df.to_json(orient='records') items = json.loads(insert_string) coll = mongo.trading[func] coll.insert(items)
def index(): whole_indicators = json.loads(ts.get_index()[:4].to_json(orient='records')) getLatestNews() whole_news = News.query.order_by(News.time.desc()).limit(7) # 站点公告 notice = Article.query.order_by(Article.updated_time.desc()).limit(7) dates = datetime.datetime.now() week = datetime.datetime.now().weekday() if week in [5, 6]: days = 4 - week dates = dates + datetime.timedelta(days=days) dates = dates.strftime('%Y-%m-%d') recommend_stocks = Stock.query.filter(Stock.code != 'ALL').limit(8).all() if current_user.is_authenticated: for i in range(len(recommend_stocks)): if Follow_Stock.query.filter_by(user_id=current_user.id, stock_id=recommend_stocks[i].code).first() is not None: recommend_stocks[i].flag = True else: recommend_stocks[i].flag = False return render_template('main/index.html', whole_indicators=whole_indicators, news=whole_news, notices=notice, dates=dates, stocks=recommend_stocks)
def GetPrice(): print("GetPrice run...") out = {} try: df = ts.get_index() # print(df) # 这里有问题,应该是和昨天收盘比涨跌,不是今天开盘 AStock = df.loc[df.code == '000001'] out['code'] = AStock.loc[0, 'code'] out['name'] = AStock.loc[0, 'name'] out['close'] = AStock.loc[0, 'close'] out['open'] = AStock.loc[0, 'open'] out['preclose'] = AStock.loc[0, 'preclose'] out['error'] = 0 # re.code = AStock.loc[0, 'code'] # re.name = AStock.loc[0, 'name'] # re.closePrice = AStock.loc[0, 'close'] # re.openPrice = AStock.loc[0, 'open'] # re.error = 0 except Exception as e: print(e) out['error'] = -1 out2 = json.dumps(out) return out2
def get_indeces(): current = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: index_df = ts.get_index() except Exception as err: err = str(err) print(err) result = {'status': 'failed', 'content': err} return Response(json.dumps(result), mimetype='application/json') index_df.drop_duplicates(subset=["code"], inplace=True) # index_df.drop(['preclose'], axis=1, inplace=True) index_df.rename(columns={ 'change': 'change_percent', 'preclose': 'settlement' }, inplace=True) index_df['time'] = current try: index_df.to_sql(name=index_table, con=engine, if_exists='append', index=False) print(index_df.head()) except Exception as err: err = str(err) print(err) result = {'status': 'failed', 'content': err} return Response(json.dumps(result), mimetype='application/json') result = {'status': '200'} return Response(json.dumps(result), mimetype='application/json')
def show_current_market(): # a = ts.get_today_all() stf = lambda v: float(v) codes = ['603188', '002940', '300694', '603156', '600128', '000622'] buy_falg = ['', '', '', '', 'B', ''] while True: try: for code, flag in zip(codes, buy_falg): s1 = ts.get_realtime_quotes(code) current_p = stf(s1['price']) open_p = stf(s1['open']) preclose_p = stf(s1['pre_close']) change = (current_p - preclose_p) / preclose_p * 100 buy_1 = stf(s1['b1_v']) print('[{}] code: {}, cp: {}, change: {:.2F}, buy one: {}'. format(flag, code, current_p, change, buy_1)) print('') inds = [0, 12, 17] df = ts.get_index() for ind in inds: print('code: {}, change: {:.2F}'.format( df['code'][ind], df['change'][ind])) for _ in range(3): print('') time.sleep(5) except: print('try again!') finally: pass
def store_index(self, trading_date=None): """获取大盘指数实时行情列表,以表格的形式展示大盘指数实时行情, 收盘后就是日K历史的行情""" print("store_index()......") trading_date = self.last_trading_date if trading_date is None else trading_date df = ts.get_index() df['date'] = trading_date self.mysqlUtils.append_data(df, 'index_data')
def __call__(self, conns): self.base = Base() self.finacial_data = conns['financial_data'] #清空表 # self.finacial_data.dopost('TRUNCATE TABLE dapan_hangqing_date') # self.finacial_data.dopost('TRUNCATE TABLE dapan_code_name') # 实时行情 hangqing = ts.get_index() today = self.base.gettoday() hangqing['date'] = today.replace('/', '-') #大盘指数每日行情数据 self.base.batchwri(hangqing, 'dapan_hangqing_date', self.finacial_data) #大盘代码-名字对照表 self.base.batchwri(hangqing[['code', 'name']], 'dapan_code_name', self.finacial_data) #大盘代码-名字对照表去重 duizhao = self.finacial_data.getdata('dapan_code_name') # print(duizhao.size) duizhao_qc = duizhao.drop_duplicates().sort_values( by='code').reset_index(drop=True) # print(df) self.finacial_data.dopost('TRUNCATE TABLE dapan_code_name') self.base.batchwri(duizhao_qc, 'dapan_code_name', self.finacial_data)
def realtime(request, code): code_list = code.split(',') index_change = ts.get_index().loc[0, "change"] str = "上证涨幅:%s<br/>-----------<br/>" % index_change code_pattern = re.compile("\d{6}$") for code in code_list: a = re.findall(code_pattern, code) if (len(a) != 1): db_data = stock_basic.objects.filter( name=code).values_list('code')[0] code = db_data[0] df = ts.get_realtime_quotes(code) name = df.loc[0, 'name'] pre_close = df.loc[0, 'pre_close'] open_price = df.loc[0, 'open'] price = df.loc[0, 'price'] volumn = df.loc[0, 'volume'] amount = df.loc[0, 'amount'] b1_p = df.loc[0, 'b1_p'] b1_v = df.loc[0, 'b1_v'] a1_p = df.loc[0, 'a1_p'] a1_v = df.loc[0, 'a1_v'] avg_price = float(amount) / int(volumn) str += '''名字:%s code:%s<br/>昨日收盘价:%s<br/>今日开盘价:%s<br/>当前价:%s<br/> 成交股数:%s<br/>成交总额:%s<br/>均价:%f<br/>卖1:price:%svolumn:%s<br/>买1:price:%svolumn:%s<br/>------------------<br/>''' % ( name, code, pre_close, open_price, price, volumn, amount, avg_price, a1_p, a1_v, b1_p, b1_v) return HttpResponse(str)
def get_mainland_index(): df = ts.get_index() if len(df) == 0: return now = datetime.datetime.now() df['date'] = now.date() df['time'] = now.time() df.to_sql('stock_mainland_index', engine, if_exists='append', chunksize=1000, index=False)
def index_catcha(self): df = pd.DataFrame(ts.get_index()) a = df[df['name'] == '上证指数'].change[0] b = df[df['name'] == '上证指数'].close[0] mess = "Change:%s index:%s" % (a, b) return mess
def avg(request): all_data = ts.get_index().iterrows() data = { 'message': 'Hello World!', 'title': '股市大盘', 'all_data': all_data, } return render(request, 'stock_market/avg.html', data)
def jjs(): print(ts.get_index()[:1]) for i in jj_list: a = requests.get( 'http://fundgz.1234567.com.cn/js/{}.js'.format(i)).text print(re.findall('name":"(.*?)".*?gszzl":"(.*?)"', a)[0]) if jj_list.index(i) == 5: print('-' * 50)
def get_index(): try: logger.info('get index data starting...') df = ts.get_index() logger.info('get index data end...') except: logger.exception('some errors between get index data end...') return df
def market_index(self): """ 获取大盘指数实时行情列表,以表格的形式展示大盘指数实时行情 :return: """ df = ts.get_index() df = df[["code", "name", "change", "preclose", "close"]] return df
def get_trading_data(ticker,startdate,enddate): data={} price=ts.get_h_data(ticker,start=startdate,end=enddate) tick=ts.get_today_ticks(ticker) index=ts.get_index() data["price"]=price data["tick"]=tick data["index"]=index return data
def get_stock_index(): """ 获取大盘指数行情 return """ df = ts.get_index() res = df.to_sql(table_index_stock, engine, if_exists='replace') msg = 'ok' if res is None else res print('写入大盘指数行情: ' + msg + '\n')
def handle_get_index(self): """ 更新大盘指数,目前不存 """ info_logger.info(self.handle_get_index.__doc__) df = tushare.get_index() """:type : DataFrame""" clean_table(IndexInTimeList) write_dataframe_to_sql(df, TableName.index_in_time, index=False)
def buildIndexList(self): tableName = 'indexList' try: engine = createDbEngine('database') df = ts.get_index() df.to_sql(tableName, engine, if_exists='replace') except: print_exc() return False return True
def get_codes_names(filename): ''' Get the latest codes which includes stock and index ''' zs = ts.get_index() stock = ts.get_today_all() codes = np.concatenate( (zs['code'].unique(), stock['code'].unique())) names = np.concatenate( (zs['name'].unique(), stock['name'].unique())) out = (codes, names) if filename: write_pickle(out, filename) return out
def get_index(engine): df = ts.get_index() df.to_sql('index', engine, if_exists='append')
def getIndex(): return ts.get_index()
def download_symbols(): df = ts.get_stock_basics() df.to_csv(SYM["all"]) index_df = ts.get_index() index_df.to_csv(SYM["id"])
client = Client() client.init('77ac42d684c5dedeca8aa6b62a1a8714f7aeaf6def3198d3a8307f8665c9f694') url1='/api/market/getMktIdxd.json?field=&beginDate=20160101&endDate=20160505&indexID=&ticker=399006&tradeDate=' code, re = client.getData(url1) if code==200: print (re) else: print (code) print (re) url2='/api/market/getMktEqud.json?field=&beginDate=20160101&endDate=20160505&secID=&ticker=000762&tradeDate=' code, result = client.getData(url2) if(code==200): file_object = open('thefile.csv', 'w') file_object.write(str(result)) file_object.close( ) else: print (code) print (result) except Exception as e: #traceback.print_exc() raise e import pandas import tushare as ts ts.set_token('77ac42d684c5dedeca8aa6b62a1a8714f7aeaf6def3198d3a8307f8665c9f694') st=ts.Market() df = st.MktEqud(tradeDate='20160505', field='ticker,secShortName,preClosePrice,openPrice,highestPrice,lowestPrice,closePrice,turnoverVol,turnoverRate') df1=st.MktEqud(ticker='600836',beginDate='20160101',endDate='20160507',field='ticker,secShortName,preClosePrice,openPrice,highestPrice,lowestPrice,closePrice,turnoverVol,turnoverVole,turnoverRate,negMarketValue,PE,PE1,PB') df2= ts.get_index() print (df1) df1.to_csv('c:/000876.csv',encoding='gbk')
def sync_market_today(): ''' sync current market data ''' df = ts.get_index() DataFrameToMongo(df, MongoClient(mongourl)['stoinfo']['market'], ['code'])
def realtimeUpdate_from_tushare(): import tushare as ts #更新股票行情 df = ts.get_today_all() for i in range(len(df)): if df.ix[i, 'open'] == 0: continue #停牌 code = df.ix[i][0] stock = getStock('sh' + code) if stock.isNull() == True or stock.type != constant.STOCKTYPE_A: stock = getStock('sz' + code) if stock.isNull() == True: continue record = KRecord() record.openPrice = df.ix[i, 'open'] record.highPrice = df.ix[i, 'high'] record.lowPrice = df.ix[i, 'low'] record.closePrice = df.ix[i, 'trade'] record.transAmount = float(df.ix[i, 'amount']) record.transCount = float(df.ix[i, 'volume']) from datetime import date d = date.today() record.datetime = Datetime(d) stock.realtimeUpdate(record) #更新指数行情 df = ts.get_index() for i in range(len(df)): code = df.ix[i][0] stock = getStock('sh' + code) if stock.isNull() == True or stock.type != constant.STOCKTYPE_INDEX: stock = getStock('sz' + code) if stock.isNull() == True: continue total = stock.getCount(Query.DAY) if total == 0: continue last_record = stock.getKRecord(total - 1) record = KRecord() record.openPrice = df.ix[i, 'open'] record.highPrice = df.ix[i, 'high'] record.lowPrice = df.ix[i, 'low'] record.closePrice = df.ix[i, 'close'] record.transCount = float(df.ix[i, 'volume']) record.transAmount = float(df.ix[i, 'amount']) if (last_record.closePrice != record.closePrice or last_record.highPrice != record.highPrice or last_record.lowPrice != record.lowPrice or last_record.openPrice != record.openPrice): from datetime import date d = date.today() record.datetime = Datetime(d) stock.realtimeUpdate(record)
if not is_exist: spam_asset_writer_sh.writerow(['date', 'code', 'amount', 'growth']) is_exist = os.path.exists('./ClassifyHistory/AssetFow' + sz_index + '.csv') asset_flow_csv_sz = open('./ClassifyHistory/AssetFow' + sz_index + '.csv', 'ab+') spam_asset_writer_sz = csv.writer(asset_flow_csv_sz, dialect='excel') if not is_exist: spam_asset_writer_sz.writerow(['date', 'code', 'amount', 'growth']) is_exist = os.path.exists('./ClassifyHistory/AssetFow' + cy_index + '.csv') asset_flow_csv_cy = open('./ClassifyHistory/AssetFow' + cy_index + '.csv', 'ab+') spam_asset_writer_cy = csv.writer(asset_flow_csv_cy, dialect='excel') if not is_exist: spam_asset_writer_cy.writerow(['date', 'code', 'amount', 'growth']) index_all = ts.get_index() sh_amount = index_all.loc[index_all['code'] == sh_index, 'amount'].values[0] sh_growth = index_all.loc[index_all['code'] == sh_index, 'change'].values[0] cy_amount = index_all.loc[index_all['code'] == cy_index, 'amount'].values[0] cy_growth = index_all.loc[index_all['code'] == cy_index, 'change'].values[0] sz_amount = index_all.loc[index_all['code'] == sz_index, 'amount'].values[0] sz_growth = index_all.loc[index_all['code'] == sz_index, 'change'].values[0] spam_asset_writer_sh.writerow([format_time_asset, sh_index, sh_amount, sh_growth]) spam_asset_writer_sz.writerow([format_time_asset, sz_index, sz_amount, sz_growth]) spam_asset_writer_cy.writerow([format_time_asset, cy_index, cy_amount, cy_growth]) asset_flow_csv_sh.close() asset_flow_csv_cy.close() asset_flow_csv_sz.close()
#coding=utf-8 import tushare as ts import datetime df = ts.get_index() df.to_csv('Index_data.csv') #d0 = datetime.datetime.today() #d1 = d0 + datetime.timedelta(days = -730) #tmp = ts.get_h_data('000001', index=True, start=d1.strftime('%Y-%m-%d'), end=d0.strftime('%Y-%m-%d')) #while True: # d0 = d1 + datetime.timedelta(days = -1) # d1 = d0 + datetime.timedelta(days = -730) # final = ts.get_h_data('000001', index=True, start=d1.strftime('%Y-%m-%d'), end=d0.strftime('%Y-%m-%d')) # try: # tmp = tmp.append(final) # except: # break #tmp.to_csv('IN000001.csv') for index, row in df.iterrows(): print index, df.ix[index]['code'], df.ix[index]['name'] final = ts.get_h_data('000001', index=True, start='1991-01-01', end='2016-02-20') final.to_csv('IN000001.csv')
#-*- coding:utf-8 -*- ''' Created on 2015年11月25日 @author: LeoBrilliant #获取大盘指数历史行情 ''' import MySQLdb import tushare as ts from datetime import datetime #连接数据库,当前参数为地址、用户、密码(可控)、数据库 #db = MySQLdb.connect("localhost", "root", "", "Data") db = MySQLdb.connect(host="localhost", user="******", passwd="", db="Data", charset="utf8") data = ts.get_index() tradingday = datetime.strftime(datetime.today(), "%Y%m%d") data['tradingday'] = tradingday indexdata = data.set_index(['tradingday', 'code']) ret = indexdata.to_sql("t_index_data", db, flavor="mysql", if_exists="append") #关闭连接 db.close() print("Success")