def draw(df, xf, yf, tf, title='New Stock Chart'): ''' Draw hight stock chart by pandas.DataFrame Args: df: dataFrame xf: field name of dataFrame to x coordinate, the value of x must be unique datetime. yf: field name of dataFrame to y coordinate. tf: field name of dataFrame to line title. ''' uniques = df[tf].unique() # log.debug(str(uniques)) c = Highstock() for unique in uniques: sel_df = df[df[tf] == unique] sel_df = sel_df.loc[:, [xf, yf]] xyl = xy(sel_df) c.add_data_set(xyl, series_type='line', name=unique) options = { 'title': { 'text': title }, } c.set_dict_options(options) c.save_file() log.info('Successful completion of drawing.')
data = Load.FinData(dataset='TaiwanStockPrice', select='2330', date='2018-10-10') print(' change type of dataframe to highcharts ') data['date'] = date2millisecond(data['date']) list_data = [] for i in range(len(data)): tem = [ int(data.loc[i, 'date']), float(data.loc[i, 'max']), float(data.loc[i, 'min']) ] list_data.append(tem) chart.add_data_set(list_data, 'arearange', 'Temperatures') options = { 'rangeSelector': { 'selected': 2 }, 'title': { 'text': 'Temperature variation by day' }, } chart.set_dict_options(options) # This will generate and save a .html file at the location you assign chart.save_file()
def creatChart(klines, symbol): filename = "%s_dayk" % symbol ohlc = [] volume = [] for line in klines: ohlc.append([ line[0], #open float(line[1]), #high float(line[2]), # low float(line[3]), # close float(line[4]) ]) volume.append([line[0], float(line[5])]) H = Highstock() groupingUnits = [['day', [1]]] options = { 'rangeSelector': { 'selected': 4 }, 'chart': { 'zoomType': 'x', 'reflow': True, 'height': 900 }, 'title': { 'text': '%s' % (symbol) }, 'subtitle': { 'text': filename }, 'yAxis': [{ 'labels': { 'align': 'right', 'x': -3 }, 'title': { 'text': 'OHLC' }, 'height': '60%', 'lineWidth': 2 }, { 'labels': { 'align': 'right', 'x': -3 }, 'title': { 'text': 'Volume' }, 'top': '65%', 'height': '35%', 'offset': 0, 'lineWidth': 2 }], } H.add_data_set(ohlc, 'candlestick', symbol, dataGrouping={'units': groupingUnits}) H.add_data_set(volume, 'column', 'Volume', yAxis=1, dataGrouping={'units': groupingUnits}) H.set_dict_options(options) H.save_file(filename) print("===--- Completed ---===")
def main(argv): from highcharts import Highstock # 暂时这样避免其他脚本 import 出错 unittest() opts, args = parse_options(argv) #exchanges = ('binance', 'huobipro', 'okex', 'zb') #symbol = 'qtum/btc' #sdt = '2018-01-20 18-00-00' #edt = '2018-01-20 18-59-00' #folder = r'C:\Users\Eph\Desktop\CC\trade\ccxtbot\CCMarkets\data' exchanges = args symbol = opts.get('symbol') sdt = opts.get('start') edt = opts.get('stop') folder = opts.get('folder') prec = int(opts.get('prec', 8)) fname = opts.get('file', 'StockChart') verbose = opts.get('verbose', False) if not exchanges or not symbol or not sdt or not edt or not folder: usage(argv[0]) return 2 options = { 'chart': { 'height': '50%', # default None }, 'title': { 'text': 'Price Difference', }, "tooltip": { "xDateFormat": "%Y-%m-%d %H:%M:%S %A", # NOTE: BUG, 设置不生效 'pointFormat': '<span style="color:{point.color}">' + '\\u25CF'.decode('unicode-escape') + \ '</span> {series.name}: <b>{point.y}</b><br/>', 'padding': 1, # default 8 }, "legend": { "enabled": True }, "xAxis": { "type": "datetime" }, 'yAxis': { 'title': { 'text': '价格', }, 'opposite': True, # False 表示在左边显示,默认值为 True }, # 这是K线图的属性,不画K线图的话不需要 "plotOptions": { "candlestick": { "color": "#d75442", "upColor": "#6ba583" } }, "rangeSelector": { "buttons": [ { "type" : "hour", "count" : 1, "text" : "1h", }, { "type" : 'hour', "count" : 3, "text" : "3h" }, { "type" : "hour", "count" : 6, "text" : "6h" }, { "type" : "hour", "count" : 12, "text" : "12h" }, { "type" : "all", "text" : "All" } ], #"selected": 2, # 默认选择的索引号,从0开始,默认值为 undefined "inputEnabled": True, "inputBoxWidth": 150, # default 90 'inputDateFormat': '%Y/%m/%d %H:%M:%S', 'inputEditDateFormat': '%Y/%m/%d %H:%M:%S', }, } chart = Highstock() chart.set_options('global', {'timezoneOffset': -8 * 60}) chart.set_dict_options(options) #chart.set_options('chart', {'height': None}) chart.set_options( 'tooltip', { #'pointFormat': '<span style="color:{point.color}">' + '\\u25CF'.decode('unicode-escape') + \ #'</span> {series.name}: <b>{point.y:.%df}</b><br/>' % prec, 'valueDecimals': prec, 'valueSuffix': ' ' + symbol.replace('/', '_').upper().split('_')[1], }) ers = [] stats = {} for exchange in exchanges: inst = ExchangeRecords(exchange, symbol, sdt, edt, folder) ers.append(inst) stats[exchange] = {} stats[exchange]['records_count'] = 0 chart.set_options('subtitle', {'text': ers[0].symbol.replace('_', '/')}) # 'binance': {'Buy': x, 'Sell': y} all_records = {} loop_count = 0 # 标记哪个交易所已经拿完数据了 # {exchange: True/False, ...} ctl = {} for inst in ers: ctl[inst.exchange] = False while True: all_true = True for v in ctl.itervalues(): if not v: all_true = False break if ctl and all_true: break loop_count += 1 for inst in ers: record = inst.get_one_record() if record is None: ctl[inst.exchange] = True continue records_dict = all_records.setdefault(inst.exchange, {}) if not record: #ctl[inst.exchange] = True continue stats[inst.exchange]['records_count'] += 1 # 不需要小数点 t = int(int(float(record[0])) * 1000) #t += 3600*1000*8 # GMT+8 buy = records_dict.setdefault('buy', []) buy.append([t, float(record[1])]) sell = records_dict.setdefault('sell', []) sell.append([t, float(record[2])]) last = records_dict.setdefault('last', []) last.append([t, float(record[3])]) if verbose: print('loop_count:', loop_count) Log(json.dumps(stats, indent=4, sort_keys=True)) for exchange in exchanges: records_dict = all_records[exchange] chart.add_data_set(records_dict['buy'], series_type='line', name='%s buy' % exchange) chart.add_data_set(records_dict['sell'], series_type='line', name='%s sell' % exchange) chart.add_data_set(records_dict['last'], series_type='line', name='%s last' % exchange) # 后缀名值 .html chart.save_file(filename=fname) Log('Successfully write to the file:', fname + '.html')