개발하는 두더지

zipline 1.3.0 JSONDecodeError 해결 방법 본문

이것저것

zipline 1.3.0 JSONDecodeError 해결 방법

덜지 2020. 1. 9. 03:57

아래 예제를 만드는데 TradingAlgorithm(initialize=initialize, handle_data=handle_data) 에서 JSONDecodeError 가 발생했다.

import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
from zipline.api import order, symbol
from zipline.algorithm import TradingAlgorithm

start = datetime.datetime(2017, 1, 1)
end = datetime.datetime(2020, 1, 6)
data = web.DataReader("AAPL", "yahoo", start, end)
plt.plot(data.index, data['Adj Close'])
plt.show()

data = data[['Adj Close']]
data.columns = ["AAPL"]
data = data.tz_localize("UTC")


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


def handle_data(context, data):
    order(context.sym, 1)


algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
result = algo.run(data)
result.head()

zipline 패키지의 benchmark.py 에서 데이터를 받아오는 부분이 실패를 해서 잘못된 값을 넘겨주면서 exception이 발생하는 것으로 보인다. 구글을 찾아보니 해결 방법이 있다..!

Zipline will have to move their datasource for SPY data somewhere else besides IEX, or change the setup to require an API >key. Another way to fix is:

sign up here: https://iexcloud.io/cloud-login#/register
find where your benchmarks.py file is: ipython, import zipline, zipline.file
Open the zipline lib in an IDE like Atom
Add your token from the IEX dashboard (instead of pk_numbers... below), and change the requests line to:
token = 'pk_numbersnumbersnumbers'
r = requests.get(
'https://cloud.iexapis.com/stable/stock/{}/chart/5y?token={}'.format(symbol, token)
)
I guess it's the nature of the beast with financial data that it's hard to find for free...but annoying.

iexclude
회원가입 후 하단에 Get started for free 탭이 있다. Select free plan 를 누르면 잠시뒤에 Membership plan successfully selected! 메시지와 함께 콘솔창을 볼 수 있다.
그리고 이메일 인증을 하면API Token: pk_2c7aeee1ff9cxxxxxxxxxxxxxxxxxxxxx 을 받을 수 있다.

zipline을 설치한 가상환경(\Anaconda3\envs\py35\Lib\site-packages\zipline) 안에 있는 benchmark.py 파일을 수정해야 합니다.

def get_benchmark_returns(symbol):
    """
    Get a Series of benchmark returns from IEX associated with `symbol`.
    Default is `SPY`.

    Parameters
    ----------
    symbol : str
        Benchmark symbol for which we're getting the returns.

    The data is provided by IEX (https://iextrading.com/), and we can
    get up to 5 years worth of data.
    """
    token = 'pk_2c7aeee1ff9c47bea9777e0c783d8e87'
    r = requests.get(
        #'https://api.iextrading.com/1.0/stock/{}/chart/5y'.format(symbol)
        'https://cloud.iexapis.com/stable/stock/{}/chart/5y?token={}'.format(symbol, token)
    )
    data = r.json()

    df = pd.DataFrame(data)

    df.index = pd.DatetimeIndex(df['date'])
    df = df['close']

    return df.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]

그리고 실행하면 정상적으로 동작

Comments