Пример #1
0
def get_bar_chart():
    chart_data = Buy2LineChart.fund_line(get_conf()['基金']['基金购买记录'])
    line_data = Line()

    all_date = None

    for _, chart_data_val in chart_data.items():
        p1, p2, p3, p4, p5 = chart_data_val[0],chart_data_val[1],chart_data_val[2],chart_data_val[3],chart_data_val[4]
        line_data = line_data.add_xaxis(p1).add_yaxis(p2, p3, markline_opts=p4, markpoint_opts=p5)
        all_date = p1
        
    # 双轴,副轴为上证指数
    index_vals = IndexHistory.get_history(all_date[0])
    # min_axis, max_axis = min(index_vals), max(index_vals)
    # last_x, last_y, last_val = all_date[-1], int(index_vals[-1]-2900), index_vals[-1]
    # print(last_x, last_y, last_val)
    sh_index = Line().add_xaxis(all_date).add_yaxis('上证指数', [int(x-2900) for x in index_vals], 
    # markline_opts=[100], 
        # markpoint_opts=[opts.MarkPointItem(coord=[last_x, last_y], value=last_val, symbol=SymbolType.RECT)],
        yaxis_index=1)
        # .extend_axis(yaxis=opts.AxisOpts(min_=[min_axis], max_=[max_axis]))
    line_data.extend_axis(yaxis=opts.AxisOpts(interval=50)).overlap(sh_index)
    # see: http://pyecharts.org/#/zh-cn/rectangular_charts

    c = (line_data)
    return c.dump_options_with_quotes()
Пример #2
0
def plot_multiple_line(x_axis,
                       y_axis_dict,
                       title,
                       double_ylabel_str,
                       double_ylabel=False,
                       ylabel_smooth=False,
                       is_show=True):
    # 由于全部展示图例时数字太多影响效果,is_show用于控制是否展示或者都不展示
    line = Line()
    line.add_xaxis(x_axis)
    for _name in y_axis_dict.keys():
        if _name != double_ylabel_str:
            line.add_yaxis(_name,
                           y_axis_dict[_name],
                           label_opts=opts.LabelOpts(is_show=is_show))
    line.set_global_opts(title_opts=opts.TitleOpts(title=title, pos_top=20),
                         toolbox_opts=opts.ToolboxOpts(pos_top=30),
                         legend_opts=opts.LegendOpts(pos_bottom=0,
                                                     orient="horizontal"))
    if double_ylabel:
        line.extend_axis(yaxis=opts.AxisOpts(
            name=double_ylabel_str, axislabel_opts=opts.LabelOpts(interval=5)))
        line.add_yaxis(double_ylabel_str,
                       y_axis_dict[double_ylabel_str],
                       yaxis_index=1,
                       is_smooth=ylabel_smooth)

    return line
Пример #3
0
def gen_line(df1):
    #df1['datetime'] = df1['date'] + ' ' + df1['time']
    df1['datetime'] = df1['date']
    dt_list1 = list(df1['datetime'])
    # print( len(dt_list1) )
    # dt_list1 = [s[5:10] for s in dt_list1]
    close_list1 = df1.apply(lambda record: float(record['close1']),
                            axis=1).tolist()
    close_list1 = np.array(close_list1)
    # print(close_list1)
    close_list2 = df1.apply(lambda record: float(record['close2']),
                            axis=1).tolist()
    close_list2 = np.array(close_list2)

    price_min = 9000
    line1 = Line(init_opts=opts.InitOpts(width='1500px', height='600px'))
    line1.set_global_opts(
        yaxis_opts=opts.AxisOpts(
            min_=price_min,
            #max_=price_max,
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),
        ),
        datazoom_opts=[
            opts.DataZoomOpts(
                is_show=True,
                type_="slider",
                range_start=0,
                range_end=100,
            ),
        ],
    )

    line1.extend_axis(yaxis=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
        formatter="{value} °C")))

    line1.add_xaxis(xaxis_data=dt_list1)
    line1.add_yaxis(
        'left',
        y_axis=close_list1,
    )
    line1.add_yaxis('right', y_axis=close_list2, yaxis_index=1)

    line1.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

    return line1
