Example #1
0
 def kline_plot(self,ktype=0):
     df=self.cal_hadata()
     #画K线图数据
     date = df.index.strftime('%Y%m%d').tolist()
     if ktype==0:
         k_value = df[['adjopen','adjclose', 'adjlow','adjhigh']].values
     else:
         k_value = df[['ha_open','ha_close', 'ha_low', 'ha_high']].values
     #引入pyecharts画图使用的是0.5.11版本,新版命令需要重写
     
     kline = Kline(self.name+'行情走势')
     kline.add('日K线图', date, k_value,
           is_datazoom_show=True,is_splitline_show=False)
     #加入5、20日均线
     df['ma20']=df.adjclose.rolling(20).mean()
     df['ma5']=df.adjclose.rolling(5).mean()
     line = Line()
     v0=df['ma5'].round(2).tolist()
     v=df['ma20'].round(2).tolist()
     line.add('5日均线', date,v0,
          is_symbol_show=False,line_width=2)
     line.add('20日均线', date,v, 
          is_symbol_show=False,line_width=2)
     #成交量
     bar = Bar()
     bar.add('成交量', date, df['vol'],tooltip_tragger='axis', 
             is_legend_show=False, is_yaxis_show=False, 
             yaxis_max=5*max(df['vol']))
     overlap = Overlap()
     overlap.add(kline)
     overlap.add(line,)
     overlap.add(bar,yaxis_index=1, is_add_yaxis=True)
     return overlap    
Example #2
0
def grids(data):
    kline = Kline(data.symbol[0])
    kline.add(
        '',
        data.index,
        data.loc[:, ['open', 'close', 'low', 'high']].values,
        mark_line=['max', 'min'],
        mark_line_valuedim=['highest', 'lowest'],
        is_datazoom_show=True,
        datazoom_xaxis_index=[0, 1],
    )

    turnover = Bar()
    turnover.add(
        '',
        data.index,
        data['turnover'].values / pow(10, 9),
        mark_line=['max', 'min'],
        is_datazoom_show=True,
    )

    grid = Grid(page_title=data['symbol'][0], width=1800, height=900)
    grid.add(kline, grid_bottom='40%')
    grid.add(turnover, grid_top='65%')
    grid.show_config()
    return grid
Example #3
0
def brush(data):
    data = hist_sum(data)
    kline = Kline()
    kline.add(
        'Kline',
        data.index,
        data.loc[:, ['open', 'close', 'low', 'high']].values,
        mark_line=['max', 'min'],
        mark_line_valuedim=['highest', 'lowest'],
        is_datazoom_show=True,
        datazoom_xaxis_index=[0, 1],
    )
    brush = Line()
    brush.add(
        'Brush',
        data.index,
        data.endpoint.values,
    )
    overlap = Overlap()
    overlap.add(kline)
    overlap.add(brush)

    macd = Bar()
    macd.add(
        'MACD',
        data.index,
        data.hist_sum.values,
    )
    page = Page()
    page.add(overlap)
    page.add(macd)
    return page
Example #4
0
def drawKline(datadf, tradeRecorddf):
    datadf["datetime"] = datadf["datetime"].dt.strftime("%Y-%m-%d %H:%M:%S")
    OHLC = df[["open", "close", "low", "high"]]
    OHLC = OHLC.values
    DATETIME = df["datetime"].values

    longOrderDF = tradeRecorddf[tradeRecorddf["direction"] == "long position"]
    longOrderDF = longOrderDF[["time", "deal price", "kaiping"]].values
    shortOrderDF = tradeRecorddf[tradeRecorddf["direction"] == "short position"]
    shortOrderDF = shortOrderDF[["time", "deal price", "kaiping"]].values
    markpointlist = []
    for longorders in longOrderDF:
        markpointlist.append(RedArrow(longorders[0], longorders[1], longorders[2]))
    for shortorders in shortOrderDF:
        markpointlist.append(GreenArrow(shortorders[0], shortorders[1], shortorders[2]))

    page = Page()
    grid = Grid(width=1920, height=900)
    kline = Kline("candlestick")
    kline.add("candlestick", DATETIME, OHLC, is_datazoom_show=True, datazoom_type='inside',
              datazoom_range=[90, 100], tooltip_tragger_on='mousemove|click', tooltip_axispointer_type='cross',
              is_label_show=False, mark_point_raw=markpointlist)
    grid.add(kline, grid_top="3%", grid_height="95%")
    page.add(grid)
    now = dt.datetime.now()
    today = now.strftime('%Y%m%d')
    time = now.strftime("%H_%M_%S")
    home = os.environ['HOME']
    page.render(home + "/Pictures/" + today + "/" + "plotKlineChartandSignal" + time + ".html")
Example #5
0
def kxian4_fun():
    from pyecharts import Kline
    api = ts.pro_api(
        'acfe91c33583e4f34c757cfc5360f7e51eefd9f0c259f4204ea4720f')

    # 取000001的前复权行情
    df = ts.pro_bar(pro_api=api,
                    ts_code='000001.SZ',
                    adj='qfq',
                    start_date='20181201',
                    end_date='20181231')
    df = df.sort_index(axis=0)
    df1 = df[['open', 'high', 'open', 'close']]

    v1 = df1.values.tolist()
    kline = Kline("K 线图示例")

    aa = [i for i in df1.index.format()]

    kline.add(
        "日K",
        aa,
        v1,
        mark_point=["max"],
        is_datazoom_show=True,
        datazoom_orient="vertical",
    )
    return kline
