2017-02-06 6 views
0

Когда я пытаюсь выполнить простой алгоритм стратегии кроссирования вне рамки квантования, используя zipline, я получаю следующую ошибку.zipline error KeyError: <type 'zipline.assets._assets.Equity'>

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

Это простая стратегия кроссовера, в которой скользящие средние 50-100 дней рассчитываются для получения торговой стратегии. Я не могу запустить эту стратегию из Quantopian framework, используя zipline.

код выглядит следующим образом

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

кодов, как показано ниже, чтобы вычислить 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] 

или использовать коды, как показано ниже, не используя Талиб:

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() 
+0

или использовать без Талиба, как показано ниже: – zshtom