JohnGalt
JohnGalt

Reputation: 1

Why does the Zipline Library not work properly (ValueError)?

I've tried this code from the book Trading Evolved, but could not get it working. The error message seems to refer to installation problems with the zipline library. I've ingested the Quandl bundle with different API keys and tried to use a different environment, but nothing seems to help. (I'm running the code on python 3.8 with Jupyter notebook) Thanks in advance for any help.

# This ensures that our graphs will be shown properly in the notebook.
%matplotlib inline

# Import Zipline functions that we need
from zipline import run_algorithm
from zipline.api import order_target_percent, symbol

# Import date and time zone libraries
from datetime import datetime
import pytz

# Import visualization
import matplotlib.pyplot as plt


def initialize(context):
    # Which stock to trade
    context.stock = symbol('AAPL')
    
    # Moving average window
    context.index_average_window = 100
    
def handle_data(context, data):
    # Request history for the stock
    equities_hist = data.history(context.stock, "close", 
                                 context.index_average_window, "1d")
    
    # Check if price is above moving average
    if equities_hist[-1] > equities_hist.mean():
        stock_weight = 1.0
    else:
        stock_weight = 0.0
    
    # Place order
    order_target_percent(context.stock, stock_weight)

def analyze(context, perf):
    fig = plt.figure(figsize=(12, 8))
    
    # First chart
    ax = fig.add_subplot(311)
    ax.set_title('Strategy Results')
    ax.semilogy(perf['portfolio_value'], linestyle='-', 
                label='Equity Curve', linewidth=3.0)
    ax.legend()
    ax.grid(False)
    
    # Second chart
    ax = fig.add_subplot(312)
    ax.plot(perf['gross_leverage'], 
            label='Exposure', linestyle='-', linewidth=1.0)
    ax.legend()
    ax.grid(True)

    # Third chart
    ax = fig.add_subplot(313)
    ax.plot(perf['returns'], label='Returns', linestyle='-.', linewidth=1.0)
    ax.legend()
    ax.grid(True)

# Set start and end date
start_date = datetime(2000, 1, 1, tzinfo=pytz.UTC)
end_date = datetime(2015, 12, 31, tzinfo=pytz.UTC)

# Fire off the backtest
results = run_algorithm(
    start=start_date, 
    end=end_date, 
    initialize=initialize, 
    analyze=analyze, 
    handle_data=handle_data, 
    capital_base=10000, 
    data_frequency = 'daily', bundle='quandl' 
) 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[4], line 66
     63 end_date = datetime(2015, 12, 31, tzinfo=pytz.UTC)
     65 # Fire off the backtest
---> 66 results = run_algorithm(
     67     start=start_date, 
     68     end=end_date, 
     69     initialize=initialize, 
     70     analyze=analyze, 
     71     handle_data=handle_data, 
     72     capital_base=10000, 
     73     data_frequency = 'daily', bundle='quandl' 
     74 )

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\utils\run_algo.py:397, in run_algorithm(start, end, initialize, capital_base, handle_data, before_trading_start, analyze, data_frequency, bundle, bundle_timestamp, trading_calendar, metrics_set, benchmark_returns, default_extension, extensions, strict_extensions, environ, custom_loader, blotter)
    393 load_extensions(default_extension, extensions, strict_extensions, environ)
    395 benchmark_spec = BenchmarkSpec.from_returns(benchmark_returns)
--> 397 return _run(
    398     handle_data=handle_data,
    399     initialize=initialize,
    400     before_trading_start=before_trading_start,
    401     analyze=analyze,
    402     algofile=None,
    403     algotext=None,
    404     defines=(),
    405     data_frequency=data_frequency,
    406     capital_base=capital_base,
    407     bundle=bundle,
    408     bundle_timestamp=bundle_timestamp,
    409     start=start,
    410     end=end,
    411     output=os.devnull,
    412     trading_calendar=trading_calendar,
    413     print_algo=False,
    414     metrics_set=metrics_set,
    415     local_namespace=False,
    416     environ=environ,
    417     blotter=blotter,
    418     custom_loader=custom_loader,
    419     benchmark_spec=benchmark_spec,
    420 )

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\utils\run_algo.py:93, in _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter, custom_loader, benchmark_spec)
     64 def _run(
     65     handle_data,
     66     initialize,
   (...)
     86     benchmark_spec,
     87 ):
     88     """Run a backtest for the given algorithm.
     89 
     90     This is shared between the cli and :func:`zipline.run_algo`.
     91     """
---> 93     bundle_data = bundles.load(
     94         bundle,
     95         environ,
     96         bundle_timestamp,
     97     )
     99     if trading_calendar is None:
    100         trading_calendar = get_calendar("XNYS")

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\data\bundles\core.py:534, in _make_bundle_core.<locals>.load(name, environ, timestamp)
    531     timestamp = pd.Timestamp.utcnow()
    532 timestr = most_recent_data(name, timestamp, environ=environ)
    533 return BundleData(
--> 534     asset_finder=AssetFinder(
    535         asset_db_path(name, timestr, environ=environ),
    536     ),
    537     equity_minute_bar_reader=BcolzMinuteBarReader(
    538         minute_equity_path(name, timestr, environ=environ),
    539     ),
    540     equity_daily_bar_reader=BcolzDailyBarReader(
    541         daily_equity_path(name, timestr, environ=environ),
    542     ),
    543     adjustment_reader=SQLiteAdjustmentReader(
    544         adjustment_db_path(name, timestr, environ=environ),
    545     ),
    546 )

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\assets\assets.py:301, in AssetFinder.__init__(self, engine, future_chain_predicates)
    299 @preprocess(engine=coerce_string_to_eng(require_exists=True))
    300 def __init__(self, engine, future_chain_predicates=CHAIN_PREDICATES):
--> 301     self.engine = engine
    302     metadata = sa.MetaData(bind=engine)
    303     metadata.reflect(only=asset_db_table_names)

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\utils\input_validation.py:811, in coerce.<locals>.preprocessor(func, argname, arg)
    809 def preprocessor(func, argname, arg):
    810     if isinstance(arg, from_):
--> 811         return to(arg, **to_kwargs)
    812     return arg

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\utils\sqlite_utils.py:44, in check_and_create_engine(path, require_exists)
     42 def check_and_create_engine(path, require_exists):
     43     if require_exists:
---> 44         verify_sqlite_path_exists(path)
     45     return sa.create_engine("sqlite:///" + path)

File ~\anaconda3\envs\zip38\lib\site-packages\zipline\utils\sqlite_utils.py:33, in verify_sqlite_path_exists(path)
     31 def verify_sqlite_path_exists(path):
     32     if path != ":memory:" and not os.path.exists(path):
---> 33         raise ValueError("SQLite file {!r} doesn't exist.".format(path))

ValueError: SQLite file 'C:\\Users\\baiti/.zipline\\data\\quandl\\2023-04-10T14;42;52.812027\\assets-7.sqlite' doesn't exist.

I'm also a bit confused that I get a ValueError, when running the code, thereby the paths to the packages script ought to be valid. I've checked the scripts as far as run_algorithm is concerned, I asked the AI and I changed the environment.

Upvotes: 0

Views: 233

Answers (0)

Related Questions