Example #6
0
def echart1(request):
    template = loader.get_template('ewpyecharts.html')

    line = Line("压力分析", width=1200, height=700)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高压力", attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"], mark_line=["average"])
    line.add("最低压力", attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"], legend_top="50%", mark_line=["average"],
             # 设置 dataZoom 控制索引为 0,1 的 x 轴,即第一个和第二个
             is_datazoom_show=True, datazoom_xaxis_index=[0, 1])

    v1 = [[2320.26, 2320.26, 2287.3, 2362.94],
          [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58, 2440.38],
          [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("考核表分析", title_top="50%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              v1, is_datazoom_show=True)

    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.add(kline, grid_bottom="60%")
#    grid.render()

    context = dict(
        myechart=grid.render_embed(),
        host=REMOTE_HOST,
        script_list=grid.get_js_dependencies()
    )

    return HttpResponse(template.render(context, request))
 def __init__(self,
              stock_name,
              jsPath='https://cdn.bootcss.com/echarts/4.1.0.rc2'):
     # 使用最新的echarts js文件
     online(jsPath)
     # K线
     self.stock_name = stock_name
     self.kline = Kline(stock_name)
     self.volume_bar = Bar('')
def K_line(date, v1):
    kline = Kline("比特币历史价格")
    kline.add(
        "日K",
        date,
        v1,
        is_datazoom_show=True,
    )
    return kline
Example #9
0
def kline_chart(code, k_data):
    kline = Kline("{0} K 线图".format(code), width="100%")
    kline.add(("日K"),
              k_data['date'],
              k_data[['open', 'close', 'low', 'high']].values.tolist(),
              mark_point=["average"],
              is_datazoom_show=True,
              datazoom_xaxis_index=[0, 1])
    return kline
def K_line(date, v1, name):
    kline = Kline(name)
    kline.add(
        "日K",
        date,
        v1,
        is_datazoom_show=True,
    )
    return kline
Example #11
0
def test_kline_default(patched):
    fixture = "kline_options.json"
    patched.return_value = "1"
    kline = Kline("K 线图-默认示例")
    kline.add("日K", DATE, data)
    actual_options = dumps_actual_options(kline.options)
    expected = get_fixture_content(fixture)
    for a, b in zip(actual_options.split("\n"), expected.split("\n")):
        eq_(a.strip(), b.strip())
Example #12
0
def test_grid_6():

    line = Line("折线图示例", width=1200, height=700)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             legend_top="50%",
             mark_line=["average"],
             is_datazoom_show=True,
             datazoom_xaxis_index=[0, 1])

    v1 = [[2320.26, 2320.26, 2287.3,
           2362.94], [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58,
           2440.38], [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例", title_top="50%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              v1,
              is_datazoom_show=True)

    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.add(kline, grid_bottom="60%")
    grid.render()
Example #13
0
def test_kline_default(patched):
    patched.return_value = "1"
    kline = Kline("K 线图-默认示例")
    kline.add("日K", DATE, data)
    actual_options = json.dumps(
        kline.options, sort_keys=True, indent=4, cls=DefaultJsonEncoder
    )
    expected = get_fixture_content("kline_options.json")
    for a, b in zip(actual_options.split("\n"), expected.split("\n")):
        eq_(a.strip(), b.strip())
Example #14
0
    def __init__(self):

        self.kline = Kline()
        self.kline2 = Kline()
        # 初始化一个指标线
        self.line = Line()
        self.line_long_win = Line()
        self.line_long_loss = Line()
        self.line_short_win = Line()
        self.line_short_loss = Line()
Example #15
0
def kline_chart_sh(sh_index_data):
    kline = Kline("上证 K 线图", width="100%", title_top="50%")
    kline.add(("日K"),
              sh_index_data['date'],
              sh_index_data[['open', 'close', 'low', 'high']].values.tolist(),
              mark_point=["average"],
              is_datazoom_show=True,
              datazoom_xaxis_index=[0, 1],
              legend_top="50%")
    return kline
Example #16
0
def kplot(kdata,
          new=True,
          axes=None,
          colorup='r',
          colordown='g',
          width=0.6,
          alpha=1.0):
    """绘制K线图
    
    :param KData kdata: K线数据
    :param bool new:    是否在新窗口中显示,只在没有指定axes时生效
    :param axes:        指定的坐标轴
    :param colorup:     the color of the rectangle where close >= open
    :param colordown:   the color of the rectangle where close < open
    :param width:       fraction of a day for the rectangle width
    :param alpha:       the rectangle alpha level, 透明度(0.0~1.0) 1.0为不透明
    """
    if not kdata:
        print("kdata is None")
        return

    if axes is None:
        axes = create_figure() if new else gca()

    title = get_draw_title(kdata)
    last_record = kdata[-1]
    text = u'%s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 涨幅:%.2f%%' % (
        last_record.datetime.date(), last_record.openPrice,
        last_record.highPrice, last_record.lowPrice, last_record.closePrice,
        100 *
        (last_record.closePrice - kdata[-2].closePrice) / kdata[-2].closePrice)

    date_list = kdata.getDatetimeList()
    if kdata.getQuery().kType == KQuery.DAY:
        x_list = [d.date() for d in date_list]
    else:
        x_list = [d.datetime() for d in date_list]

    y_list = [[k.openPrice, k.closePrice, k.lowPrice, k.highPrice]
              for k in kdata]

    style = gcf().get_style(axes)
    kline = Kline(title, text, title_pos='center', subtitle_color='#FF0000')
    kline.add(None,
              x_axis=x_list,
              y_axis=y_list,
              mark_line=["max"],
              mark_line_symbolsize=0,
              mark_line_valuedim='highest',
              **style)
    axes.add(kline)

    gcf().set_xaxis(x_list)
    gcf().add_axis(axes)
    return gcf()
Example #17
0
def test_kline_default(patched):
    patched.return_value = "1"
    kline = Kline("K 线图-默认示例")
    kline.add("日K", DATE, data)
    actual_options = json.dumps(kline.options,
                                sort_keys=True,
                                indent=4,
                                cls=DefaultJsonEncoder)
    expected = get_fixture_content("kline_options.json")
    for a, b in zip(actual_options.split("\n"), expected.split("\n")):
        eq_(a.strip(), b.strip())
Example #18
0
def test_kline_datazoom_vertical():
    kline = Kline("K 线图-dataZoom 垂直布局")
    kline.add(
        "日K",
        DATE,
        data,
        mark_line=["max"],
        is_datazoom_show=True,
        datazoom_orient="vertical",
    )
    kline.render()
Example #19
0
def K_line(date, v1):
    kline = Kline("比特币历史价格")
    kline.add(
        "日K",
        date,
        v1,
        is_datazoom_show=True,
    )
    overlap = Overlap()
    overlap.add(kline)
    overlap.render()
Example #20
0
def k_line(stock_num):
    v1, date = to_csv(stock_num)
    if v1 == 0:
        kline = 0
        return kline
    kline = Kline(stock_num, width=800, height=450)
    kline.add("Daily K Line",
              date,
              v1,
              mark_point=["max"],
              is_datazoom_show=True)
    return kline
Example #21
0
def showHotRankOfCity():
    ans = getEchartsK()
    kline = Kline("各城市发文K线图")
    kline.add(
        "",
        list(ans.keys()),
        list(ans.values()),
        mark_point=["min"],
        is_datazoom_show=True,
        #datazoom_orient="vertical",
    )
    #   kline.render()
    return kline
Example #22
0
def plot_line_graph():
    page = Page('back_testing')

    line = Line("K 线图-dataZoom 垂直布局", width=1300, height=400, title_pos="left")
    line.add(
        "日K",
        ["2017/7/{}".format(i + 1) for i in range(31)],
        [random.randint(1, 2000) for _ in range(31)],
        tooltip_trigger="axis",
        tooltip_axispointer_type='cross',
        mark_line=["max", 'min'],
        legend_top="3%",
        mark_point=['average', 'max', 'min'],
        is_smooth=True,
        line_color='#5296de',
        line_width=2.5,
        # yaxis_type="log",
    )

    line.add("日收益", ["2017/7/{}".format(i + 1) for i in range(31)],
             [random.randint(1, 2000) for _ in range(31)],
             tooltip_trigger="axis",
             mark_point=['average', 'max', 'min'],
             mark_line=["max", 'min'],
             is_datazoom_show=True,
             legend_top="3%",
             is_smooth=True,
             line_color='#082039',
             line_width=2.5,
             **style.init_style
             # yaxis_type="log",
             )

    page.add(line)
    # line.show_config()

    kline = Kline("K 线图-dataZoom 水平布局",
                  width=1300,
                  height=400,
                  title_pos="left")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              data,
              mark_point=["max"],
              is_datazoom_show=True,
              **style.init_style)

    page.add(kline)
    # kline.show_config()

    page.render(FILE_DIR + 'line_graph.html')
Example #23
0
def brush(data):
    data = feature.full_data(data)
    print(data.tail())

    kline = Kline()
    kline.add(
        'Kline',
        data.index,
        data.loc[:, ['open', 'close', 'low', 'high']].values,
        # mark_line=['max', 'min'],
        # mark_line_valuedim=['highest', 'lowest'],
        # is_datazoom_show=True,
        # datazoom_xaxis_index=[0, 1, 2],
        # datazoom_type='both',
        # tooltip_axispointer_type='cross',
        # is_more_utils=True,
    )

    brush = Line()
    brush.add(
        'Brush',
        data.index,
        data.endpoint
    )
    overlap = Overlap()
    overlap.add(kline)
    overlap.add(brush)

    turnover = Bar()
    turnover.add(
        '',
        data.index,
        data.turnover.values / pow(10, 6),
        mark_line=['max', 'min']
    )

    macd = Bar()
    macd.add(
        '',
        data.index,
        data.macdhist.values,
        mark_line=['max', 'min'],
    )

    grid = Grid('', width='100%', height=900)
    grid.add(overlap, grid_bottom='40%')
    grid.add(turnover, grid_top='65%', grid_bottom='20%')
    grid.add(macd, grid_top='85%')

    return overlap
Example #24
0
def test_overlap_kline_line():
    import random

    v1 = [
        [2320.26, 2320.26, 2287.3, 2362.94],
        [2300, 2291.3, 2288.26, 2308.38],
        [2295.35, 2346.5, 2295.35, 2345.92],
        [2347.22, 2358.98, 2337.35, 2363.8],
        [2360.75, 2382.48, 2347.89, 2383.76],
        [2383.43, 2385.42, 2371.23, 2391.82],
        [2377.41, 2419.02, 2369.57, 2421.15],
        [2425.92, 2428.15, 2417.58, 2440.38],
        [2411, 2433.13, 2403.3, 2437.42],
        [2432.68, 2334.48, 2427.7, 2441.73],
        [2430.69, 2418.53, 2394.22, 2433.89],
        [2416.62, 2432.4, 2414.4, 2443.03],
        [2441.91, 2421.56, 2418.43, 2444.8],
        [2420.26, 2382.91, 2373.53, 2427.07],
        [2383.49, 2397.18, 2370.61, 2397.94],
        [2378.82, 2325.95, 2309.17, 2378.82],
        [2322.94, 2314.16, 2308.76, 2330.88],
        [2320.62, 2325.82, 2315.01, 2338.78],
        [2313.74, 2293.34, 2289.89, 2340.71],
        [2297.77, 2313.22, 2292.03, 2324.63],
        [2322.32, 2365.59, 2308.92, 2366.16],
        [2364.54, 2359.51, 2330.86, 2369.65],
        [2332.08, 2273.4, 2259.25, 2333.54],
        [2274.81, 2326.31, 2270.1, 2328.14],
        [2333.61, 2347.18, 2321.6, 2351.44],
        [2340.44, 2324.29, 2304.27, 2352.02],
        [2326.42, 2318.61, 2314.59, 2333.67],
        [2314.68, 2310.59, 2296.58, 2320.96],
        [2309.16, 2286.6, 2264.83, 2333.29],
        [2282.17, 2263.97, 2253.25, 2286.33],
        [2255.77, 2270.28, 2253.31, 2276.22],
    ]
    attr = ["2017/7/{}".format(i + 1) for i in range(31)]
    kline = Kline("Kline-Line 示例")
    kline.add("日K", attr, v1)
    line_1 = Line()
    line_1.add("line-1", attr, [random.randint(2400, 2500) for _ in range(31)])
    line_2 = Line()
    line_2.add("line-2", attr, [random.randint(2400, 2500) for _ in range(31)])

    overlap = Overlap()
    overlap.add(kline)
    overlap.add(line_1)
    overlap.add(line_2)
    overlap.render()
Example #25
0
def test_overlap_kline_line():
    import random

    v1 = [
        [2320.26, 2320.26, 2287.3, 2362.94],
        [2300, 2291.3, 2288.26, 2308.38],
        [2295.35, 2346.5, 2295.35, 2345.92],
        [2347.22, 2358.98, 2337.35, 2363.8],
        [2360.75, 2382.48, 2347.89, 2383.76],
        [2383.43, 2385.42, 2371.23, 2391.82],
        [2377.41, 2419.02, 2369.57, 2421.15],
        [2425.92, 2428.15, 2417.58, 2440.38],
        [2411, 2433.13, 2403.3, 2437.42],
        [2432.68, 2334.48, 2427.7, 2441.73],
        [2430.69, 2418.53, 2394.22, 2433.89],
        [2416.62, 2432.4, 2414.4, 2443.03],
        [2441.91, 2421.56, 2418.43, 2444.8],
        [2420.26, 2382.91, 2373.53, 2427.07],
        [2383.49, 2397.18, 2370.61, 2397.94],
        [2378.82, 2325.95, 2309.17, 2378.82],
        [2322.94, 2314.16, 2308.76, 2330.88],
        [2320.62, 2325.82, 2315.01, 2338.78],
        [2313.74, 2293.34, 2289.89, 2340.71],
        [2297.77, 2313.22, 2292.03, 2324.63],
        [2322.32, 2365.59, 2308.92, 2366.16],
        [2364.54, 2359.51, 2330.86, 2369.65],
        [2332.08, 2273.4, 2259.25, 2333.54],
        [2274.81, 2326.31, 2270.1, 2328.14],
        [2333.61, 2347.18, 2321.6, 2351.44],
        [2340.44, 2324.29, 2304.27, 2352.02],
        [2326.42, 2318.61, 2314.59, 2333.67],
        [2314.68, 2310.59, 2296.58, 2320.96],
        [2309.16, 2286.6, 2264.83, 2333.29],
        [2282.17, 2263.97, 2253.25, 2286.33],
        [2255.77, 2270.28, 2253.31, 2276.22],
    ]
    attr = ["2017/7/{}".format(i + 1) for i in range(31)]
    kline = Kline("Kline-Line 示例")
    kline.add("日K", attr, v1)
    line_1 = Line()
    line_1.add("line-1", attr, [random.randint(2400, 2500) for _ in range(31)])
    line_2 = Line()
    line_2.add("line-2", attr, [random.randint(2400, 2500) for _ in range(31)])

    overlap = Overlap()
    overlap.add(kline)
    overlap.add(line_1)
    overlap.add(line_2)
    overlap.render()
Example #26
0
def test_kline_user_define_markline_style():
    kline = Kline("K 线图-自定义标记点风格")
    kline.add("日K", DATE, data, mark_point=["min", "max"],
              mark_point_symbolsize=80,
              datazoom_orient='vertical',
              mark_line_valuedim=['lowest', 'highest'])
    kline.show_config()
    kline.render()
Example #27
0
def test_grid_multiple_datazoom_index():
    line = Line("折线图示例", width=1200, height=700)
    line.add("最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"], mark_line=["average"])
    line.add("最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"], legend_top="50%",
             mark_line=["average"], is_datazoom_show=True,
             datazoom_xaxis_index=[0, 1])

    v1 = [[2320.26, 2320.26, 2287.3, 2362.94],
          [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58, 2440.38],
          [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例", title_top="50%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)], v1,
              is_datazoom_show=True)

    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.add(kline, grid_bottom="60%")
    grid.render()
