Beispiel #1
0
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Line, Kline, Scatter

kline1 = Kline()
kline2 = Kline()

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'))

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

df = pd.read_csv('F:/Stock/kline.csv')

str1 = str(df.iloc[0, 1])
str2 = str(df.iloc[1, 1])

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

df1 = pd.read_csv('F:/Stock/Data_Day/' + df.iloc[0, 1] + ".csv")
df1 = df1.sort_index(ascending=False).reset_index(drop=True)
date1 = df1.xs('Date Time', axis=1).tolist()
data1 = []
vol1 = []
Beispiel #2
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)