Exemplo n.º 1
0
 def __init__(self, dbinfo=ct.DB_INFO, redis_host=None):
     self.logger = getLogger(__name__)
     self.crawler = get_tushare_client()
     self.dbname = self.get_dbname()
     self.redis = create_redis_obj(
     ) if redis_host is None else create_redis_obj(host=redis_host)
     self.mysql_client = CMySQL(dbinfo, self.dbname, iredis=self.redis)
     if not self.mysql_client.create_db(self.dbname):
         raise Exception("init margin database failed")
Exemplo n.º 2
0
def main(mode = ct.PAPER_TRADING, start_date = '20170815', end_date = '20171113'):
    if mode == ct.PAPER_TRADING:
        cash = 100000
        beta = 9.49
        mean = -0.282
        std  = 34.73
        feed = dataFramefeed.Feed()
        instruments = ['300296', '300613']
        fpath       = '/Users/hellobiek/Documents/workspace/python/quant/smart_deal_tool/configure/tushare.json' 
        ts_client   = get_tushare_client(fpath)
        for code in instruments:
            df = ts.pro_bar(pro_api = ts_client, ts_code = add_suffix(code), adj = 'qfq', start_date = start_date, end_date = end_date)
            df = df.rename(columns = {"ts_code": "code", "trade_date": "date", "vol": "volume", "pct_change": "pchange"})
            df['date'] = df.date.apply(lambda x: time.strftime('%Y-%m-%d', time.strptime(x, "%Y%m%d")))
            df = df.set_index("date")
            feed.addBarsFromDataFrame(code, df)

        # broker setting
        # broker commission类设置
        broker_commission = broker.backtesting.TradePercentage(0.002)
        # fill strategy设置
        fill_stra = broker.fillstrategy.DefaultStrategy(volumeLimit = 1.0)
        sli_stra  = broker.slippage.NoSlippage()
        fill_stra.setSlippageModel(sli_stra)
        # 完善broker类
        brk = broker.backtesting.Broker(cash, feed, broker_commission)
        brk.setFillStrategy(fill_stra)

    pStrategy = PairTradingStrategy(feed, instruments, brk, beta, mean, std, cash)

    returnsAnalyzer = sreturn.Returns()
    pStrategy.attachAnalyzer(returnsAnalyzer)

    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    pStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    drawDownAnalyzer = drawdown.DrawDown()
    pStrategy.attachAnalyzer(drawDownAnalyzer)

    tradesAnalyzer = trades.Trades()
    pStrategy.attachAnalyzer(tradesAnalyzer)

    plt = plotter.StrategyPlotter(pStrategy)

    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

    pStrategy.run()

    plt.plot()

    print("Final portfolio value: $%.2f" % pStrategy.getResult())
    print("Cumulative returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100))
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0.05)))
    print("Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100))
    print("Longest drawdown duration: %s" % (drawDownAnalyzer.getLongestDrawDownDuration()))
Exemplo n.º 3
0
 def __init__(self, dbinfo=ct.DB_INFO, redis_host=None):
     self.dbinfo = dbinfo
     self.logger = getLogger(__name__)
     self.tu_client = get_tushare_client()
     self.doc = CDoc()
     self.redis = create_redis_obj(
     ) if redis_host is None else create_redis_obj(redis_host)
     self.mysql_client = CMySQL(dbinfo, iredis=self.redis)
     self.margin_client = Margin(dbinfo=dbinfo, redis_host=redis_host)
     self.rstock_client = RIndexStock(dbinfo=dbinfo, redis_host=redis_host)
     self.sh_market_client = StockExchange(ct.SH_MARKET_SYMBOL)
     self.sz_market_client = StockExchange(ct.SZ_MARKET_SYMBOL)
     self.emotion_client = Emotion()
Exemplo n.º 4
0
from os.path import abspath, dirname
sys.path.insert(0, dirname(dirname(dirname(abspath(__file__)))))
import operator
import numpy as np
import pandas as pd
import tushare as ts
import statsmodels.api as sm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import statsmodels.tsa.stattools as sts
from ccalendar import CCalendar
from sklearn.model_selection import train_test_split
from common import get_dates_array, get_tushare_client, add_suffix, delta_days, create_redis_obj, transfer_int_to_date_string
fpath = '/Users/hellobiek/Documents/workspace/python/quant/smart_deal_tool/configure/tushare.json'
mredis = create_redis_obj(host="127.0.0.1")
ts_client = get_tushare_client(fpath)


def select_code(code_list, start_date, end_date):
    date_arrays = list()
    for mdate in get_dates_array(start_date, end_date, dformat="%Y%m%d"):
        if CCalendar.is_trading_day(transfer_int_to_date_string(mdate),
                                    redis=mredis):
            date_arrays.append(mdate)
    #choose stock which is not suspended verry long
    total_df = pd.DataFrame()
    for code in code_list:
        df = ts.pro_bar(pro_api=ts_client,
                        ts_code=add_suffix(code),
                        adj='qfq',
                        start_date=start_date,
Exemplo n.º 5
0
#-*- coding: utf-8 -*-
from common import get_tushare_client

if __name__ == '__main__':
    tu_client = get_tushare_client()
    df = tu_client.trade_cal(exchange='',
                             start_date='20190101',
                             end_date='20201231')
    df = df[['cal_date', 'is_open']]
    df = df.rename(columns={"cal_date": "calendarDate", "is_open": "isOpen"})
    df['calendarDate'] = df['calendarDate'].astype(str)
    df['calendarDate'] = pd.to_datetime(
        df.calendarDate).dt.strftime("%Y-%m-%d")
    old_df = pd.read_csv('/conf/calAll.csv')
    new_df = old_df.append(df)
    new_df = new_df.reset_index(drop=True)
    new_df.to_csv('/conf/calAll.csv')