Example #28
0
def plot(df):
	kl=df.copy()
	#计算指标
	macd = talib.MACD(np.array(kl['CLOSE']), fastperiod=12, slowperiod=26, signalperiod=9)
	boll = talib.BBANDS(np.array(kl['CLOSE']), timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
	#绘图
	page = Page(page_title='KBM')
	kline = Kline()
	kline.add('', list(kl.index), [list(kl[['OPEN', 'CLOSE', 'LOW', 'HIGH']].iloc[i,].values) for i in range(len(kl))],is_datazoom_show=True, datazoom_xaxis_index=[0, 1], datazoom_type="both", is_xaxislabel_align=True,tooltip_axispointer_type="cross")
	line = Line(' ')
	line.add('upperband', list(kl.index), boll[0].tolist())
	line.add('middleband', list(kl.index), boll[1].tolist())
	line.add('lowerband', list(kl.index), boll[2].tolist())
	overlap1 = Overlap()
	overlap1.add(kline)
	overlap1.add(line)
	# line=Line(' ',width=1800,height=600)
	# line.add('中债国债到期收益率:10年',df.Times,df.Data[0], mark_line=0,is_datazoom_show=True,datazoom_xaxis_index=[0, 1],is_xaxislabel_align=True)
	line2 = Line(' ')
	line2.add('MACD', list(kl.index), macd[0].tolist())
	line2.add('MACDsignal',list(kl.index), macd[1].tolist(), is_datazoom_show=True,tooltip_axispointer_type="cross")
	bar = Bar(' ')
	macd2 = macd[2].tolist()
	macdhistUp = []
	macdhistDown = []
	for i in range(len(macd2)):
		if (macd2[i] > 0):
			macdhistUp.append(macd2[i])
			macdhistDown.append(0)
		else:
			macdhistUp.append(0)
			macdhistDown.append(macd2[i])
	# bar.add('MACDhist',klt,macd[2].tolist(),is_datazoom_show=True,legend_top='65%')
	bar.add('MACDhistUp', list(kl.index), macdhistUp, is_datazoom_show=True, legend_top='65%', label_color=['#ff0000'])
	bar.add('MACDhistDown', list(kl.index), macdhistDown, is_datazoom_show=True, legend_top='65%', label_color=['#00ff00'])
	overlap = Overlap()
	overlap.add(bar)
	overlap.add(line2)
	grid = Grid(width=1920, height=950)
	grid.add(overlap1, grid_bottom='40%')
	grid.add(overlap, grid_top='70%')
	# page.add(line)
	# page.add(overlap)
	page.add(grid)
	path=os.path.abspath('.')
	page.render(path+'\\plot\\KBM.html')
Example #29
0
def test_kline_user_define_markline_style():
    title = "K 线图-自定义标记点风格"
    kline = Kline(title)
    kline.add(
        "日K",
        DATE,
        data,
        mark_point=["min", "max"],
        mark_point_symbolsize=80,
        datazoom_orient="vertical",
        mark_line_valuedim=["lowest", "highest"],
    )
    kline.render()
    actual_content = get_default_rendering_file_content()
    assert "lowest" in actual_content
    assert "highest" in actual_content
    assert json.dumps(title) in actual_content
Example #30
0
def kplot(kdata, new=True, axes=None, 
          colorup='r', colordown='g', width=0.6, alpha=1.0):
    """绘制K线图
    
    :param KData kdata: K线数据
    :param bool new:    是否在新窗口中显示,只在没有指定axes时生效
    :param axes:        指定的坐标轴
    :param colorup:     the color of the rectangle where close >= open
    :param colordown:   the color of the rectangle where close < open
    :param width:       fraction of a day for the rectangle width
    :param alpha:       the rectangle alpha level, 透明度(0.0~1.0) 1.0为不透明
    """
    if not kdata:
        print("kdata is None")
        return
    
    if axes is None:
        axes = create_figure() if new else gca()
        
    title = get_draw_title(kdata)
    last_record = kdata[-1]
    text = u'%s 开:%.2f 高:%.2f 低:%.2f 收:%.2f 涨幅:%.2f%%' % (
        last_record.datetime.date(), 
        last_record.openPrice, last_record.highPrice,
        last_record.lowPrice,  last_record.closePrice,
        100*(last_record.closePrice-kdata[-2].closePrice)/kdata[-2].closePrice)
    
    date_list = kdata.getDatetimeList()
    if kdata.getQuery().kType == KQuery.DAY:
        x_list = [d.date() for d in date_list]
    else:
        x_list = [d.datetime() for d in date_list]
        
    y_list = [[k.openPrice, k.closePrice, k.lowPrice, k.highPrice] for k in kdata] 

    style = gcf().get_style(axes)
    kline = Kline(title, text, title_pos='center', subtitle_color='#FF0000')
    kline.add(None, x_axis=x_list, y_axis=y_list,
              mark_line=["max"], mark_line_symbolsize=0, 
              mark_line_valuedim='highest',
              **style)
    axes.add(kline)
    
    gcf().set_xaxis(x_list)
    gcf().add_axis(axes)
    return gcf()
    def plot(self, code=None):
        """plot the market_data"""
        if code is None:
            path_name = '.' + os.sep + 'QA_' + self.type + \
                '_codepackage_' + self.if_fq + '.html'
            kline = Kline('CodePackage_' + self.if_fq + '_' + self.type,
                          width=1360, height=700, page_title='QUANTAXIS')

            data_splits = self.splits()

            for i_ in range(len(data_splits)):
                data = []
                axis = []
                for dates, row in data_splits[i_].data.iterrows():
                    open, high, low, close = row[1:5]
                    datas = [open, close, low, high]
                    axis.append(dates[0])
                    data.append(datas)

                kline.add(self.code[i_], axis, data, mark_point=[
                          "max", "min"], is_datazoom_show=True, datazoom_orient='horizontal')
            kline.render(path_name)
            webbrowser.open(path_name)
            QA_util_log_info(
                'The Pic has been saved to your path: %s' % path_name)
        else:
            data = []
            axis = []
            for dates, row in self.select_code(code).data.iterrows():
                open, high, low, close = row[1:5]
                datas = [open, close, low, high]
                axis.append(dates[0])
                data.append(datas)

            path_name = '.{}QA_{}_{}_{}.html'.format(
                os.sep, self.type, code, self.if_fq)
            kline = Kline('{}__{}__{}'.format(code, self.if_fq, self.type),
                          width=1360, height=700, page_title='QUANTAXIS')
            kline.add(code, axis, data, mark_point=[
                      "max", "min"], is_datazoom_show=True, datazoom_orient='horizontal')
            kline.render(path_name)
            webbrowser.open(path_name)
            QA_util_log_info(
                'The Pic has been saved to your path: {}'.format(path_name))
Example #32
0
def k():

    import talib
    import numpy as np
    import tushare as ts
    from pyecharts import Grid, Bar, Line, Kline, Overlap

    data = ts.get_k_data('399300',
                         index=True,
                         start='2017-01-01',
                         end='2017-06-31')
    ochl = data[['open', 'close', 'high', 'low']]
    ochl_tolist = [ochl.ix[i].tolist() for i in range(len(ochl))]

    sma_10 = talib.SMA(np.array(data['close']), 10)
    sma_30 = talib.SMA(np.array(data['close']), 30)

    kline = Kline()
    kline.add("日K", data['date'], ochl_tolist, is_datazoom_show=True)

    line = Line()
    line.add('10 日均线',
             data['date'],
             sma_10,
             is_fill=False,
             line_opacity=0.8,
             is_smooth=True)
    line.add('30 日均线',
             data['date'],
             sma_30,
             is_fill=False,
             line_opacity=0.8,
             is_smooth=True)

    bar = Bar()
    bar.add("成交量", data['date'], data['volume'], is_stack=True)

    overlap = Overlap()
    overlap.add(kline)
    overlap.add(line)
    #overlap.add(bar)

    return overlap.render_embed()
Example #33
0
def kline_plot(name, ktype=0):
    df = cal_hadata(name)  # 画K线图数据
    # date = df.index.strftime('%Y%m%d').tolist()
    date = df.trade_date.tolist()
    # date = df['trade_date'].values.dt.strftime('%Y.%m.%d').tolist
    # date = df.index.tolist()
    if ktype == 0:
        k_value = df[['open', 'close', 'low', 'high']].values
    else:
        k_value = df[['ha_open', 'ha_close', 'ha_low', 'ha_high']].values

    # 引入pyecharts画图使用的是0.5.11版本,新版命令需要重写
    from pyecharts import Kline, Line, Bar, Scatter, Overlap
    kline = Kline(name + '行情走势')
    kline.add('日K线图',
              date,
              k_value,
              is_datazoom_show=True,
              is_splitline_show=False)
    # 加入5、20日均线
    df['ma20'] = df.close.rolling(20).mean()
    df['ma5'] = df.close.rolling(5).mean()
    line = Line()
    v0 = df['ma5'].round(2).tolist()
    v = df['ma20'].round(2).tolist()
    line.add('5日均线', date, v0, is_symbol_show=False, line_width=2)
    line.add('20日均线', date, v, is_symbol_show=False, line_width=2)
    # 成交量
    bar = Bar()
    bar.add('成交量',
            date,
            df['vol'],
            tooltip_tragger='axis',
            is_legend_show=False,
            is_yaxis_show=False,
            yaxis_max=5 * max(df['vol']))
    overlap = Overlap()
    overlap.add(kline)
    overlap.add(line, )
    overlap.add(bar, yaxis_index=1, is_add_yaxis=True)
    # display(HTML(overlap._repr_html_()))
    # warnings.filterwarnings("ignore")
    return overlap
Example #34
0
 def __kline(self, **kwargs):
     overlap = Overlap()
     oclh = self.__df[['open', 'close', 'low', 'high']].values.tolist()
     kline = Kline(self.title)
     kline.add("",
               self.__date,
               oclh,
               is_datazoom_show=True,
               tooltip_tragger='axis',
               tooltip_axispointer_type='cross',
               datazoom_xaxis_index=self.xaxis,
               is_xaxis_show=False)
     # pyechars have no public options
     kline._option.get('yAxis')[0].update(scale=True,
                                          splitArea={"show": False})
     overlap.add(kline)
     if kwargs.get('MA') is not None:
         mas = kwargs.get('MA')
         overlap.add(self.__ma(*mas))
     return overlap
Example #35
0
def plot_datastruct(_quotation_base, code=None):
    if code is None:
        path_name = '.' + os.sep + 'QA_' + _quotation_base.type + \
            '_codepackage_' + _quotation_base.if_fq + '.html'
        kline = Kline('CodePackage_' + _quotation_base.if_fq + '_' + _quotation_base.type,
                      width=1360, height=700, page_title='QUANTAXIS')

        data_splits = _quotation_base.splits()

        for i_ in range(len(data_splits)):
            data = []
            axis = []
            for dates, row in data_splits[i_].data.iterrows():
                open, high, low, close = row[1:5]
                datas = [open, close, low, high]
                axis.append(dates[0])
                data.append(datas)

            kline.add(_quotation_base.code[i_], axis, data, mark_point=[
                      "max", "min"], is_datazoom_show=True, datazoom_orient='horizontal')
        kline.render(path_name)
        webbrowser.open(path_name)
        QA_util_log_info('The Pic has been saved to your path: %s' % path_name)
    else:
        data = []
        axis = []
        for dates, row in _quotation_base.select_code(code).data.iterrows():
            open, high, low, close = row[1:5]
            datas = [open, close, low, high]
            axis.append(dates[0])
            data.append(datas)

        path_name = '.' + os.sep + 'QA_' + _quotation_base.type + \
            '_' + code + '_' + _quotation_base.if_fq + '.html'
        kline = Kline(code + '__' + _quotation_base.if_fq + '__' + _quotation_base.type,
                      width=1360, height=700, page_title='QUANTAXIS')
        kline.add(code, axis, data, mark_point=[
                  "max", "min"], is_datazoom_show=True, datazoom_orient='horizontal')
        kline.render(path_name)
        webbrowser.open(path_name)
        QA_util_log_info('The Pic has been saved to your path: %s' % path_name)
def k_demo():
    v1 = [[2320.26, 2320.26, 2287.3,
           2362.94], [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58,
           2440.38], [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例")
    kline.add(
        "日K",
        ["2017/7/{}".format(i + 1) for i in range(31)],
        v1,
        is_datazoom_show=True,
    )
    return kline
Example #37
0
def test_kline_datazoom_horizontal():
    kline = Kline("K 线图示例 - dataZoom 水平布局")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              data,
              mark_point=["max"],
              is_datazoom_show=True)
    kline.render()
Example #38
0
def draw(code):
    import pandas as pd
    stock = pd.read_csv(code + '.csv',
                        usecols=[0, 1, 2, 3, 4, 5, 6],
                        encoding='gbk')
    stock.head()

    stock_new = stock.iloc[:180, :]
    stock_new_sorted = stock_new.sort_values('日期', ascending=True)
    stock_new_sorted.head()

    from pyecharts import Kline
    stock_code = stock_new_sorted['股票代码'][0]
    stock_name = stock_new_sorted['名称'][0]
    index = stock_new_sorted['日期']
    v = [[o, close, lowest, highest] for o, close, lowest, highest in zip(
        stock_new_sorted['开盘价'], stock_new_sorted['收盘价'],
        stock_new_sorted['最低价'], stock_new_sorted['最高价'])]
    kline = Kline()
    kline.add(stock_name + '(' + stock_code + ')' + '日K线图',
              index,
              v,
              mark_point=["max"],
              is_datazoom_show=True)
    kline.render()
Example #39
0
def graphpage(labels,mode_combo,startdate,enddate,optInterval,width1, height1):
    #optInterval='D/W/M' labels

    startdate = startdate.replace("/","-")#convert to tushare readable date
    enddate = enddate.replace("/","-")

    page = Page()

    for label in labels:  # generate numbers of graphs according to numbers of queries in treewidget
        label1 = re.split("-", label)
        overlap = Overlap()

        if label1[2]!="分笔" and label1[2]!="季度饼图": #"K线" "复权" "历史分钟"
            if mode_combo == "复权":
            #if optInterval == "qfq" or optInterval == "hfq":#复权
                array = ts.get_h_data(label1[1], start=startdate, end=enddate, autype="qfq")
                array = array.sort_index()
                time = array.index.format()  # 日期正是index
            elif mode_combo == "K线":
            #elif optInterval.isalnum() :#历史K线
                array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval)
                time = array['date'].tolist()  # array.date
            elif mode_combo == "历史分钟":
                array_bfr = ts.get_tick_data(label1[1], date=startdate)
                array_bfr.sort_values("time")
                a = startdate + " " + array_bfr["time"]
                array_bfr["time"] = a
                array_bfr["time"] = pd.to_datetime(a)
                array_bfr = array_bfr.set_index("time")
                if label1[2] != "Volume" and label1[2] != "Amount":
                    price_df = array_bfr["price"].resample(optInterval).ohlc()  # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl
                    price_df = price_df.dropna()
                    array = price_df
                    time = price_df.index.format()

                elif label1[2] == "Volume":
                    vols = array_bfr["volume"].resample(optInterval).sum()  #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare
                    vols = vols.dropna()
                    vol_df = pd.DataFrame(vols, columns=["volume"])
                    array = vol_df
                    time = vol_df.index.format()
                else:
                    amounts = array_bfr["amount"].resample(optInterval).sum()
                    amounts = amounts.dropna()
                    amount_df = pd.DataFrame(amounts, columns=["amount"])
                    array = amount_df
                    time = amount_df.index.format()

            #绘图方法

            if label1[2] == 'Kline':
                re_array = array[['open', 'close', 'high', 'low']]
                data_li = list(row.tolist() for index, row in re_array.iterrows())  # data_list = list(re_array.as_matrix())
                close = array['close'].tolist()
                kline = Kline(label1[0] + "-" + optInterval, width=width1*10/11, height = (height1*10/11) / len(labels))
                kline.add(label1[0], time, data_li, is_datazoom_show=True, datazoom_type="slider", yaxis_interval=1)
                overlap.add(kline)

                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(label1[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(label1[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(label1[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)

                page.add(overlap)
            else:#When label1[2]==open/close/volume
                if label1[2] == 'Open':
                    list_aft = array['open'].tolist()
                elif label1[2] == 'Close':
                    list_aft = close
                elif label1[2] == 'High':
                    list_aft = array['high'].tolist()
                elif label1[2] == 'Low':
                    list_aft = array['low'].tolist()
                elif label1[2] == 'Volume':#volume
                    list_aft = array['volume'].tolist()
                else:#amount
                    list_aft = array['amount'].tolist()

                line = Line(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
                line.add(label1[0] + "-" + label1[2], time, list_aft, is_datazoom_show=True, yaxis_max="dataMax",
                         yaxis_min="dataMin", datazoom_type="slider")
                overlap.add(line)
                page.add(overlap)


        elif label1[2]=="分笔":
            array = ts.get_tick_data(label1[1], date=startdate)
            array = array.sort_values("time")
            date = array["time"].tolist()
            amount = array["amount"].tolist()
            atype = array["type"].tolist()
            price = array["price"].tolist()
            flag = ["bar" for i in date]
            for idx, val in enumerate(atype):
                if val == "卖盘":
                    amount[idx] = -amount[idx]
                if val == "中性盘":
                    amount[idx] = 0

            returnarray = list(zip(date, amount, flag, price))

            form = [e[1] for e in returnarray]
            time = [d[0] for d in returnarray]

            bar = Bar(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            bar.add(label1[0] + "-" + label1[2], time, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax")
            overlap.add(bar)

            line = Line(label1[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            price = [e[3] for e in returnarray]
            line.add(label1[0] + "price", time, price, yaxis_min="dataMin", yaxis_max="dataMax", is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_type="value")
            overlap.add(line, yaxis_index=1, is_add_yaxis=True)
            page.add(overlap)
        elif label1[2]=="季度饼图":
            datestr = startdate.split("-")
            thisyear = datestr[0]
            df2 = ts.top10_holders(code=label1[1], gdtype="1")
            test = df2[1]["quarter"].tolist()
            df_ready = df2[1]
            idxlist = []
            for idx, val in enumerate(test):
                a = val.split("-")
                if a[0] == thisyear:
                    # print a[0],idx
                    idxlist.append(idx)
            thing = df_ready.loc[idxlist]
            thing = thing.sort_values(["quarter", "name"])
            # print a[0],id
            name = thing["name"].tolist()
            value = thing["hold"].tolist()
            quarter = thing["quarter"].tolist()
            namearray = [name[i:i + 10] for i in range(0, len(name), 10)]
            valuearray = [value[j:j + 10] for j in range(0, len(value), 10)]
            quarterarray = [quarter[k:k + 10] for k in range(0, len(quarter), 10)]

            flag = ["pie" for i in namearray]
            num = [len(value) for k in namearray]
            returnarray = list(zip(namearray, valuearray, quarterarray, flag, num))

            timeline = Timeline(is_auto_play=False, timeline_bottom=0)  # zip(namearray,valuearray,quarter,flag,num)
            namearray = [c[0] for c in returnarray]
            valuearray = [d[1] for d in returnarray]
            quarter = [e[2] for e in returnarray]
            num = returnarray[0][4]

            for x in range(0, int(num / 10)):
                list1 = valuearray[x]
                names = namearray[x]
                quarters = quarter[x][0]

                for idx, val in enumerate(list1):
                    list1[idx] = float(val)

                pie = Pie(label1[0] + "-" + "前十股东", width=width1 * 10 / 11, height=(height1 * 10 / 11))

                pie.add(label1[0] + "-" + "前十股东", names, list1, radius=[30, 55], is_legend_show=False,
                        is_label_show=True, label_formatter="{b}: {c}\n{d}%")
                timeline.add(pie, quarters)
                # namearray = [y for y in namearray[x]]
            timeline.render()

    page.render()
Example #40
0
def test_kline_datazoom_horizontal():
    kline = Kline("K 线图-dataZoom 水平布局")
    kline.add("日K", DATE, data,
              mark_point=["max"], is_datazoom_show=True)
    kline.render()
Example #41
0
def test_kline_default():
    kline = Kline("K 线图-默认示例")
    kline.add("日K", DATE, data)
    kline.render()
Example #42
0
def test_grid():

    # grid_0
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=720, is_grid=True)
    bar.add("商家A", attr, v1, is_stack=True, grid_bottom="60%")
    bar.add("商家B", attr, v2, is_stack=True, grid_bottom="60%")
    line = Line("折线图示例", title_top="50%")
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温", attr, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"])
    line.add("最低气温", attr, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"],
             mark_line=["average"], legend_top="50%")
    bar.grid(line.get_series(), grid_top="60%")
    bar.show_config()
    bar.render()

    # grid_1
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    scatter = Scatter(width=1200, is_grid=True)
    scatter.add("散点图示例", v1, v2, grid_left="60%", legend_pos="70%")
    es = EffectScatter()
    es.add("动态散点图示例", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0],
           effect_scale=6, legend_pos="20%")
    scatter.grid(es.get_series(), grid_right="60%")
    scatter.show_config()
    scatter.render()

    # grid_2
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=720, width=1200, title_pos="65%", is_grid=True)
    bar.add("商家A", attr, v1, is_stack=True, grid_bottom="60%", grid_left="60%")
    bar.add("商家B", attr, v2, is_stack=True, grid_bottom="60%", grid_left="60%", legend_pos="80%")
    line = Line("折线图示例")
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温", attr, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"])
    line.add("最低气温", attr, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"],
             mark_line=["average"], legend_pos="20%")
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    scatter = Scatter("散点图示例", title_top="50%", title_pos="65%")
    scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%")
    es = EffectScatter("动态散点图示例", title_top="50%")
    es.add("es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0], effect_scale=6,
           legend_top="50%", legend_pos="20%")
    bar.grid(line.get_series(), grid_bottom="60%", grid_right="60%")
    bar.grid(scatter.get_series(), grid_top="60%", grid_left="60%")
    bar.grid(es.get_series(), grid_top="60%", grid_right="60%")
    bar.show_config()
    bar.render()

    # grid_3
    line = Line("折线图示例", width=1200, is_grid=True)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温", attr, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"],
             mark_line=["average"], grid_right="65%")
    line.add("最低气温", attr, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"],
             mark_line=["average"], legend_pos="20%")
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图示例", title_pos="45%")
    pie.add("", attr, v1, radius=[30, 55], legend_pos="65%", legend_orient='vertical')
    line.grid(pie.get_series(), grid_left="60%")
    line.show_config()
    line.render()

    # grid_4
    line = Line("折线图示例", width=1200, is_grid=True)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温", attr, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"],
             mark_line=["average"], grid_right="60%")
    line.add("最低气温", attr, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"],
             mark_line=["average"], legend_pos="20%", grid_right="60%")
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    value = [20, 40, 60, 80, 100, 120]
    v1 = [[2320.26, 2320.26, 2287.3, 2362.94],
          [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58, 2440.38],
          [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例", title_pos="60%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)], v1, legend_pos="80%")
    line.grid(kline.get_series(), grid_left="55%")
    line.show_config()
    line.render()

    # grid_5
    import random
    x_axis = ["12a", "1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a",
              "12p", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p"]
    y_aixs = ["Saturday", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday", "Sunday"]
    data = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]
    heatmap = HeatMap("热力图示例", height=700, is_grid=True)
    heatmap.add("热力图直角坐标系", x_axis, y_aixs, data, is_visualmap=True, visual_top="45%",
                visual_text_color="#000", visual_orient='horizontal', grid_bottom="60%")
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", title_top="52%")
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True, legend_top="50%")
    heatmap.grid(bar.get_series(), grid_top="60%")
    heatmap.show_config()
    heatmap.render()
Example #43
0
def test_kline():

    # kline_0
    v1 = [[2320.26, 2320.26, 2287.3, 2362.94],
          [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58, 2440.38],
          [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)], v1)
    kline.show_config()
    kline.render()

    # kline_1
    kline = Kline("K 线图示例")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)], v1, mark_point=["max"], is_datazoom_show=True)
    kline.show_config()
    kline.render()

    # kline_2
    kline = Kline("K 线图示例")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)], v1, mark_point=["max"],
              is_datazoom_show=True, datazoom_orient='vertical')
    kline.show_config()
    kline.render()
Example #44
0
def test_more():
    page = Page()

    # line
    line = Line("折线图示例")
    line.add(
        "最高气温",
        WEEK,
        [11, 11, 15, 13, 12, 13, 10],
        mark_point=["max", "min"],
        mark_line=["average"],
    )
    line.add(
        "最低气温",
        WEEK,
        [1, -2, 2, 5, 3, 2, 0],
        mark_point=["max", "min"],
        mark_line=["average"],
    )

    # pie
    v1 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图-圆环图示例", title_pos="center")
    pie.add(
        "",
        CLOTHES,
        v1,
        radius=[40, 75],
        label_text_color=None,
        is_label_show=True,
        legend_orient="vertical",
        legend_pos="left",
    )

    page.add([line, pie])

    # kline
    v1 = [
        [2320.26, 2320.26, 2287.3, 2362.94],
        [2300, 2291.3, 2288.26, 2308.38],
        [2295.35, 2346.5, 2295.35, 2345.92],
        [2347.22, 2358.98, 2337.35, 2363.8],
        [2360.75, 2382.48, 2347.89, 2383.76],
        [2383.43, 2385.42, 2371.23, 2391.82],
        [2377.41, 2419.02, 2369.57, 2421.15],
        [2425.92, 2428.15, 2417.58, 2440.38],
        [2411, 2433.13, 2403.3, 2437.42],
        [2432.68, 2334.48, 2427.7, 2441.73],
        [2430.69, 2418.53, 2394.22, 2433.89],
        [2416.62, 2432.4, 2414.4, 2443.03],
        [2441.91, 2421.56, 2418.43, 2444.8],
        [2420.26, 2382.91, 2373.53, 2427.07],
        [2383.49, 2397.18, 2370.61, 2397.94],
        [2378.82, 2325.95, 2309.17, 2378.82],
        [2322.94, 2314.16, 2308.76, 2330.88],
        [2320.62, 2325.82, 2315.01, 2338.78],
        [2313.74, 2293.34, 2289.89, 2340.71],
        [2297.77, 2313.22, 2292.03, 2324.63],
        [2322.32, 2365.59, 2308.92, 2366.16],
        [2364.54, 2359.51, 2330.86, 2369.65],
        [2332.08, 2273.4, 2259.25, 2333.54],
        [2274.81, 2326.31, 2270.1, 2328.14],
        [2333.61, 2347.18, 2321.6, 2351.44],
        [2340.44, 2324.29, 2304.27, 2352.02],
        [2326.42, 2318.61, 2314.59, 2333.67],
        [2314.68, 2310.59, 2296.58, 2320.96],
        [2309.16, 2286.6, 2264.83, 2333.29],
        [2282.17, 2263.97, 2253.25, 2286.33],
        [2255.77, 2270.28, 2253.31, 2276.22],
    ]
    kline = Kline("K 线图示例")
    kline.add(
        "日K",
        ["2017/7/{}".format(i + 1) for i in range(31)],
        v1,
        is_datazoom_show=True,
    )
    page.add(kline)

    # radar
    schema = [
        ("销售", 6500),
        ("管理", 16000),
        ("信息技术", 30000),
        ("客服", 38000),
        ("研发", 52000),
        ("市场", 25000),
    ]
    v1 = [[4300, 10000, 28000, 35000, 50000, 19000]]
    v2 = [[5000, 14000, 28000, 31000, 42000, 21000]]
    radar = Radar("雷达图示例")
    radar.config(schema)
    radar.add("预算分配", v1, is_splitline=True, is_axisline_show=True)
    radar.add(
        "实际开销",
        v2,
        label_color=["#4e79a7"],
        is_area_show=False,
        legend_selectedmode="single",
    )
    page.add(radar)

    # scatter3d
    import random

    data = [
        [
            random.randint(0, 100),
            random.randint(0, 100),
            random.randint(0, 100),
        ]
        for _ in range(80)
    ]
    scatter3D = Scatter3D("3D 散点图示例", width=1200, height=600)
    scatter3D.add("", data, is_visualmap=True, visual_range_color=RANGE_COLOR)
    page.add(scatter3D)

    # wordcloud
    name = [
        "Sam S Club",
        "Macys",
        "Amy Schumer",
        "Jurassic World",
        "Charter Communications",
        "Chick Fil A",
        "Planet Fitness",
        "Pitch Perfect",
        "Express",
        "Home",
        "Johnny Depp",
        "Lena Dunham",
        "Lewis Hamilton",
        "KXAN",
        "Mary Ellen Mark",
        "Farrah Abraham",
        "Rita Ora",
        "Serena Williams",
        "NCAA baseball tournament",
        "Point Break",
    ]
    value = [
        10000,
        6181,
        4386,
        4055,
        2467,
        2244,
        1898,
        1484,
        1112,
        965,
        847,
        582,
        555,
        550,
        462,
        366,
        360,
        282,
        273,
        265,
    ]
    wordcloud = WordCloud(width=1300, height=620)
    wordcloud.add("", name, value, word_size_range=[30, 100], rotate_step=66)
    page.add(wordcloud)

    # liquid
    liquid = Liquid("水球图示例")
    liquid.add("Liquid", [0.6])
    page.add(liquid)
    assert len(page) == 7
    assert isinstance(page[0], Line)
    assert (
        ("echarts" in page.js_dependencies)
        or ("echarts.min" in page.js_dependencies)
    )
    page.render()
