Esempio n. 1
0
def abc():
    ts_code='002713.SZ'
    csv_file = '{0}.csv'.format(ts_code)
    render_html = '{0}.html'.format(ts_code)
    end_date = datetime.now().strftime('%Y%m%d')

    df = None
    if not os.path.exists(csv_file):
        MY_TOKEN = '190040a13eb5b092ca76fa003f58d693c9121e0fc621f6d2ad221468'
        ts.set_token(MY_TOKEN)
        pro = ts.pro_api()
        df1 = pro.daily(ts_code=ts_code, start_date='20140101', end_date=end_date)
        df = df1.sort_values(by=['trade_date'])
        df.reset_index(level=0, inplace=True)
        df.drop(['index'], axis=1, inplace=True)
        print(df)
        df.to_csv(csv_file)

    if not df is None:
        df = pd.read_csv(csv_file)

    date = df.trade_date.tolist()
    data = []
    for idx in df.index :
        row=[df.iloc[idx]['open'],df.iloc[idx]['close'],df.iloc[idx]['low'],df.iloc[idx]['high']]
        data.append(row)
    WIDTH = 1100
    HEIGHT = 550
    chart_init = {
        "width": WIDTH,
        "height": HEIGHT,
    }
    kline = Kline()
    kline.add_xaxis(date).add_yaxis('日K', data)
    kline.set_global_opts(
        xaxis_opts=opts.AxisOpts(is_scale=True),
        yaxis_opts=opts.AxisOpts(  
            is_scale=True,  
            splitarea_opts=opts.SplitAreaOpts(  
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)  
            ),
        ),
        datazoom_opts=[opts.DataZoomOpts()],
        # title_opts=opts.TitleOpts(title='日K线图:{0}'.format(ts_code)),
    )
    # kline.add_yaxis(
    #     "日K",
    #     date,
    #     data,
    #     mark_point=["max"],
    #     is_datazoom_show=True,
    # )
    # 生成一个名为 render.html 的文件

    kline.render(render_html)
    kline.render_notebook()
    # kline.render('a.html')
    # 在jupyter中使用,只需要使用xxx.render_notebook() 方法即可在Jupyter中显示图
Esempio n. 2
0
    def draw_Kline(self):
        """
        画股票的K线图,需要传入四个数据
        分别是["open", "close", "high", "low"]
        :return: 画出图像
        """
        Df_s1 = Read_One_Stock(self.SC).select_col("open", "high", "low",
                                                   "close", "vol", "amount")
        length = Df_s1.shape[0]
        Df_s1.sort_values("trade_date", inplace=True)
        Df_s1.index = list(range(length))
        price = np.array(Df_s1[["open", "close", "high", "low"]]).tolist()
        date = np.array(Df_s1["trade_date"], dtype=np.string_).tolist()
        ma_value_5 = calculate_ma_n(list(Df_s1['close']), 5)
        ma_value_10 = calculate_ma_n(list(Df_s1['close']), 10)
        ma_value = np.array([ma_value_5, ma_value_10]).tolist()

        kline = Kline()
        kline.set_global_opts(
            xaxis_opts=opts.AxisOpts(is_scale=True),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True,
                    areastyle_opts=opts.AreaStyleOpts(opacity=1)),
            ),
            datazoom_opts=[opts.DataZoomOpts()],
            title_opts=opts.TitleOpts(title="K-Line of {}".format(self.SC)),
        )
        kline.add_xaxis(date)
        kline.add_yaxis('K-Line', price)

        line = Line()
        line.add_xaxis(date)
        line.add_yaxis(series_name="ma5",
                       y_axis=ma_value[0],
                       label_opts=opts.LabelOpts(is_show=False))
        line.add_yaxis(series_name="ma10",
                       y_axis=ma_value[1],
                       label_opts=opts.LabelOpts(is_show=False))
        line.set_global_opts(
            xaxis_opts=opts.AxisOpts(is_scale=True),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True,
                    areastyle_opts=opts.AreaStyleOpts(opacity=1)),
            ),
            datazoom_opts=[opts.DataZoomOpts()],
            title_opts=opts.TitleOpts(title=""))

        kline.overlap(line)
        kline.render("./Plots/{} Candle Plot.html".format(self.SC))
def _stock_():
    stock_code = '000001'
    freq = 'day'
    # stock_df = download_index_bars(stock_code, freq=freq)
    # print(stock_df)

    csv = os.path.join(ct.DATA_DIR, 'index_%s_%s.csv' % (stock_code, freq))
    stock_df = pd.read_csv(csv)
    html = os.path.join(ct.HTML_DIR, 'index_%s_%s.html' % (stock_code, freq))
    stock_df.to_csv(csv, index=False)
    
    from pyecharts import options as opts
    from pyecharts.charts import Kline

    WIDTH = 1100
    HEIGHT = 550
    chart_init = {
        "width": WIDTH,
        "height": HEIGHT,
    }
    kline = Kline()
    date = stock_df.datetime.tolist()
    data = []
    for index, row in stock_df.iterrows():
        item = [row.open, row.close, row.low, row.high]
        data.append(item)
    print(data)

    kline.add_xaxis(date).add_yaxis('日K', data)
    kline.set_global_opts(
        xaxis_opts=opts.AxisOpts(is_scale=True),
        yaxis_opts=opts.AxisOpts(  
            is_scale=True,  
            splitarea_opts=opts.SplitAreaOpts(  
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)  
            ),
        ),
        datazoom_opts=[opts.DataZoomOpts()],
        # title_opts=opts.TitleOpts(title='日K线图:{0}'.format(ts_code)),
    )
    # kline.add_yaxis(
    #     "日K",
    #     date,
    #     data,
    #     mark_point=["max"],
    #     is_datazoom_show=True,
    # )
    # 生成一个名为 render.html 的文件
    kline.render(html)
Esempio n. 4
0
    def drawLine(self, data, stockcode):
        print(data)
        # stockcode=self.get_stockcode()
        stockname = self.get_stockname(stockcode)
        kldata = data.values[:, [1, 2, 3, 4, 5]]  # 分别对应日期,开盘价、收盘价、最低价和最高价
        print(kldata)
        kdate = kldata[0]
        kobj = Kline().add_xaxis(kdate)
        kobj.add_yaxis(stockname + "-日K线图", kldata.tolist())
        kobj.set_global_opts(yaxis_opts=opts.AxisOpts(is_scale=True),
                             xaxis_opts=opts.AxisOpts(is_scale=True),
                             title_opts=opts.TitleOpts(title=""))

        renderfile = stockcode + 'render.html'
        kobj.render(renderfile)

        br.open(renderfile)
Esempio n. 5
0
        df1.iloc[idx1]['Open'], df1.iloc[idx1]['Close'], df1.iloc[idx1]['Low'],
        df1.iloc[idx1]['High']
    ]
    row2 = df1.iloc[idx1]['Volume']
    data1.append(row1)
    vol1.append(row2)
kline1.add_xaxis(date1)
kline1.add_yaxis(str1, data1)

#-------------------------------------------------------------------------------------------------------------------

df2 = pd.read_csv('F:/Stock/Data_Day/' + df.iloc[1, 1] + ".csv")
df2 = df2.sort_index(ascending=False).reset_index(drop=True)
date2 = df2.xs('Date Time', axis=1).tolist()
data2 = []
vol2 = []
for idx2 in df2.index:
    row3 = [
        df2.iloc[idx2]['Open'], df2.iloc[idx2]['Close'], df2.iloc[idx2]['Low'],
        df2.iloc[idx2]['High']
    ]
    row4 = df2.iloc[idx2]['Volume']
    data2.append(row3)
    vol2.append(row4)
print(date2)
kline2.add_xaxis(date2)
kline2.add_yaxis(str2, data2)
kline1.overlap(kline2)

kline1.render(path='F:\\Stock/Kline.html')
Esempio n. 6
0
y_data = hist_data[['open', 'close', 'low', 'high']].values.tolist()
ma5 = hist_data['ma5']
ma10 = hist_data['ma10']

x.reverse()
y_data.reverse()
print(x)

x1 = hist_data.index.tolist()[:20]
y1 = hist_data['open'].iloc[:20]
y2 = hist_data['close'].iloc[:20]

