In [1]:
import OnePy as op
%matplotlib inline

Cleaner介绍


In [2]:
from OnePy.sys_module.base_cleaner import CleanerBase

class SMA(CleanerBase):
    """
    编写自己的cleaner,只需自己创建一个CleanerBase的子类,然后覆盖calculate方法
    默认提供data字典, key 为 ticker_frequency 的形式,比如 000001_D
    self.data 内又是以open,high,low,close,volume为键值的字典, 
    每次事件循环只会保留固定rolling_window长度的数据
    """
    
    def calculate(self, ticker):
        key = f'{ticker}_{self.frequency}'
        close = self.data[key]['close']

        return sum(close)/len(close)

In [3]:
class SmaStrategy(op.StrategyBase): 

    def __init__(self):
        super().__init__()
        self.sma1 = SMA(rolling_window=3,   # 设置cleaner中data长度
                        buffer_day= 40,     # 设置preload数据长度,过低会自动调整
                        frequency='D'       # 设置需要用来计算的数据频率,默认为系统频率
                       ).calculate
        
        self.sma2 = SMA(5, 40).calculate

    def handle_bar(self):
        for ticker in self.env.tickers:
            if self.sma1(ticker) > self.sma2(ticker):

                self.buy(100, ticker, takeprofit=15,
                         stoploss=100)
            else:
                self.sell(100, ticker)


TICKER_LIST = ['000001']
INITIAL_CASH = 20000
FREQUENCY = 'D'
START, END = '2018-03-01', '2018-10-01'

# 实例化策略,会自动添加到env.strategies中,key为类名
SmaStrategy()

# 用MongoDB数据库回测
go = op.backtest.stock(TICKER_LIST, FREQUENCY, INITIAL_CASH, START, END)

go.sunny()


正在初始化OnePy
=============== OnePy初始化成功! ===============
开始寻找OnePiece之旅~~~

+--------------------------------+
|Fromdate           |  2018-03-01|
|Todate             |  2018-10-01|
|Initial_Value      |   $20000.00|
|Final_Value        |   $19483.31|
|Total_Return       |     -2.583%|
|Max_Drawdown       |      2.959%|
|Max_Duration       |    146 days|
|Max_Drawdown_Date  |  2018-09-21|
|Sharpe_Ratio       |       -2.04|
+--------------------------------+

In [4]:
from OnePy.builtin_module.mongodb_saver.tushare_saver import  multi_tushare_to_mongodb
from OnePy.builtin_module.mongodb_saver.utils import MongoDBFunc

# 保存H1数据
FREQUENCY = ["H1"]  # 注意Tushre的H1数据只有从2018年开始的数据
START = '2018-02-01'
TICKER_LIST = ['000001']

multi_tushare_to_mongodb(ticker_list=TICKER_LIST, 
                         period_list=FREQUENCY,
                         fromdate=START)

MongoDBFunc().drop_duplicates(TICKER_LIST, FREQUENCY, 'tushare')


Start!
<<000001, H1>> has completed, Total: 482
['000001'],H1 all set!!!!!
<<000001, H1>> has been drop 482 duplicates!

尝试用不同的frequency的cleaner回测, 变成每次用H1数据计算SMA信号


In [5]:
class SmaStrategy(op.StrategyBase):

    def __init__(self):
        super().__init__()
        self.sma1 = SMA(rolling_window=3,   
                        buffer_day= 10,     
                        frequency='H1'       
                       ).calculate
        
        self.sma2 = SMA(5, 10,'H1').calculate

    def handle_bar(self):
        for ticker in self.env.tickers:
            if self.sma1(ticker) > self.sma2(ticker):

                self.buy(100, ticker, takeprofit=15,
                         stoploss=100)
            else:
                self.sell(100, ticker)


TICKER_LIST = ['000001']
INITIAL_CASH = 20000
FREQUENCY = 'D'
START, END = '2018-04-01', '2018-10-01'

# 实例化策略,会自动添加到env.strategies中
SmaStrategy()

# 用MongoDB数据库回测
go = op.backtest.stock(TICKER_LIST, FREQUENCY, INITIAL_CASH, START, END)

go.sunny(show_process=False)


正在初始化OnePy
=============== OnePy初始化成功! ===============
开始寻找OnePiece之旅~~~

+--------------------------------+
|Fromdate           |  2018-04-01|
|Todate             |  2018-10-01|
|Initial_Value      |   $20000.00|
|Final_Value        |   $19910.21|
|Total_Return       |     -0.449%|
|Max_Drawdown       |      1.396%|
|Max_Duration       |     99 days|
|Max_Drawdown_Date  |  2018-08-20|
|Sharpe_Ratio       |       -0.83|
+--------------------------------+

In [6]:
go.output.show_setting()


+--------------------+
|readers_1  |  000001|
+--------------------+
+--------------------+
|cleaners_1  |  SMA_1|
|cleaners_2  |  SMA_2|
+--------------------+
+--------------------------+
|strategy_1  |  SmaStrategy|
+--------------------------+
+-------------------------+
|brokers_1  |  StockBroker|
+-------------------------+
+-----------------------------------------------+
|risk_managers_1  |  StockLimitFilterRiskManager|
+-----------------------------------------------+
+-----------------------------+
|recorders_1  |  StockRecorder|
+-----------------------------+

Strategy介绍


In [8]:
class SmaStrategy(op.StrategyBase):

    def __init__(self):
        super().__init__() # 需要继承父类构造函数
        
    def handle_bar(self):
        pass
    
##         调取账户信息
        # go.env.recorder.holding_pnl.latest(ticker='000001', long_or_short='long')
        # go.env.recorder.realized_pnl
        # go.env.recorder.commission
        # go.env.recorder.market_value
        # go.env.recorder.margin
        # go.env.recorder.position
        # go.env.recorder.avg_price
        # go.env.recorder.cash
        # go.env.recorder.frozen_cash
        # go.env.recorder.balance        
        
##         Function
#         self.cur_price
#         self.buy
#         self.sell
#         self.short
#         self.cover
#         self.cancel_pending
#         self.cancel_tst

In [ ]: