zipline错误KeyError:<type'zipline.assets._assets.equity'=“”>

时间:2017-02-06 02:13:19

标签: pandas algorithmic-trading zipline

当我尝试使用zipline在quantopian框架外执行简单的交叉策略算法时,我收到以下错误。

KeyError: <type 'zipline.assets._assets.Equity'>

这是一个简单的交叉策略,计算50-100天移动平均线以得出交易策略。我无法使用zipline从Quantopian框架中运行此策略。

代码如下

import pandas as pd
import zipline
from zipline import TradingAlgorithm
from zipline.api import order, sid
from zipline.utils.factory import load_from_yahoo
import matplotlib.pyplot as plt
from zipline.api import order, symbol, record, order_target
import pytz
%matplotlib inline

# creating time interval
start = pd.Timestamp('2013-01-25', tz='UTC')
end = pd.Timestamp('2017-02-01', tz='UTC')

#input_date = get_pricing(['AAPL'],start,end,frequency='daily')
# loading the data
#input_data = load_bars_from_yahoo(stocks=['AAPL'], start=start,end=end,)

data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start, end=end)
data = data.dropna()


def initialize(context):
    context.security= symbol('AAPL')
    context.i =0


def handle_data(context, data):


 context.i += 1
    if context.i<100:
        return

MA1 = data[context.security].mavg(50)
MA2 = data[context.security].mavg(100)
date = str(data[context.security].datetime)[:10]
current_price = data[context.security].price
current_positions = context.portfolio.positions[symbol('AAPL')].amount
cash = context.portfolio.cash
value = context.portfolio.portfolio_value
current_pnl = context.portfolio.pnl
if (MA1 > MA2) and current_positions == 0:
    number_of_shares = 100
    order(context.security, number_of_shares)
    record(AAPL=inputdata[symbol('AAPL')].price,date=date,MA1 = MA1, MA2 =   MA2, Price= 
             current_price,status="buy",shares=number_of_shares,PnL=current_pnl,cash=cash,value=value)

elif (MA1 < MA2) and current_positions != 0:
    order_target(context.security, 0)
    record(AAPL=inputdata[symbol('AAPL')].price,date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="sell",shares="--",PnL=current_pnl,cash=cash,value=value)

else:
    record(AAPL=inputdata[symbol('AAPL')].price,date=date,MA1 = MA1, MA2 = MA2, Price= current_price,status="--",shares="--",PnL=current_pnl,cash=cash,value=value)


algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
results = algo.run(input_data)

1 个答案:

答案 0 :(得分:1)

使用以下代码计算MA1和MA2,然后就可以了! 因为某些功能在zipline 1.1.0中已经过时了

from talib import MA
trailing_window = data.history(assets=context.security, fields='price', bar_count=100, frequency='1d')
MA1 = MA(trailing_window.values, 50)[-1]
MA2 = MA(trailing_window.values, 100)[-1]

或使用以下代码而不使用talib:

trailing_window1 = data.history(assets=context.security, fields='price', bar_count=50, frequency='1d')
trailing_window2 = data.history(assets=context.security, fields='price', bar_count=100, frequency='1d')
MA1 = trailing_window1.mean()
MA2 = trailing_window2.mean()