对示例Zipline策略和杠杆进行建模似乎超过了1

时间:2018-11-08 14:21:24

标签: python quantitative-finance zipline quantopian

我正在使用自己的数据对文档中的示例交易策略进行建模。在这里,我使用以太坊价格。我不确定是否可以在此处发布文件。

我看到的问题是,我希望杠杆率可以是0或1(或者如果有任何剩余变化,则处于零下)。如果移动平均线交叉,则根据交叉的方向,我买入我的投资组合的100%,或卖出100%。这是Zipline文档中使用的示例策略。

我的问题是我使用时

    record(leverage = context.account.leverage)

然后作图,我发现杠杆率短暂地跃升到1以上。我不确定为什么会发生这种情况。

代码如下:

%load_ext zipline
from zipline.api import order_target, order_target_percent, get_open_orders, get_datetime, record, symbol
import zipline
import matplotlib.pyplot as plt
from datetime import datetime
from collections import OrderedDict
import pandas as pd
import pytz
import matplotlib.pyplot as plt
from matplotlib import style

data = OrderedDict()
tickers = ['ETH']

#Takes in ETH data, cleans, resamples, and creates panel
for ticker in tickers:
    data[ticker] = pd.read_csv("{}USD_Bitfinex.csv".format(ticker), index_col=0, parse_dates=['Date'])
    data[ticker]['open'] = data[ticker]['Last'].shift(-1)
    data[ticker] = data[ticker][['open', 'High', 'Low', 'Last', 'Volume']]
    data[ticker].columns = ('open', 'high', 'low', 'close', 'volume')
    data[ticker].sort_index(inplace=True)
    data[ticker].drop(data[ticker].index[0], inplace=True)
    data[ticker] = data[ticker].resample('1h').pad()
    print(type(data[ticker].index))
    print(data[ticker])

panel = pd.Panel(data)
panel.minor_axis = ['open', 'high', 'low', 'close', 'volume']
panel.major_axis = panel.major_axis.tz_localize(pytz.utc)

def initialize(context):
    context.i = 0

    context.asset = symbol('ETH')

def print_open_orders(context, data):
    if get_open_orders():  
        for security, orders in get_open_orders().iteritems():  
            for oo in orders:  
                print("%.5s : OPEN ORDER %s [amt=%d,filled=%d,left=%d]" % (str(get_datetime().time()), str(oo.created), oo.amount, oo.filled, oo.amount - oo.filled))
    else:
        print("%.5s : NO OPEN ORDERS" % (str(get_datetime().time())))

def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 28:
        return

    # Compute averages
    # data.history() has to be called with the same params
    # from above and returns a pandas dataframe.
    short_mavg = data.history(context.asset, 'price', bar_count=7, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price', bar_count=28, frequency="1d").mean()

    print_open_orders(context, data)

    # Trading logic
    if short_mavg > long_mavg:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        order_target_percent(context.asset, 1)
        print('Buying')
    elif short_mavg < long_mavg:
        order_target_percent(context.asset, 0)
        print('Selling')


    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg,
           long_mavg=long_mavg)

    record(leverage = context.account.leverage)
    record(cash = context.portfolio.cash)

perf = zipline.run_algorithm(start=datetime(2017, 1, 5, 0, 0, 0, 0, pytz.utc),
                      end=datetime(2018, 3, 1, 0, 0, 0, 0, pytz.utc),
                      initialize=initialize,
                      capital_base=100000,
                      handle_data=handle_data,
                             data=panel)

现在当我绘制杠杆时

perf.leverage.plot()
plt.title('Portfolio Leverage')

plt.show()

我得到这样的图表:

enter image description here

我无法理解高于1的峰值。有什么想法吗?

0 个答案:

没有答案