# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# 看看均线策略。

# +
import pandas as pd
from datetime import datetime
import trdb2py

isStaticImg = False
width = 960
height = 768

pd.options.display.max_columns = None
pd.options.display.max_rows = None

trdb2cfg = trdb2py.loadConfig('./trdb2.yaml')
# -

# 我们先指定一个特定的基金，特定的时间段来分析吧。

# +
# 具体基金
# asset = 'jrj.510310'
# baselineasset = 'jrj.510310'
# asset = 'jqdata.000300_XSHG|1d'
asset = 'jqdata.000036_XSHG|1d'

# 起始时间，0表示从最开始算起
tsStart = 0
tsStart = int(trdb2py.str2timestamp('2013-05-01', '%Y-%m-%d'))

# 结束时间，-1表示到现在为止
tsEnd = -1
tsEnd = int(trdb2py.str2timestamp('2020-09-30', '%Y-%m-%d'))

# 初始资金池
paramsinit = trdb2py.trading2_pb2.InitParams(
    money=10000,
)

# 买入参数，用全部的钱来买入（也就是复利）
paramsbuy = trdb2py.trading2_pb2.BuyParams(
    perHandMoney=1,
    depositMoney=10000,
)

paramsbuy1 = trdb2py.trading2_pb2.BuyParams(
    perHandMoney=1,
    nextTimes=1,
)

# 买入参数，用全部的钱来买入（也就是复利）
paramsbuy2 = trdb2py.trading2_pb2.BuyParams(
    moneyParts=2,
)

# 卖出参数，全部卖出
paramssell = trdb2py.trading2_pb2.SellParams(
    perVolume=1,
)

# 卖出参数，全部卖出
paramssell7 = trdb2py.trading2_pb2.SellParams(
#     perVolume=1,
    keepTime=7 * 24 * 60 * 60,
)

lststart = [1, 2, 3, 4, 5]
lsttitle = ['周一', '周二', '周三', '周四', '周五']
# -

# 首先看看这个基金的基准表现，就是在开始时间就直接买入，然后一直持有，看具体的收益率。

# +
# baseline    
s0 = trdb2py.trading2_pb2.Strategy(
    name="normal",
    asset=trdb2py.str2asset(asset),         
)
        
buy0 = trdb2py.trading2_pb2.CtrlCondition(
    name='buyandhold',
)

# paramsbuy = trdb2py.trading2_pb2.BuyParams(
#     perHandMoney=1,
# )

# paramsinit = trdb2py.trading2_pb2.InitParams(
#     money=10000,
# )

s0.buy.extend([buy0])
s0.paramsBuy.CopyFrom(paramsbuy)
s0.paramsInit.CopyFrom(paramsinit)        
p0 = trdb2py.trading2_pb2.SimTradingParams(
    assets=[trdb2py.str2asset(asset)],
    startTs=tsStart,
    endTs=tsEnd,
    strategies=[s0],
    title='baseline',
)  

pnlBaseline = trdb2py.simTrading(trdb2cfg, p0)
trdb2py.showPNL(pnlBaseline, toImg=isStaticImg, width=width, height=height)
# -

# 那么策略基准线大概就是这样了，7年多的时间2.2倍。

# +
lstparams = []


buy0 = trdb2py.trading2_pb2.CtrlCondition(
    name='indicatorsv',
    operators=['<='],
    vals=[-0.015],
    strVals=['roc.{}'.format(1)],
)

sell0 = trdb2py.trading2_pb2.CtrlCondition(
    name='indicatorsv',
    operators=['>='],
    vals=[0.02],
    strVals=['roc.{}'.format(1)],
)

s0 = trdb2py.trading2_pb2.Strategy(
    name="normal",
    asset=trdb2py.str2asset(asset),
)

s0.buy.extend([buy0])
s0.sell.extend([sell0])
s0.paramsBuy.CopyFrom(paramsbuy)
s0.paramsSell.CopyFrom(paramssell) 
s0.paramsInit.CopyFrom(paramsinit)        
lstparams.append(trdb2py.trading2_pb2.SimTradingParams(
    assets=[trdb2py.str2asset(asset)],
    startTs=tsStart,
    endTs=tsEnd,
    strategies=[s0],
    title='roc[{}-{}]'.format(1.5, 2),
))
 
lstpnlmix = trdb2py.simTradings(trdb2cfg, lstparams, ignoreTotalReturn=2.3)

trdb2py.showPNLs(lstpnlmix + [pnlBaseline], toImg=isStaticImg, width=width, height=height)

# +
lstparams = []

lstdown = []
lstup = []

os = -0.05
while True:
    lstdown.append(os)
    if os >= 0:
        break
    os += 0.001

os = 0.05
while True:
    lstup.append(os)
    if os <= 0:
        break
    os -= 0.001    

for dobj in lstdown:
    for uobj in lstup:
        buy0 = trdb2py.trading2_pb2.CtrlCondition(
            name='indicatorsv',
            operators=['<='],
            vals=[dobj],
            strVals=['roc.{}'.format(1)],
        )

        sell0 = trdb2py.trading2_pb2.CtrlCondition(
            name='indicatorsv',
            operators=['>='],
            vals=[uobj],
            strVals=['roc.{}'.format(1)],
        )

        s0 = trdb2py.trading2_pb2.Strategy(
            name="normal",
            asset=trdb2py.str2asset(asset),
        )

        s0.buy.extend([buy0])
        s0.sell.extend([sell0])
        s0.paramsBuy.CopyFrom(paramsbuy)
        s0.paramsSell.CopyFrom(paramssell) 
        s0.paramsInit.CopyFrom(paramsinit)        
        lstparams.append(trdb2py.trading2_pb2.SimTradingParams(
            assets=[trdb2py.str2asset(asset)],
            startTs=tsStart,
            endTs=tsEnd,
            strategies=[s0],
            title='roc[{:0.2f}-{:0.2f}]'.format(dobj * 100, uobj * 100),
        ))
        
# len(lstparams)

lstpnlmix = trdb2py.simTradings(trdb2cfg, lstparams, ignoreTotalReturn=3)

trdb2py.showPNLs(lstpnlmix + [pnlBaseline], toImg=isStaticImg, width=width, height=height)

# +
dfpnl = trdb2py.buildPNLReport(lstpnlmix + [pnlBaseline])

# dfpnl1 = dfpnl[dfpnl['totalReturns'] >= 2]

dfpnl[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False)
# -



StarcoderdataJupyterScriptsDedupFiltered