Пример #4
0
             data=[opts.MarkPointItem(type_="max",
                                      name="最大值")],  #最大值圆点配置
             symbol_size=40),
         label_opts=opts.LabelOpts(is_show=False)  #不显示每个点的值
     )
 c.set_global_opts(  #全局配置开始
     # title_opts = opts.TitleOpts(title = "The Development of COVID-19 News"),
     xaxis_opts=opts.AxisOpts(
         axislabel_opts=opts.LabelOpts(interval=30),
         name="Date",
         name_gap=30),
     yaxis_opts=opts.AxisOpts(name_rotate=90,
                              name_location="center",
                              name_gap=30))
 c.extend_axis(yaxis=opts.AxisOpts(name_rotate=90,
                                   name_location="center",
                                   name_gap=60))  #基于折线图扩展纵坐标,设置右边的纵坐标
 b = Bar()  #开始画底层的柱状图
 b.add_xaxis(publish_date)
 #  for death_type in [publisher_dic[publisher], 'Global']:
 for death_type in [publisher_dic[publisher]]:  #开始加daily cases柱状图
     y = []
     for day in publish_date:
         df_value = death_df[death_df['Date'] == day][
             death_type]  #death_type是不同的国家
         if len(df_value) > 0:  #57-60,把没有新闻量的日期设置为0
             y.append(int(df_value))
         else:
             y.append(0)
     b.add_yaxis(
         death_type + " daily cases",
Пример #5
0
def draw_charts(kline_data ,canshu ={} ,canshu2={},vol_bar=False,markline_show1 =False ,markline_show2 =False, path = '0501'):
    '''
    df['candle_begin_time','open','high','low','close','volume']
    [['candle_begin_time','open','high','low','close','volume']]

    kdata = df[['open', 'high', 'low', 'close']].values.tolist()
    df['candle_begin_time'].values.tolist()
    :return:
    '''

    df = kline_data.copy()

    df['candle_begin_time'] = pd.to_datetime(df['candle_begin_time'])
    time_list = df['candle_begin_time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')).values.tolist()
    vol = df['volume'].values.tolist()
    kline = Kline()
    kline.add_xaxis(xaxis_data=time_list)
    signal_pos_list = []
    if 'signal' in df.columns:
        print('signal,存在!')
        df['pos'] = df['signal'].shift(1)
        for i  in df[df['pos'] > 0].index:
            bar0 = df.iloc[i]
            sig_pos0 = opts.MarkPointItem(name="做多",
                               coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low -2],
                               value='买',
                               symbol ='circle',
                               symbol_size =[20,40],
                               itemstyle_opts = {'color': 'red'})

            signal_pos_list.append(sig_pos0)
        for i in df[df['pos'] < 0].index:
            bar0 = df.iloc[i]
            sig_pos0 = opts.MarkPointItem(name="做空",
                                          coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.high +3],
                                          value='卖',
                                          symbol='circle',
                                          symbol_size=[20, 40],
                                          itemstyle_opts={'color': 'blue'})
            signal_pos_list.append(sig_pos0)
        for i  in df[df['pos'] == 0].index:
            bar0 = df.iloc[i]
            sig_pos0 = opts.MarkPointItem(name="平仓",
                               coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low - 2],
                               value='平',
                               symbol ='triangle',
                               symbol_size =[20,40],
                               itemstyle_opts = {'color': 'green'})

            signal_pos_list.append(sig_pos0)
    else :
        df['pos'] =None
    markline =[]
    if markline_show1 and ('signal' in df.columns) :
        area_index_list =[i for i  in df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index]
        for ix,i in enumerate(area_index_list):
            if ix+1 > len(area_index_list)-1:
                break
            i_now = df.iloc[area_index_list[ix]]
            i_next = df.iloc[area_index_list[ix+1]]
            if (i_now['pos'] >0) or (i_now['pos'] <0) :
                log_info = f"价差:={i_next['open']-i_now['open']}--({i_next['open']}-{i_now['open']})"
            else :
                log_info =f"平仓:{i_next['open']}---开仓:{i_now['open']}"
            sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),
                            "yAxis": i_now['open'] ,
                            "value": None},
                        {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),
                         "yAxis": i_now['open'],
                         "value":log_info}]
            sig_area_v = [{"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),
                            "yAxis": i_now['open'] ,
                            "value": None},
                        {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),
                         "yAxis": i_next['open'],
                         "value":None}]
            markline.append(sig_area)
            markline.append(sig_area_v)

    elif markline_show2 and ('signal' in df.columns):
        area_index_list =[i for i in  df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index]
        for ix,i in enumerate(area_index_list):
            i_now = df.iloc[area_index_list[ix]]
            i_1_now = df.iloc[area_index_list[ix-1]] if ix != 0 else 0
            if i_now['pos'] == 0:
                log_info = f"交易价: {round(i_now['open'], 1)} +- 2__盈亏:{round(i_now['open'], 1) - round(i_1_now['open'], 1)}"
            else:
                log_info = f"交易价: {round(i_now['open'],1)} +- 2"

            sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),
                            "yAxis": i_now['open'] ,
                            "value": None},
                        {"xAxis": (i_now['candle_begin_time']+timedelta(minutes=15)).strftime('%Y-%m-%d %H:%M:%S'),
                         "yAxis": i_now['open'],
                         "value":log_info}]

            markline.append(sig_area)


    colors = {'red': 'rgb((220,20,60)','red2': 'rgb((250,20,40)',
              'yangzi': 'rgb(255,0,255)', 'zi': 'rgb(128,0,128)',
              'sehnzi': 'rgb(148,0,211)', 'blue': 'rgb(0,0,255)',
              'qing': 'rgb(0,255,255)', 'black': 'rgb(0,0,0)',
              'shengreen': 'rgb(157,255,212)', 'green': 'rgb(0,255,0)',
              'yellow': 'rgb(255,255,0)', 'glod': 'rgb(218,165,32)',
              'orange': 'rgb(255,165,0)', 'brown': 'rgb(165,42,42)'}
    kline.add_xaxis(xaxis_data=time_list)
    kline.add_yaxis(series_name="oclh",
                    xaxis_index=1,
                    yaxis_index=1,
                    y_axis =df.loc[:, ['open', 'close', 'low', 'high']].values.tolist(),
                    markline_opts=opts.MarkLineOpts(data=markline,
                                                    linestyle_opts=opts.LineStyleOpts(type_='dotted',width=3,color='red',opacity=0.5),
                                                    label_opts=opts.LabelOpts(position="right", color="blue", font_size=13),),
                    #官网给出的样本
                    markpoint_opts=opts.MarkPointOpts(data=signal_pos_list),
                    itemstyle_opts=opts.ItemStyleOpts(color="#ec0090", color0="#00aa3c"), )

    kline.set_global_opts(
                    legend_opts=opts.LegendOpts(is_show=True,pos_top=30, pos_left="left",orient='vertical'),
                    datazoom_opts=[ opts.DataZoomOpts(
                                        is_show=False,
                                        type_="inside",
                                        xaxis_index=[0, 1],
                                        range_start=90,
                                        range_end=100,
                                        orient='vertical'),
                                    opts.DataZoomOpts(
                                        is_show=True,
                                        xaxis_index=[0, 1],
                                        type_="slider",
                                        pos_top="20%",
                                        range_start=90,
                                        range_end=100,orient='vertical'),],
                    yaxis_opts =opts.AxisOpts(
                                is_scale=True,
                                splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),),
                    title_opts=opts.TitleOpts(
                        title = 'K_line',
                        pos_top='middle',
                        title_textstyle_opts=opts.TextStyleOpts(
                            color='black',font_weight='bold' ,font_size=20)),
                    tooltip_opts=opts.TooltipOpts(
                                trigger="axis",
                                trigger_on='"mousemove"',#click|mousemove
                                axis_pointer_type="cross",
                                is_show_content=True,
                                is_always_show_content=True,
                                background_color="rgba(20, 105, 245, 0.1)",
                                border_width=1,
                                border_color= "#ccc",
                                position = ['70%','30%'],
                                textstyle_opts=opts.TextStyleOpts(font_size=10,color="#000"),),
                    visualmap_opts=opts.VisualMapOpts(
                                is_show=True,
                                dimension=2,
                                series_index=5,
                                is_piecewise=True,
                                pieces=[{"value": 1, "color": "#00da3c"},{"value": -1, "color": "#ec0000"},],),
                    axispointer_opts=opts.AxisPointerOpts(
                                is_show=True,
                                link=[{"xAxisIndex": "all"}],
                                label=opts.LabelOpts(background_color="#777"),),
                    brush_opts=opts.BrushOpts(
                                x_axis_index="all",
                                brush_link="all",
                                out_of_brush={"colorAlpha": 0.1},
                                brush_type="lineX",),
    )

    if len(canshu.keys())>0:
        cos = list(colors.values())
        line =  Line()
        for k,v in canshu.items():
            line.add_xaxis(xaxis_data=time_list)
            line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))
            co = cos.pop()
            line.add_yaxis(
            series_name=k,
            y_axis = [y for y in v.values.tolist() if y != np.nan],
            xaxis_index=1,
            yaxis_index=1,
            is_smooth=False,
            is_connect_nones=False,# 是否连接空数据
            is_symbol_show=False,#是否显示值的位置,默认显示。
            color = co,
            is_hover_animation = False, # 是否开启 hover 在拐点标志上的提示动画效果。
            linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9,color=co),
            label_opts=opts.LabelOpts(is_show =True,position='middle',distance=2,rotate=5,color = 'rgb(165,42,42)'),
            itemstyle_opts=opts.ItemStyleOpts(color=co),)
        kline = kline.overlap(line)

    grid_chart = Grid(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK))
    grid_chart.add(kline,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%",pos_top='4%' ,height="70%"))

    if( vol_bar == True) or (len(canshu2.keys())==0):
        bar = Bar()
        bar.add_xaxis(xaxis_data=time_list)
        bar.add_yaxis(
            series_name="volume",
            y_axis=vol,
            xaxis_index=1,
            yaxis_index=2,
            label_opts=opts.LabelOpts(is_show=False), )

        bar.set_global_opts(xaxis_opts=opts.AxisOpts(
            type_="category",
            is_scale=True,
            grid_index=1,
            boundary_gap=False,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=False),
            split_number=20,
            min_="dataMin",
            max_="dataMax", ),
            yaxis_opts=opts.AxisOpts(
                grid_index=1,
                is_scale=True,
                split_number=2,
                axislabel_opts=opts.LabelOpts(is_show=False),
                axisline_opts=opts.AxisLineOpts(is_show=False),
                axistick_opts=opts.AxisTickOpts(is_show=False),
                splitline_opts=opts.SplitLineOpts(is_show=False), ),
            legend_opts=opts.LegendOpts(is_show=True), )
        grid_chart.add(bar,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="80%", height="15%"),)

    if len(canshu2.keys())>0 :
        line2 = Line()
        line2.add_xaxis(xaxis_data=time_list)
        for i, k in enumerate(canshu2.keys()):
            co = random.choice(list(colors.values()))
            line2.add_yaxis(
                series_name=k,
                y_axis=[y for y in canshu2[k].values.tolist()],
                xaxis_index=1,
                yaxis_index=i + 1,
                is_smooth=True,
                is_symbol_show=False,
                is_hover_animation=True,
                color=co,
                z_level=0,
                linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.5, color=co),
                label_opts=opts.LabelOpts(is_show=False), )
            if k == list(canshu2.keys())[-1]: continue
            line2.extend_axis(yaxis=opts.AxisOpts(name=k, type_="value", position="right", min_=None, max_=None,
                                                  axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color=co)),
                                                  axislabel_opts=opts.LabelOpts(formatter="{value}"), ))
        line2.set_global_opts(xaxis_opts=opts.AxisOpts(
            type_="category", is_scale=True, grid_index=1, split_number=20, min_="dataMin", max_="dataMax",
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=False), ),
            yaxis_opts=opts.AxisOpts(name=k, grid_index=i + 1, position='right',
                                     splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),
                                     min_=None, max_=None, is_scale=True, offset=50, ), )
        grid_chart.add(line2,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="75%", height="23%"),is_control_axis_index=True)


    tab = Tab()

    zijin_data = (kline_data['per_lr'].cumsum())
    zijin_data.fillna(method='ffill', inplace=True)
    zijin_line = Line(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK)).add_xaxis(time_list)
    zijin_line.add_yaxis(series_name="zijin_line:", y_axis=zijin_data.values, color="#FF0000")
    zijin_line.set_global_opts(

            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
            title_opts=opts.TitleOpts(title="资金曲线变化"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
            yaxis_opts = opts.AxisOpts(
                is_scale=True,
                axislabel_opts=opts.LabelOpts(is_show=False),
                axisline_opts=opts.AxisLineOpts(is_show=False),
                axistick_opts=opts.AxisTickOpts(is_show=False),
                splitline_opts=opts.SplitLineOpts(is_show=False), ),
                 legend_opts = opts.LegendOpts(is_show=True)
    )
    tab.add(grid_chart,'kline' )
    tab.add(zijin_line,'资金曲线变化' )
    tab.render(f"{path}.html")
    html0 = tab.render(f"{path}.html")
    if os.path.exists(html0):
        print("ok!保存在:")
        print(html0)
    else:
        print('保存失败!')
Пример #6
0
def draw_line_charts(input_data,input_data2,canshu =[],path=''):
    canshu_list = []
    max0 = int(max(input_data[canshu].max())*1.001)
    min0 =  int(min(input_data[canshu].min())*0.995)
    print(max0,min0)
    for i in canshu:
        canshu_dict0 = {}
        canshu_dict0[i] = input_data[i]
        canshu_list.append(canshu_dict0)
    print(input_data.keys())
    print(input_data.tail(100))
    input_data['candle_begin_time'] = pd.to_datetime(input_data['candle_begin_time'])
    time_list = input_data['candle_begin_time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')).values.tolist()

    tab = Tab()
    line_base = Line(init_opts=opts.InitOpts(width="1500px", height="700px", theme=ThemeType.DARK)).add_xaxis(time_list)
    line_base.add_yaxis(series_name="close:",
                        y_axis=input_data['close'].values,
                        is_symbol_show=False,

                        color="#FF0000")
    line_base.set_global_opts(
        datazoom_opts=[opts.DataZoomOpts(range_start=95,
            range_end=100,), opts.DataZoomOpts(
            type_="inside",
            range_start=95,
            range_end=100,
            )],
        title_opts=opts.TitleOpts(title="资金曲线变化"),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            axislabel_opts=opts.LabelOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False), ),
            legend_opts=opts.LegendOpts(is_show=True)    )
    for ix,v in enumerate(canshu_list):
        v0:str
        value0:dict
        for k,v0 in v.items():
            name =k
            value0 = v0
        data0 = pd.DataFrame(value0)
        data0.fillna(method='bfill',inplace=True)
        # print(data0)
        line_base.add_yaxis(
            series_name=name,
            y_axis=data0.values.tolist(),
            yaxis_index=2,
            linestyle_opts=opts.LineStyleOpts(),
            label_opts=opts.LabelOpts(is_show=False),
        )
        line_base.extend_axis(
            yaxis=opts.AxisOpts(
            name="资金情况",
            name_location="start",
            type_="value",
            max_= max0,
            min_= min0,
            is_inverse=False,
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),))
    tab.add(line_base,'资金变化')

    table0 = Table().add(list(input_data2.columns), input_data2.values.tolist()).set_global_opts(
                    title_opts=ComponentTitleOpts(title="策略统计", subtitle=str(dt.datetime.now())))
    table0.add_js_funcs('''
    document.write("<p style='color:#FF0000;'>
        注释:none </p>"
                        ''')
    tab.add(table0,'策略统计表')

    html0 =tab.render(path)
    if os.path.exists(html0):
        print("ok!保存在:")
        print(html0)
    else:
        print('保存失败!')
Пример #7
0
from pyecharts import options as opts
# 连接数据库
connect = pymysql.Connect(
    host='localhost',
    port=3306,
    user='******',
    passwd='demo1029',
    db='mysql',
    charset='utf8'
)
# 获取游标
cursor = connect.cursor()
ItemName = input('输入需要搜索的物品名称:')
xaxis = []
yaxis = []
yaxis1 = []
sql = "select * from mysql.itemprice where itemname = '"+ItemName+"' order by updatetime"
cursor.execute(sql)
for i in cursor.fetchall():
    xaxis.append(i[4])
    yaxis.append(i[1])
    yaxis1.append(i[3])
line = Line()
line.add_xaxis(xaxis)
line.add_yaxis(ItemName, yaxis)
line.add_yaxis(ItemName, yaxis1, yaxis_index =1)
line.extend_axis(yaxis=opts.AxisOpts())
line.render(path='d:/1.html')

cursor.close()
connect.close()
Пример #8
0
    def v_tradecost_ktest(
        self, unitcost=True, start=None, end=yesterdayobj(), rendered=True
    ):
        """
        visualization giving the average cost line together with netvalue line as well as buy and sell points

        :returns: pyecharts.line
        """
        # funddata = []
        # costdata = []

        pprice = self.price[self.price["date"] <= end]
        pcftable = self.cftable

        if start is not None:
            pprice = pprice[pprice["date"] >= start]
            pcftable = pcftable[pcftable["date"] >= start]
        # for _, row in pprice.iterrows():
        #     date = row["date"]
        #     funddata.append(row["netvalue"])
        #     if unitcost:
        #         cost = 0
        #         if (date - self.cftable.iloc[0].date).days >= 0:
        #             cost = self.unitcost(date)
        #         costdata.append(cost)
        #
        coords = []
        # pcftable = pcftable[abs(pcftable["cash"]) > threhold]
        # for i, r in pcftable.iterrows():
            # coords.append([r.date, pprice[pprice["date"] <= r.date].iloc[-1]["netvalue"]])
        def marker_factory(x, y):
            buy = pcftable[pcftable["date"] <= x].iloc[-1]["cash"]
            print("buy",buy)
            if buy < 0:
                color = "#ff7733"
            else:

                color = "#3366ff"
            size = (abs(buy) - lower) / (upper - lower) * 5 + 5
            print("size",size)
            return opts.MarkPointItem(
                coord=[x.date(), y],
                itemstyle_opts=opts.ItemStyleOpts(color=color),
            # this nested itemstyle_opts within MarkPointItem is only supported for pyechart>1.7.1
                symbol="circle",
                symbol_size=size,
            )

        def marker_factory3v(x, y):
            buy = pcftable[pcftable["date"] <= x].iloc[-1]["cash"]
            print("buy",buy)
            if buy < 0:
                color = "#ff7733"
            else:

                color = "#3366ff"
            # size = (abs(buy) - lower) / (upper - lower) * 5 + 5
            size = len(str(buy)) * 10
            print("size",size)
            return opts.MarkPointItem(
                value = -buy,
                coord=[x.date(), y],
                itemstyle_opts=opts.ItemStyleOpts(color=color),
            # this nested itemstyle_opts within MarkPointItem is only supported for pyechart>1.7.1
                # symbol="circle",
                symbol_size=size,
            )



        coords_cash = []
        # print("pcftable",pcftable)
        # print("pprice",pprice)
           #cash begin
        cashdata = []
        valuedata = []
        # partp = self.price[self.price["date"] >= self.cftable.iloc[0].date]
        # 多基金账单时起点可能非该基金持有起点
        # partp = partp[partp["date"] <= end]

        # valuedata = [
            # self.briefdailyreport(d).get("currentvalue", 0) for d in partp.date
            # self.briefdailyreport(d).get("currentvalue", 0) for d in pprice.date
        # ]
        # print(pprice.date)
        # print("begin to cal ccost")
        for d in pprice.date:
            ucost = self.unitcost(d)
            cshare = self.briefdailyreport(d).get("currentshare")
            if(ucost is None or cshare is None  ):
                valuedata.append(0)
                cashdata.append(0)
            else:
                cashdata.append(ucost*cshare)
                valuedata.append(self.briefdailyreport(d).get("currentvalue", 0))
        #     # self.unitcost(d)*self.briefdailyreport(d).get("currentshare")  for d in partp.date
        #     self.unitcost(d)*self.briefdailyreport(d).get("currentshare")  for d in pprice.date
        # ]
       #cash end


      # date = [d.date() for d in partp.date]
        date = [d.date() for d in pprice.date]
        date_dict = {}
        for i,d in enumerate(date):
            date_dict[convert_date(d)]=i
        # print("date_dict",date_dict)
        # print("date",date)
        # print("cashdata",cashdata)
        # pcftable = pcftable[abs(pcftable["cash"]) > threhold]
        # print("print offset")
        offset = pcftable["date"]
        # print("offset",offset)
        offset = offset[0]
        offsetdate = []
        coords_markvalue = []
        pos = 3
        for i, r in pcftable.iterrows():
            # print("i,r",i,r)
            # print("r.date",type(r.date.date()))
            # print("convert_date(r.date)",type(convert_date(r.date)))
            # print("date_dict[r.date]",date_dict[convert_date(r.date.date())])


            offset = r.date - offset

            valuecoords = valuedata[date_dict[convert_date(r.date.date())]]
            cashcoords = cashdata[date_dict[convert_date(r.date.date())]]
            distance = valuecoords - cashcoords
            if(pos == 3):
                coords_markvalue.append([r.date,cashcoords,offset])
                pos =0
            elif(pos == 0 ):
                coords_markvalue.append([r.date,cashcoords + distance/2,offset])
                pos = 1
            elif(pos == 1):
                coords_markvalue.append([r.date,valuecoords,offset])
                pos =2
            elif(pos ==2 ):
                coords_markvalue.append([r.date,cashcoords,offset])
                pos = 0



            # if(distance>2000):
                # pos = 1
                # coords_markvalue.append([r.date,cashcoords + distance/2,offset])
            # elif(distance<-2000):
                #coords_markvalue.append([r.date,valuecoords - distance/2,offset])
                # coords_markvalue.append([r.date,valuecoords - distance/2,offset])
            # else:
                #coords_markvalue.append([r.date,valuecoords,offset])
                # coords_markvalue.append([r.date,cashcoords,offset])

            coords_cash.append([r.date, cashdata[date_dict[convert_date(r.date.date())]],offset])
            coords.append([r.date,cashdata[date_dict[convert_date(r.date.date())]]])
            offsetdate.append(offset)
            offset = r.date
        # offsetdate[0] = pd.Timedelta(1,unit = "D")

        print("coords_cash",coords_cash)
        print("len(coords_cash)",len(coords_cash))
        # print("offsetdate",offsetdate)
        print("len(offsetdate)",len(offsetdate))


        upper = pcftable.cash.abs().max()
        lower = pcftable.cash.abs().min()
        if upper == lower:
            upper = 2 * lower + 1  # avoid zero in denominator
        global previous
        global direction
        previous = 0
        direction = 1


        def marker_factory1v(x, y,offsetday):
            offset = 0
            buy = pcftable[pcftable["date"] <= x].iloc[-1]["cash"]
            markvalue = 0
            ycoor = y
            global direction
            global previous
            print("previous before:",previous)

            # loc = (abs(buy) - lower) / (upper - lower) * 5000 + 5000
            loc = len(str(buy)) * 1000 + 1000
            if buy < 0:
                color = "#ff7733"
                markvalue = -buy
                if(offsetday < pd.Timedelta(7,unit = "D")):
                    offset = -100
                    ycoor = y + loc*previous*direction
                    previous = 1
                    direction =-direction
                else:
                    previous = 0

            else:
                color = "#3366ff"
                markvalue = -buy
                if(offsetday < pd.Timedelta(7,unit = "D")):
                    ycoor = y + loc*previous*direction
                    direction = -direction
                    previous = 1
                else:
                    previous = 0
            print("previous after",previous)
            # size = (abs(buy) - lower) / (upper - lower) * 50 + 50
            size = len(str(buy)) * 10
            return opts.MarkPointItem(name="test",
                coord=[x.date(), ycoor],
                value = -buy,
                itemstyle_opts=opts.ItemStyleOpts(color=color),
                # this nested itemstyle_opts within MarkPointItem is only supported for pyechart>1.7.1
                # symbol="circle",
                # symbol="rectangle",
                symbol_size=size,
            )
        def marker_factory2v(x, y,offsetday):
            offset = 0
            buy = pcftable[pcftable["date"] <= x].iloc[-1]["cash"]
            markvalue = 0
            ycoor = y
            global direction
            global previous
            print("previous before:",previous)
            print("offsetday",offsetday)
            print("day",x.date())

            # loc = (abs(buy) - lower) / (upper - lower) * 5000 + 5000
            loc = len(str(buy)) * 100
            if buy < 0:
                color = "#ff7733"
                markvalue = -buy
                if(offsetday < pd.Timedelta(5,unit = "D")):
                    offset = -100
                    #ycoor = y + loc*previous*direction
                    ycoor = y +loc*previous*direction
                    previous = 1
                    direction =-direction
                else:
                    previous = 0

            else:
                color = "#3366ff"
                markvalue = -buy
                if(offsetday < pd.Timedelta(5,unit = "D")):
                    #ycoor = y + loc*previous*direction
                    ycoor = y + loc*previous*direction
                    direction = -direction
                    previous = 1
                else:
                    previous = 0
            print("previous after",previous)
            # size = (abs(buy) - lower) / (upper - lower) * 50 + 50
            size = len(str(round(-buy))) * 12
            return opts.MarkPointItem(name="test",
                coord=[x.date(), ycoor],
                value = -round(buy),
                itemstyle_opts=opts.ItemStyleOpts(color=color),
                # this nested itemstyle_opts within MarkPointItem is only supported for pyechart>1.7.1
                # symbol="circle",
                # symbol="rectangle",
                symbol_size=size,
            )


        # print("getting cashdata,pprice",pprice.date)


            # print("2cashdata",cashdata)
        # print("funddata",funddata)
        print("len(2chashdata)",len(cashdata))
        # print("funddata",len(funddata))
        # print("valuedata",valuedata)
        print("len(valuedata)",len(valuedata))

        line = Line()

        #line.add_xaxis([d.date() for d in pprice.date])
        line.add_xaxis(date)

        line.add_yaxis(
                       series_name="持仓总值1",
                       y_axis=valuedata,
                       # is_symbol_show=False,
                       # )

            # y_axis=funddata,
            is_symbol_show=False,
            markpoint_opts=opts.MarkPointOpts(
                data=[marker_factory2v(*c) for c in coords_markvalue],
            ),
        )
        line.extend_axis(
                         yaxis = opts.AxisOpts(
                                axislabel_opts = opts.LabelOpts(formatter="{value}%",)))
        print("xianjinzhi")
        line.add_yaxis(
            series_name="现金值",
            y_axis=cashdata,
            is_symbol_show=False,
            markpoint_opts=opts.MarkPointOpts(
                # data=[marker_factory(*c) for c in coords_cash],
                data=[marker_factory(*c) for c in coords],
                # symbol = "circle",
                # symbol_size =size,
            ),
        )

        def tooltip_factory(coords):
            for x,y in coords:
                return opts.TooltipOpts(
                is_show=True,
                trigger="axis",
                trigger_on="mousemove",
                axis_pointer_type="cross",
                formatter = str(y)
            )

        line.set_global_opts(
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=True, type_="slider", range_start=50, range_end=100
                ),
                opts.DataZoomOpts(
                    is_show=True,
                    type_="slider",
                    orient="vertical",
                    range_start=50,
                    range_end=100,
                ),
            ],
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                trigger="axis",
                # trigger_on="mousemove",
                trigger_on="click",
                axis_pointer_type="cross",
                # formatter = [tooltip_factory(*c) for c in coords]
                formatter = JsCode(
                    """function(params){
                    if(params.dataIndex){
                    return params.dataIndex
                    }
                    else{
                    return params
                    }
                }
                    """
                )
            ),
            # tooltip_opts=tooltip_factory(coords)
            # tooltip_opts=tooltip_factory(coords)
        )

        if rendered:
            return line.render_notebook()