#Line-折线图
line = Line().add_xaxis(x1).add_yaxis('开盘价', y1,
                                      is_smooth=True).add_yaxis('收盘价',
                                                                range(20),
                                                                is_smooth=True)
line.render('/Users/mac/Desktop/fig.html')

#K-line图

#K_line = Kline().add_xaxis(x).add_yaxis('美的集团-000333',y_data).set_global_opts(datazoom_opts=[opts.DataZoomOpts(type_="inside")])
#K_line.render('/Users/mac/Desktop/fig1.html')
K_line = Kline().add_xaxis(x).add_yaxis(
    '美的集团-000333',
    y_data,
    markline_opts=opts.MarkLineOpts(
        [opts.MarkLineItem(type_='max', value_dim='close')]),
).set_global_opts(datazoom_opts=[opts.DataZoomOpts(type_="inside")])
K_line.render('/Users/mac/Desktop/fig1.html')
Esempio n. 7
0
from pyecharts.charts import Line, Kline, Bar

import pandas as pd
from datetime import datetime, timedelta

fn = 'bar/min1_SR001.csv'

df1 = pd.read_csv(fn)
df1['datetime'] = df1['date'] + ' ' + df1['time']
print(df1.head())
dt_list = list(df1['datetime'])
#print(dt_list)
k_plot_value = df1.apply(
    lambda record:
    [record['open'], record['close'], record['low'], record['high']],
    axis=1).tolist()
#print(k_plot_value)

kline = Kline(init_opts=opts.InitOpts(width='1500px'))
kline.add_xaxis(list(df1['datetime']))
kline.add_yaxis('日K', k_plot_value)
kline.set_global_opts(
    title_opts=opts.TitleOpts(title='Kline-基本示例'),
    datazoom_opts=[opts.DataZoomOpts()],
)
#xaxis_opts=opts.AxisOpts(type_='time'))
kline.render()

# if __name__ == '__main__':
#     pass
Esempio n. 8
0
from nature import get_dss

fn = get_dss() + 'backtest/fut/al/' + 'day_al01.csv'

df1 = pd.read_csv(fn)
df1['datetime'] = df1['date'] + ' ' + df1['time']
print(df1.head())
dt_list = list(df1['datetime'])
#print(dt_list)
k_plot_value = df1.apply(
    lambda record:
    [record['open'], record['close'], record['low'], record['high']],
    axis=1).tolist()
#print(k_plot_value)

kline = Kline(init_opts=opts.InitOpts(width='1500px', height='700px'))
kline.add_xaxis(list(df1['datetime']))
kline.add_yaxis('日K', k_plot_value)
kline.set_global_opts(
    title_opts=opts.TitleOpts(title='Kline-基本示例'),
    datazoom_opts=[opts.DataZoomOpts()],
)
#xaxis_opts=opts.AxisOpts(type_='time'))

fn = get_dss() + 'backtest/render/bar1.html'
kline.render(fn)

