'TradingAlgorithm' object has no attribute 'stock_list' 错误什么原因

新手专区
标签: #<Tag:0x00007efe9150f8e8>

(linengwei) #1

回测引擎:每日数据处理函数,每天执行一次

def m19_handle_data_bigquant_run(context, data):
bought_stock = []
positions = context.portfolio.positions
for equity in positions:
position = positions[equity]
bought_stock = bought_stock.append(position)

for bought in bought_stock:
    import datetime
    import time

    tt = time.strftime("%y-%m-%d")    #获取今日日期
    to_day = datetime.datetime.strptime(tt, "%y-%m-%d")     #将获取的今日日期调整格式
    start_date = datetime.datetime.now()+datetime.timedelta(days=-200)   #从今日往前计算120个交易日期作为start_date

    stock_data = DataSource('bar1d_CN_STOCK_A').read(bought,start_date=start_date,end_date=to_day,fields=["date","close","high","low","adjust_factor"])
    stock_data['high'] = stock_data['high']/stock_data['adjust_factor']
    stock_data['low'] = stock_data['low']/stock_data['adjust_factor']
    stock_data['close'] = stock_data['close']/stock_data['adjust_factor']

    for i in range(0,len(stock_data)-100):
        stock_data = stock_data.drop(index=i)
    stock_data = stock_data.reset_index(drop=True)
    
    stock_data['date']=stock_data['date'].astype('str')
    stock_data['date']=pd.to_datetime(stock_data['date'])

    stock_data.set_index('date', inplace=True)
    stock_data["H"] = 0
    stock_data["L"] = 0
    stock_data["RSV"] = 0
    stock_data["K"] = 50
    stock_data["D"] = 50
    stock_data["J"] = 0
    stock_data = stock_data.dropna()
    stock_data.reset_index(inplace=True)

    for i in range(0,len(stock_data)-1,1):
        data_h = stock_data.loc[i:i+8,stock_data.columns=="high"]
        data_h_h = data_h.loc[:,"high"].max()
        data_l = stock_data.loc[i:i+8,stock_data.columns=="low"]
        data_l_l = data_l.loc[:,"low"].min()
        stock_data.loc[i+8,stock_data.columns=="H"] = data_h_h
        stock_data.loc[i+8,stock_data.columns=="L"] = data_l_l

        if pd.isnull(stock_data.loc[i+8,stock_data.columns=="close"].values[-1]):
            break
        c   = stock_data.loc[i+8,stock_data.columns=="close"].values[-1]
        h   = stock_data.loc[i+8,stock_data.columns=="H"].values[-1]
        l   = stock_data.loc[i+8,stock_data.columns=="L"].values[-1]
        rsv = ((c - l)/(h - l)) * 100
        stock_data.loc[i+8,stock_data.columns=="RSV"] = rsv

        k_1 = stock_data.loc[i+7,stock_data.columns=="K"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="K"] = (2/3) * k_1 + (1/3) * rsv

        d_1 = stock_data.loc[i+7,stock_data.columns=="D"].values[-1]
        k = stock_data.loc[i+8,stock_data.columns=="K"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="D"] = (2/3) * d_1 + (1/3) * k

        d = stock_data.loc[i+8,stock_data.columns=="D"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="J"] = 3*k - 2*d

        j_1 = stock_data.loc[i+7,stock_data.columns=="J"].values[-1]
        j   = stock_data.loc[i+8,stock_data.columns=="J"].values[-1]
    


    stock_data = stock_data.round(2)
    stock_data = stock_data.drop(index=100)



    current_quantity = context.portfolio.positions[context.symbol(bought)].amount
    
    if j_1 > j:
        context.order(context.symbol(bought), current_quantity* (-1))



stocks = ["000060.SZA","600030.SHA","000758.SZA"]
stock_list = []
for stock in stocks:
    import datetime
    import time
    tt = time.strftime("%y-%m-%d")    #获取今日日期
    to_day = datetime.datetime.strptime(tt, "%y-%m-%d")     #将获取的今日日期调整格式
    start_date = datetime.datetime.now()+datetime.timedelta(days=-150)   #从今日往前计算120个交易日期作为start_date
    stock_data = DataSource('bar1d_CN_STOCK_A').read(stock,start_date=start_date,end_date=to_day,fields=["date","close","high","low","adjust_factor"])
    stock_data['high'] = stock_data['high']/stock_data['adjust_factor']
    stock_data['low'] = stock_data['low']/stock_data['adjust_factor']
    stock_data['close'] = stock_data['close']/stock_data['adjust_factor']
    for i in range(0,len(stock_data)-80):
        stock_data = stock_data.drop(index=i)
    stock_data = stock_data.reset_index(drop=True)

    stock_data['date']=stock_data['date'].astype('str')
    stock_data['date']=pd.to_datetime(stock_data['date'])

    stock_data.set_index('date', inplace=True)
    stock_data["H"] = 0
    stock_data["L"] = 0
    stock_data["RSV"] = 0
    stock_data["K"] = 50
    stock_data["D"] = 50
    stock_data["J"] = 0
    stock_data = stock_data.dropna()
    stock_data.reset_index(inplace=True)

    for i in range(0,len(stock_data)-1,1):
        data_h = stock_data.loc[i:i+8,stock_data.columns=="high"]
        data_h_h = data_h.loc[:,"high"].max()
        data_l = stock_data.loc[i:i+8,stock_data.columns=="low"]
        data_l_l = data_l.loc[:,"low"].min()
        stock_data.loc[i+8,stock_data.columns=="H"] = data_h_h
        stock_data.loc[i+8,stock_data.columns=="L"] = data_l_l

        if pd.isnull(stock_data.loc[i+8,stock_data.columns=="close"].values[-1]):
            break
        c   = stock_data.loc[i+8,stock_data.columns=="close"].values[-1]
        h   = stock_data.loc[i+8,stock_data.columns=="H"].values[-1]
        l   = stock_data.loc[i+8,stock_data.columns=="L"].values[-1]
        rsv = ((c - l)/(h - l)) * 100
        stock_data.loc[i+8,stock_data.columns=="RSV"] = rsv

        k_1 = stock_data.loc[i+7,stock_data.columns=="K"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="K"] = (2/3) * k_1 + (1/3) * rsv

        d_1 = stock_data.loc[i+7,stock_data.columns=="D"].values[-1]
        k = stock_data.loc[i+8,stock_data.columns=="K"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="D"] = (2/3) * d_1 + (1/3) * k

        d = stock_data.loc[i+8,stock_data.columns=="D"].values[-1]
        stock_data.loc[i+8,stock_data.columns=="J"] = 3*k - 2*d

        j_1 = stock_data.loc[i+7,stock_data.columns=="J"].values[-1]
        j   = stock_data.loc[i+8,stock_data.columns=="J"].values[-1]

        c_2 = stock_data.loc[i+7,stock_data.columns=="close"].values[-1]
        c_1 = stock_data.loc[i+8,stock_data.columns=="close"].values[-1]
    stock_data = stock_data.dropna(axis=0)
    stock_data = stock_data.round(2)



    if  c_2 <= c_1 :
        if stock not in bought_stock:
            stock_list = stock_list.append(stock)



if len(context.stock_list) >= 2:
    weights = round(1/len(context.stock_list),2)
else:
    weights = 0.25
    
for stock in context.stock_list:
    if stock not in bought_stock:
        if len(context.stock_list) < 10:
            context.order_target_percent(context.symbol(stock), 0.2)
        else:
            context.order_target_value(context.symbol(stock), context.portfolio.cash * weights)

回测引擎:初始化函数,只执行一次

def m19_initialize_bigquant_run(context):
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))

m1 = M.instruments.v2(
start_date=‘2019-01-01’,
end_date=‘2021-08-01’,
market=‘CN_STOCK_A’,
instrument_list=’’,
max_count=0
)

m19 = M.trade.v4(
instruments=[“000060.SZA”,“600030.SHA”,“000758.SZA”],
start_date=‘2019-01-01’,
end_date=‘2021-08-01’,
handle_data=m19_handle_data_bigquant_run,
initialize=m19_initialize_bigquant_run,
volume_limit=0.025,
order_price_field_buy=‘open’,
order_price_field_sell=‘close’,
capital_base=1000000,
auto_cancel_non_tradable_orders=True,
data_frequency=‘daily’,
price_type=‘真实价格’,
product_type=‘股票’,
plot_charts=True,
backtest_only=False,
benchmark=‘000300.SHA’
)


(yvan0617) #2

stock_list是你自己定义的一个变量,不是context对象里面的,不需要加context这个前缀
image


BigQuant策略组