Пример #9
0
def generate_line_html2(rows, select=None):
    line = Line(
        opts.InitOpts(height='500px', width='1424px', theme=ThemeType.LIGHT))

    x = []
    y1 = []
    y2 = []

    min_y = 10000
    max_y = 0
    for row in rows:
        x.append(row['date'])
        mid_price = row['mid_price']
        avg_premium = row['avg_premium']
        if mid_price > max_y:
            max_y = mid_price
        elif mid_price < min_y:
            min_y = mid_price

        y1.append(mid_price)
        y2.append(avg_premium)
    delta = max_y - min_y
    interval = round(delta / 5, 2)
    star_up1 = round(min_y + interval * 1, 2)
    star_up2 = round(min_y + interval * 2, 2)
    star_up3 = round(min_y + interval * 3, 2)
    star_up4 = round(min_y + interval * 4, 2)

    line.add_xaxis(x)
    line.extend_axis(
        yaxis=opts.AxisOpts(type_='value',
                            name='溢价率平均值(%)',
                            name_rotate=90,
                            name_gap=55,
                            name_location='middle',
                            is_scale=True,
                            axislabel_opts=opts.LabelOpts(
                                formatter='{value}%'),
                            splitline_opts=opts.SplitLineOpts(is_show=False),
                            axisline_opts=opts.AxisLineOpts(
                                is_on_zero=False, symbol=['none', 'arrow'])))

    line.add_yaxis("价格中位数", y1, yaxis_index=0)
    line.add_yaxis("溢价率平均值", y2, yaxis_index=1)

    line.set_global_opts(
        title_opts=opts.TitleOpts(title="用价格中位数估值",
                                  pos_left='center',
                                  pos_top=-5),
        tooltip_opts=opts.TooltipOpts(trigger='axis', ),
        legend_opts=opts.LegendOpts(
            is_show=True,
            pos_top=20,
            # pos_bottom=-50,
            selected_mode='multiple'),
        datazoom_opts={
            'start': 0,
            'end': 100
        },
        toolbox_opts=opts.ToolboxOpts(feature={
            'dataZoom': {},
        }),
        xaxis_opts=opts.AxisOpts(
            # data=None,
            type_='time',
            name='时间',
            name_gap=30,
            is_scale=True,
            name_location='middle',
            splitline_opts=opts.SplitLineOpts(is_show=False),
            # axislabel_opts=opts.LabelOpts(formatter="{value}"), #echarts.format.formatTime('yy-MM-dd', value*1000)
            axisline_opts=opts.AxisLineOpts(is_on_zero=False,
                                            symbol=['none', 'arrow'])),
        yaxis_opts=opts.AxisOpts(
            type_='value',
            name='价格中位数(元)',
            name_rotate=90,
            name_gap=55,
            name_location='middle',
            is_scale=True,
            axislabel_opts=opts.LabelOpts(formatter='{value}元'),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_on_zero=False,
                                            symbol=['none', 'arrow'])),
        visualmap_opts=opts.VisualMapOpts(is_show=True,
                                          type_='color',
                                          pos_top='50',
                                          pos_left='5',
                                          min_=min_y,
                                          max_=max_y,
                                          is_piecewise=True,
                                          split_number=5,
                                          series_index=0,
                                          pieces=[
                                              {
                                                  'min': min_y,
                                                  'max': star_up1,
                                                  'color': '#93CE07',
                                                  'label': '★★★★★'
                                              },
                                              {
                                                  'min': star_up1,
                                                  'max': star_up2,
                                                  'color': '#FBDB0F',
                                                  'label': '★★★★'
                                              },
                                              {
                                                  'min': star_up2,
                                                  'max': star_up3,
                                                  'color': '#FC7D02',
                                                  'label': '★★★'
                                              },
                                              {
                                                  'min': star_up3,
                                                  'max': star_up4,
                                                  'color': '#FD0100',
                                                  'label': '★★'
                                              },
                                              {
                                                  'min': star_up4,
                                                  'max': max_y,
                                                  'color': '#AC3B2A',
                                                  'label': '★'
                                              },
                                          ]),
    )
    line.set_colors(['lightcoral', 'lightskyblue'])
    line.set_series_opts(
        symbol='none',
        smooth=False,
        linestyle_opts=opts.LineStyleOpts(width=2, ),
        label_opts=opts.LabelOpts(is_show=False),
        markline_opts=opts.MarkLineOpts(
            is_silent=True,
            symbol='none',
            label_opts=opts.LabelOpts(
                position='end',
                is_show=False,
                formatter=JsCode("function (params){return params.name}")),
            linestyle_opts=opts.LineStyleOpts(
                color='#333',
                type_='dashed',
            ),
            data=[
                opts.MarkLineItem(y=min_y, name='0%'),
                opts.MarkLineItem(y=star_up1, name='20%'),
                opts.MarkLineItem(y=star_up2, name='40%'),
                opts.MarkLineItem(y=star_up3, name='60%'),
                opts.MarkLineItem(y=star_up4, name='80%'),
                opts.MarkLineItem(y=max_y, name='100%'),
            ]),
    )
    line_html = line.render_embed('template.html', env)
    return line_html