# if __name__ == '__main__':
#     pass
Esempio n. 9
0
def run_strategy(smaPeriod):
    df_new = pd.DataFrame(columns=('shares_ID', 'total number of trades',
                                   'Profit times number of trades',
                                   'Profit Percentage',
                                   'Final portfolio value'))
    for (root, dirs, files) in os.walk("E:/Stock/Data_Day"):
        z = 0
        for x in range(len(files)):
            z = z + 1
            #K线图
            df = pd.read_csv("E:/Stock/Data_Day/" + files[x])
            df = df.sort_index(ascending=False).reset_index(drop=True)
            print("进度:", z / len(files) * 100, "%")
            date = df.xs('Date Time', axis=1).tolist()
            data = []
            vol = []
            for idx in df.index:
                row1 = [
                    df.iloc[idx]['Open'], df.iloc[idx]['Close'],
                    df.iloc[idx]['Low'], df.iloc[idx]['High']
                ]
                row2 = df.iloc[idx]['Volume']
                data.append(row1)
                vol.append(row2)
            kline1 = Kline()
            line1 = Line()
            line2 = Line()
            line3 = Line()
            scatter1 = Scatter()
            scatter2 = Scatter()

            kline1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                   yaxis_opts=opts.AxisOpts(is_scale=True),
                                   datazoom_opts=[opts.DataZoomOpts()])
            kline1.extend_axis(
                yaxis=opts.AxisOpts(type_='value', position='right'))
            kline1.extend_axis(
                yaxis=opts.AxisOpts(type_='value', position='right'))

            # 价格均线
            line1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                  yaxis_opts=opts.AxisOpts(is_scale=True),
                                  datazoom_opts=[opts.DataZoomOpts()])
            # 成交量
            line2.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                  yaxis_opts=opts.AxisOpts(is_scale=True),
                                  datazoom_opts=[opts.DataZoomOpts()])
            #资金量
            line3.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                  yaxis_opts=opts.AxisOpts(is_scale=True),
                                  datazoom_opts=[opts.DataZoomOpts()])
            #买入点
            scatter1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                     yaxis_opts=opts.AxisOpts(is_scale=True),
                                     datazoom_opts=[opts.DataZoomOpts()])
            #卖出点
            scatter2.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                                     yaxis_opts=opts.AxisOpts(is_scale=True),
                                     datazoom_opts=[opts.DataZoomOpts()])

            kline1.add_xaxis(date)
            kline1.add_yaxis(files[x], data)
            line2.add_xaxis(date)
            line2.add_yaxis("vol",
                            vol,
                            yaxis_index=1,
                            label_opts=opts.LabelOpts(is_show=False))

            feed = GenericBarFeed(Frequency.DAY, None, None)
            feed.addBarsFromCSV("fd", "E:/Stock/Data_Day/" + files[x])
            global myStrategy
            myStrategy = MyStrategy(feed, "fd", smaPeriod)
            trade_situation = trades.Trades()
            myStrategy.attachAnalyzer(trade_situation)
            plt = plotter.StrategyPlotter(myStrategy)
            # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
            plt.getInstrumentSubplot("test").addDataSeries(
                "SMA", myStrategy.getSMA())
            # Plot the simple returns on each bar.
            # plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
            myStrategy.run()
            scatter1.add_xaxis(myStrategy.Buyday)
            scatter1.add_yaxis("Buy", myStrategy.Buyprice)
            scatter2.add_xaxis(myStrategy.Sellday)
            scatter2.add_yaxis("Sell", myStrategy.Sellprice)
            line1.add_xaxis(myStrategy.Barday)
            line1.add_yaxis("Price_SMA",
                            myStrategy.Sma_price,
                            label_opts=opts.LabelOpts(is_show=False))
            line3.add_xaxis(date)
            line3.add_yaxis("money",
                            myStrategy.money,
                            yaxis_index=2,
                            label_opts=opts.LabelOpts(is_show=False))
            plt.savePlot("E:/Stock/html_png_Total_day/" + files[x] + ".png")
            print(files[x] + " Final portfolio value:$%.2f" %
                  myStrategy.getBroker().getEquity())
            print("total number of trades", trade_situation.getCount())
            print("Profit times number of trades ",
                  trade_situation.getProfitableCount())
            if trade_situation.getCount() > 0:
                Percentage = trade_situation.getProfitableCount(
                ) / trade_situation.getCount()
                print("百分比", Percentage)
            else:
                Percentage = 0
                print("百分比", 0)
            df1 = pd.DataFrame({
                "shares_ID": [files[x]],
                'total number of trades': [trade_situation.getCount()],
                'Profit times number of trades':
                trade_situation.getProfitableCount(),
                'Profit Percentage':
                Percentage,
                'Final portfolio value': [myStrategy.getBroker().getEquity()]
            })
            kline1.overlap(scatter1)
            kline1.overlap(scatter2)
            kline1.overlap(line1)
            kline1.overlap(line2)
            kline1.overlap(line3)
            kline1.render(path='E:\\Stock/html_png_Total_day/' + files[x] +
                          '.html')
            df_new = pd.concat([df1, df_new], ignore_index=True)
    df_new.to_csv("E:/Stock/html_png_Total_day/Total_Min.csv", index=False)