Example #45
0
def graphpage(items,startdate,enddate,option,width1, height1): #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
    page = Page()
    for i in items:#generate numbers of graphs according to numbers of queries in treewidget
        j = re.split("-",i)
        if len(j)==3:
            a = generateline(j[1],j[2],startdate,enddate,option)#stock number, Type, startdate, enddate, 30 or 15 or days
            if a is None:
                continue
            time = [d[0] for d in a]#get time from returned dictionary
            if j[2]!="Kline":

                if len(a[0])==4 and a[0][2]=="bar": #for 分笔data
                    overlap = Overlap()
                    form = [e[1] for e in a]
                    bar = Bar(j[0] + "-" + j[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                    bar.add(j[0] + "-" + j[2], time, form, yaxis_min = "dataMin",yaxis_max = "dataMax",is_datazoom_show = True, datazoom_type = "slider")
                    overlap.add(bar)

                    line = Line(j[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                    price = [e[3] for e in a]
                    line.add(j[0] + "price", time, price, yaxis_min = "dataMin",yaxis_max = "dataMax", is_datazoom_show = True, datazoom_type = "slider",
                            yaxis_type="value")
                    overlap.add(line,yaxis_index=1, is_add_yaxis=True)

                    page.add(overlap)

                if len(a[0])==5 and a[0][3]=="pie":
                    overlap = Overlap()
                    timeline = Timeline(is_auto_play=False, timeline_bottom=0) #zip(namearray,valuearray,quarter,flag,num)
                    namearray = [c[0] for c in a]
                    valuearray = [d[1] for d in a]
                    quarter = [e[2] for e in a]
                    num = a[0][4]

                    for x in range(0, num / 10):
                        list1 = valuearray[x]
                        names = namearray[x]
                        quarters = quarter[x][0]

                        for idx, val in enumerate(list1):
                            list1[idx] = float(val)

                        pie = Pie(j[0]+"-"+"前十股东".decode("utf-8"),width=width1 * 10 / 11, height=(height1 * 10 / 11))

                        pie.add(j[0]+"-"+"前十股东".decode("utf-8"), names, list1, radius=[30, 55], is_legend_show=False,
                                is_label_show=True, label_formatter = "{b}: {c}\n{d}%")
                        # print list
                        # print names
                        # print quarterarray

                        timeline.add(pie, quarters)
                        # namearray = [y for y in namearray[x]]
                    timeline.render()

                    return


                    #need more statement
                else:
                    form = [e[1] for e in a]#for not分笔 data
                    line = Line(j[0] + "-" + j[2], width=width1*10/11, height=(height1*10/11)/len(items))
                    line.add(j[0] + "-" + j[2], time, form, is_datazoom_show=True, datazoom_type="slider",yaxis_min="dataMin",yaxis_max="dataMax")
                    page.add(line)
            else:
                overlap = Overlap()#for k线
                close = zip(*a)[2]
                candle = [[x[1], x[2], x[3], x[4]] for x in a]
                candlestick = Kline(j[0] + "-" + j[2], width=width1*10/11, height = (height1*10/11) / len(items))
                candlestick.add(j[0], time, candle, is_datazoom_show=True, datazoom_type="slider",yaxis_interval = 1)
                overlap.add(candlestick)
                if len(close)>10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(j[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close)>20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(j[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close)>30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(j[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)
                page.add(overlap)
        else:
            for k in range(1, len(j)/3):#if graphs are combined
                j[3*k-1] = re.sub("\n&","",j[3*k-1])
            sizearray=[]
            #if j[1] != "Candlestick"
            layout = Overlap()
            for i in xrange(0, len(j),3):
                array = j[i:i +3]
                b = generateline(array[1],array[2],startdate,enddate,option)
                if b is None:
                    continue
                btime = [d[0] for d in b]
                if array[2] != "Kline":

                    if len(b[0])==4 and b[0][2]=="bar":
                        form = [e[1] for e in b]
                        bar = Bar(array[0] + "-" + array[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                        bar.add(array[0] + "-" + array[2], btime, form, is_datazoom_show=True, datazoom_type="slider",
                                yaxis_min="dataMin", yaxis_max="dataMax")
                        layout.add(bar)
                        line = Line(array[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items))
                        price = [e[3] for e in b]
                        line.add(array[0] + "price", btime, price, is_datazoom_show=True, datazoom_type="slider",
                                     yaxis_min="dataMin", yaxis_type="value")
                        layout.add(line, yaxis_index=1, is_add_yaxis=True)




                    else:
                        line = Line(array[0] + "-" + array[2],width=width1*10/11, height=(height1*10/11) / len(items))
                        line.add(array[0]+"-"+array[2], btime, b, is_datazoom_show=True, yaxis_max = "dataMax", yaxis_min = "dataMin",datazoom_type="slider")
                        layout.add(line)
                else:
                    candle = [[x[1], x[2], x[3], x[4]] for x in b]
                    candlestick = Kline(array[0] + "-" + array[1], width=width1*10/11,
                                        height=(height1*10/11) / len(items))
                    candlestick.add(array[0], btime, candle, is_datazoom_show=True, datazoom_type=["slider"])

                    #if i == 0:
                    close = zip(*b)[2]
                    if len(close)>10:
                        ma10 = calculateMa(close, 10)
                        line4 = Line(title_color="#C0C0C0")
                        line4.add(array[0] + "-" + "MA10", btime, ma10)
                        layout.add(line4)
                    if len(close)>20:
                        ma20 = calculateMa(close, 20)
                        line5 = Line(title_color="#C0C0C0")
                        line5.add(array[0] + "-" + "MA20", btime, ma20)
                        layout.add(line5)
                    if len(close)>30:
                        ma30 = calculateMa(close, 30)
                        line6 = Line(title_color="#C0C0C0")
                        line6.add(array[0] + "-" + "MA30", btime, ma30)
                        layout.add(line6)
                    layout.add(candlestick)
            page.add(layout)
    page.render()