quantopian / pyfolio

Portfolio and risk analytics in Python
https://quantopian.github.io/pyfolio
Apache License 2.0
5.61k stars 1.76k forks source link

numpy error when trying to import pyfolio #629

Open CaioLC opened 4 years ago

CaioLC commented 4 years ago

Problem Description

I'm coding along Andreas Clenow's book "Trading Evolved" and having a issue importing pyfolio, due to a numpy error:

ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C header, got 192 from PyObject

Doing some online research, this error can be fixed by upgrading numpy to version 1.16.1. Problem is, such version is not compatible with Python 3.5 which I use for zipline library. Any thoughts on a different approach to solving this compatibility issue? thanks in advance

%matplotlib inline

from zipline import run_algorithm
from zipline.api import order_target_percent, record, symbol
from datetime import datetime
import pytz
import matplotlib.pyplot as plt
import pyfolio as pf

def initialize(context):
    # which stocks to trade
    dji = [
        'AAPL',
        'AXP',
        'BA',
        'CAT',
        'CSCO',
        'CVX',
        'DIS',
        'DWDP',
        'GS',
        'HD',
        'IBM',
        'INTC',
        'JNJ',
        'JPM',
        'KO',
        'MCD',
        'MMM',
        'MRK',
        'MSFT',
        'NKE',
        'PFE',
        'PG',
        'TRV',
        'UNH',
        'UTX',
        'V',
        'VZ',
        'WBA',
        'WMT',
        'XOM',
    ]

    # make a list of symbols from the list of tickers
    context.universe = [symbol(s) for s in dji]

    # history window
    context.history_window = 20

    # portfolio size
    context.stocks_to_hold = 10

    # schedule the daily trading routine for once per month
    schedule_function(handle_data, date_rules.month_start(), time_rules.market_close())

def month_perf(ts):
    perf = (ts[-1] / ts[0]) - 1
    return perf

def handle_data(context, data):
    # get history for all the stocks
    hist = data.history(context.universe, 'close', context.history_window, '1d')

    # this creates a table of percent returns, in order
    perf_table = hist.apply(month_perf).sort_values(ascending=False)

    # make buy list of the top N stocks
    buy_list = perf_table[:context.stocks_to_hold]

    # the rest will not be held
    the_rest = perf_table[context.stocks_to_hold:]

    # Place target buy orders for top N stocks
    for stock, perf in buy_list.iteritems():
        stock_weight = 1 / context.stocks_to_hold

        # place order
        if data.can_trade(stock):
            # place the trade
            order_target_percent(stock, stock_weight)

    # make sure we are flat the rest
    for stock, perf in the_rest.iteritems():
        # place order
        if data.can_trade(stock):
            # place the trade
            order_target_percent(stock, 0.0)

def analyze(context, perf):
    # Use PyFolio to generate a performance report
    returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(perf)
    pf.create_returns_tear_sheet(returns, benchmark_rets=None)

# Set start and end date
start = datetime(2003, 1, 1, tzinfo=pytz.UTC)
end = datetime(2017, 12, 31, tzinfo=pytz.UTC)

# fire off the backtest
results = run_algorithm(
    start = start,
    end = end,
    initialize = initialize,
    analyze = analyze,
    capital_base = 10000,
    data_frequency = 'daily', bundle='quandl'
)

Please provide the full traceback:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-93e9e8997f0c> in <module>()
      6 import pytz
      7 import matplotlib.pyplot as plt
----> 8 import pyfolio as pf
      9 
     10 def initialize(context):

C:\ProgramData\Anaconda3\envs\zip35\lib\site-packages\pyfolio\__init__.py in <module>()
      2 
      3 from . import utils
----> 4 from . import timeseries
      5 from . import pos
      6 from . import txn

C:\ProgramData\Anaconda3\envs\zip35\lib\site-packages\pyfolio\timeseries.py in <module>()
     23 import scipy as sp
     24 import scipy.stats as stats
---> 25 from sklearn import linear_model
     26 
     27 from .deprecate import deprecated

C:\ProgramData\Anaconda3\envs\zip35\lib\site-packages\sklearn\__init__.py in <module>()
     80     from . import _distributor_init  # noqa: F401
     81     from . import __check_build  # noqa: F401
---> 82     from .base import clone
     83     from .utils._show_versions import show_versions
     84 

C:\ProgramData\Anaconda3\envs\zip35\lib\site-packages\sklearn\base.py in <module>()
     18 
     19 from . import __version__
---> 20 from .utils import _IS_32BIT
     21 
     22 _DEFAULT_TAGS = {

C:\ProgramData\Anaconda3\envs\zip35\lib\site-packages\sklearn\utils\__init__.py in <module>()
     20 from scipy.sparse import issparse
     21 
---> 22 from .murmurhash import murmurhash3_32
     23 from .class_weight import compute_class_weight, compute_sample_weight
     24 from . import _joblib

__init__.pxd in init sklearn.utils.murmurhash()

ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C header, got 192 from PyObject

Versions

suhan-jung commented 4 years ago

same issue here. so I installed pyfolio version 0.8.0, no numpy.ufunc error, but have "AttributeError: module 'pandas_datareader.data' has no attribute 'get_data_google'" error in another example.