### Import Buyapple Example Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/beginner-tutorial.md Imports the buyapple example algorithm from the zipline.examples module. ```python from zipline.examples import buyapple ``` -------------------------------- ### Install in Development Mode Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/CLAUDE.md Install the project in editable mode, allowing changes to be reflected immediately without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Test Installation from PyPI Test Server Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md Verify the package uploaded to the test PyPI server by creating a new virtualenv and installing zipline using the extra-index-url. ```bash pip install --extra-index-url https://test.pypi.org/simple zipline python -c 'import zipline;print(zipline.__version__)' ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/install.md Commands to install required binary dependencies on various Linux distributions. ```bash $ sudo apt install libatlas-base-dev python-dev gfortran pkg-config libfreetype6-dev hdf5-tools ``` ```bash $ sudo dnf install atlas-devel gcc-c++ gcc-gfortran libgfortran python-devel redhat-rpm-config hdf5 ``` ```bash $ pacman -S lapack gcc gcc-fortran pkg-config hdf5 ``` ```bash $ pacman -S python3 ``` -------------------------------- ### Install TA-lib on Linux Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Download, configure, build, and install the TA-lib C library on a Linux system. This is a prerequisite for running Zipline tests. ```bash wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz tar -xvzf ta-lib-0.4.0-src.tar.gz cd ta-lib/ ./configure --prefix=/usr make sudo make install ``` -------------------------------- ### Install Zipline via pip Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/install.md Standard command to install the package using pip, ideally within a virtual environment. ```bash $ pip install zipline-reloaded ``` -------------------------------- ### Test sdist Installation Locally Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md After building the sdist, test its installation in a clean virtualenv within an empty directory to ensure all files and dependencies are included. ```bash pip install /dist/zipline-...tar.gz python -c 'import zipline;print(zipline.__version__)' ``` -------------------------------- ### Install Zipline in Development Mode Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Install Zipline and its test dependencies in editable mode within your activated virtual environment. ```bash pip install -e .[test] ``` -------------------------------- ### Build Source Distribution (sdist) Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md Run this command from the zipline root to build the sdist, which includes all necessary files for installation. ```bash python setup.py sdist ``` -------------------------------- ### Compile TA-Lib from Source Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/install.md Steps to download, configure, and install the TA-Lib library required for technical analysis. ```bash $ wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz $ tar -xzf ta-lib-0.4.0-src.tar.gz $ cd ta-lib/ $ sudo ./configure $ sudo make $ sudo make install ``` -------------------------------- ### Display zipline/examples/buyapple.py content Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb This code snippet displays the content of the `buyapple.py` example file. The command used depends on the operating system. ```python # assuming you're running this notebook in zipline/docs/notebooks if os.name == 'nt': # windows doesn't have the cat command, but uses 'type' similarly ! type "..\\..\\zipline\\examples\\buyapple.py" else: ! cat ../../zipline/examples/buyapple.py ``` -------------------------------- ### Example Pipeline Output Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Illustrates the potential output of a Zipline pipeline for a given day, showing asset prices and their winsorized values. ```python 'PRICE' 'WINSOR_1' 'WINSOR_2' 'WINSOR_3' Asset_1 1 2 4 3 Asset_2 2 2 4 3 Asset_3 3 3 4 3 Asset_4 4 4 4 4 Asset_5 5 5 5 4 Asset_6 6 5 5 4 ``` -------------------------------- ### Example 10-day returns data Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Sample 10-day returns data for SPY, MSFT, and FB assets used in calculations. ```python SPY MSFT FB 2017-03-13 -.03 .03 .04 2017-03-14 -.02 -.03 .02 2017-03-15 -.01 .02 .01 2017-03-16 0 -.02 .01 2017-03-17 .01 .04 -.01 2017-03-20 .02 -.03 -.02 2017-03-21 .03 .01 -.02 2017-03-22 .04 -.02 -.02 ``` -------------------------------- ### Install TA-lib on OS X Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Install the TA-lib C library on macOS using the Homebrew package manager. This is a prerequisite for running Zipline tests. ```bash $ brew install ta-lib ``` -------------------------------- ### Check Zipline CLI Help Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Verify that the Zipline command-line interface is accessible after installation. ```bash $ zipline --help ``` -------------------------------- ### Install Zipline via Conda Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/releases.md Use this command to install Zipline using the conda package manager. ```python conda install -c quantopian zipline ``` -------------------------------- ### Install Zipline Reloaded with pip Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/README.md Use this command to install the Zipline Reloaded package if your system meets the prerequisites. ```bash pip install zipline-reloaded ``` -------------------------------- ### CSV Data Format Example Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/bundles.md This is an example of the expected OHLCV format for CSV files used with the `csvdir` bundle. Ensure your data includes date, open, high, low, close, volume, dividend, and split columns. ```text date,open,high,low,close,volume,dividend,split 2012-01-03,58.485714,58.92857,58.42857,58.747143,75555200,0.0,1.0 2012-01-04,58.57143,59.240002,58.468571,59.062859,65005500,0.0,1.0 2012-01-05,59.278572,59.792858,58.952858,59.718571,67817400,0.0,1.0 2012-01-06,59.967144,60.392857,59.888573,60.342857,79573200,0.0,1.0 2012-01-09,60.785713,61.107143,60.192856,60.247143,98506100,0.0,1.0 2012-01-10,60.844284,60.857143,60.214287,60.462856,64549100,0.0,1.0 2012-01-11,60.382858,60.407143,59.901428,60.364285,53771200,0.0,1.0 ``` -------------------------------- ### Defining a Pre-Trading Start Function Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/whatsnew/0.8.0.txt Define a function that will be executed once before the market opens each day. This is useful for setting up daily parameters or performing pre-market analysis. ```python def before_trading_start(context): # User-defined logic here pass ``` -------------------------------- ### Zipline Schedule Function Examples Source: https://context7.com/stefan-jansen/zipline-reloaded/llms.txt Illustrates how to use `schedule_function` to run custom functions at specific times, such as daily rebalancing, periodic analysis, or end-of-day order cancellation. Requires `date_rules` and `time_rules`. ```python from zipline.api import ( schedule_function, date_rules, time_rules, order_target_percent, symbol, get_open_orders, cancel_order ) def initialize(context): context.assets = [symbol('AAPL'), symbol('MSFT'), symbol('GOOG')] # Rebalance at market open on the first day of each month schedule_function( rebalance, date_rule=date_rules.month_start(days_offset=0), time_rule=time_rules.market_open(hours=0, minutes=30) ) # Check portfolio every day at market close schedule_function( log_portfolio, date_rule=date_rules.every_day(), time_rule=time_rules.market_close(minutes=1) ) # Weekly analysis on Fridays schedule_function( weekly_analysis, date_rule=date_rules.week_end(days_offset=0), time_rule=time_rules.market_open(hours=1) ) # Cancel unfilled orders at end of day schedule_function( cancel_open_orders, date_rule=date_rules.every_day(), time_rule=time_rules.market_close() ) def rebalance(context, data): """Equal-weight portfolio rebalancing.""" weight = 1.0 / len(context.assets) for asset in context.assets: if data.can_trade(asset): order_target_percent(asset, weight) def log_portfolio(context, data): """Log portfolio status.""" portfolio = context.portfolio print(f"Portfolio value: ${portfolio.portfolio_value:,.2f}") print(f"Cash: ${portfolio.cash:,.2f}") def weekly_analysis(context, data): """Perform weekly analysis.""" for asset in context.assets: returns = data.history(asset, 'price', 5, '1d').pct_change().dropna() print(f"{asset.symbol} weekly return: {returns.sum():.2%}") def cancel_open_orders(context, data): """Cancel all unfilled orders.""" for asset, orders in get_open_orders().items(): for order in orders: cancel_order(order) ``` -------------------------------- ### Zipline buyapple.py example algorithm Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb A basic Zipline algorithm that buys 10 shares of Apple (AAPL) at each data event. It sets a commission of 0.0075 per share and uses volume-based slippage. ```python #!/usr/bin/env python # # Copyright 2014 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from zipline.api import order, record, symbol from zipline.finance import commission, slippage def initialize(context): context.asset = symbol("AAPL") # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) def handle_data(context, data): order(context.asset, 10) record(AAPL=data.current(context.asset, "price")) # Note: this function can be removed if running ``` -------------------------------- ### Build and View Docs Locally Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md Navigate to the docs directory and run make html to build the documentation, then open the index.html file in your browser. ```bash cd docs make html {BROWSER} build/html/index.html ``` -------------------------------- ### Importing and Registering CSV Bundle Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/bundles.md Import necessary libraries and functions, define start and end sessions, and register a custom CSV directory bundle with Zipline. Ensure pandas is installed and the CSV files are in the specified directory. ```python import pandas as pd from zipline.data.bundles import register from zipline.data.bundles.csvdir import csvdir_equities ``` ```python start_session = pd.Timestamp('2016-1-1', tz='utc') end_session = pd.Timestamp('2018-1-1', tz='utc') ``` ```python register( 'custom-csvdir-bundle', csvdir_equities( ['daily'], '/path/to/your/csvs', ), calendar_name='NYSE', # US equities start_session=start_session, end_session=end_session ) ``` -------------------------------- ### Build Documentation Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/CLAUDE.md Build the project's HTML documentation. Navigate to the 'docs' directory before running this command. ```bash cd docs && make html ``` -------------------------------- ### Demean with Percentile Mask Example Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Example of using demean() with a percentile_between mask to handle outliers. ```python >>> base = MyFactor(...) >>> normalized = base.demean( ... mask=base.percentile_between(1, 99), ... ) ``` -------------------------------- ### Initialize and Run a Zipline Algorithm Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/whatsnew/0.6.1.txt Demonstrates the Quantopian-style algorithm structure using initialize and handle_data functions. ```python from datetime import datetime import pytz from zipline import TradingAlgorithm from zipline.utils.factory import load_from_yahoo from zipline.api import order def initialize(context): context.test = 10 def handle_date(context, data): order('AAPL', 10) print(context.test) if __name__ == '__main__': import pylab as pl start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc) end = datetime(2010, 1, 1, 0, 0, 0, 0, pytz.utc) data = load_from_yahoo( stocks=['AAPL'], indexes={}, start=start, end=end) data = data.dropna() algo = TradingAlgorithm( initialize=initialize, handle_data=handle_date) results = algo.run(data) results.portfolio_value.plot() pl.show() ``` -------------------------------- ### Build and View Documentation Locally Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Build the Zipline documentation locally using Sphinx and open it in a web browser. Assumes you are in the Zipline root directory. ```bash # assuming you're in the Zipline root directory $ cd docs $ make html $ {BROWSER} build/html/index.html ``` -------------------------------- ### Install Zipline Reloaded with conda Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/README.md Install Zipline Reloaded from the conda-forge channel using the conda package manager. ```bash conda install -c conda-forge zipline-reloaded ``` -------------------------------- ### AssetDBWriter.init_db(txn) Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Initializes the asset database by connecting and creating necessary tables. ```APIDOC ## init_db(txn=None) ### Description Connect to database and create tables. ### Parameters #### Request Body - **txn** (sa.engine.Connection) - Optional - The transaction block to execute in. If not provided, a new transaction is started. ### Response #### Success Response (200) - **metadata** (sa.MetaData) - The metadata that describes the new assets db. ``` -------------------------------- ### Zipline Command-Line Arguments for Benchmarks Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/releases.md These command-line arguments provide explicit options for specifying benchmark data, replacing implicit downloading. ```none --benchmark-file The csv file that contains the benchmark returns (date, returns columns) --benchmark-symbol The instrument's symbol to be used as a benchmark. (should exist in the ingested bundle) --benchmark-sid The sid of the instrument to be used as a benchmark. (should exist in the ingested bundle) --no-benchmark This flag is used to set the benchmark to zero. Alpha, beta and benchmark metrics are not calculated ``` -------------------------------- ### Download Market Data with Quandl Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/README.md Set your Quandl API key as an environment variable and ingest market data. This step is necessary before running Zipline algorithms that require historical data. ```bash $ export QUANDL_API_KEY="your_key_here" $ zipline ingest -b quandl ``` -------------------------------- ### GET zipline.api.get_open_orders Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Retrieve all of the current open orders. ```APIDOC ## GET zipline.api.get_open_orders ### Description Retrieve all of the current open orders. If an asset is provided, returns only orders for that asset. ### Parameters #### Query Parameters - **asset** (Asset) - Optional - The asset to filter open orders by. ### Response #### Success Response (200) - **open_orders** (dict[list[Order]] or list[Order]) - A dictionary mapping Assets to lists of orders, or a list of orders if an asset was specified. ``` -------------------------------- ### Define start_of_simulation Method Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/risk-and-perf-metrics.md Implement the start_of_simulation method to initialize caches and state at the beginning of a backtest. ```python def start_of_simulation(self, ledger, emission_rate, trading_calendar, sessions, benchmark_source): ... ``` -------------------------------- ### GET /zipline/finance/metrics/load Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Retrieves an instance of a registered metrics set. ```APIDOC ## GET /zipline/finance/metrics/load ### Description Returns an instance of the metrics set registered with the given name. ### Parameters #### Query Parameters - **name** (str) - Required - The name of the metrics set to load. ### Response #### Success Response (200) - **metrics** (set[Metric]) - A new instance of the metrics set. #### Error Response - **ValueError** - Raised when no metrics set is registered to the provided name. ``` -------------------------------- ### GET zipline.api.get_order Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Lookup an order based on the order id. ```APIDOC ## GET zipline.api.get_order ### Description Lookup an order based on the order id returned from one of the order functions. ### Parameters #### Query Parameters - **order_id** (str) - Required - The unique identifier for the order. ### Response #### Success Response (200) - **order** (Order) - The order object. ``` -------------------------------- ### Zipline Order Placement Functions Source: https://context7.com/stefan-jansen/zipline-reloaded/llms.txt Demonstrates various methods for placing orders, including basic share orders, value-based orders, percentage-based orders, and target-based orders. Also shows how to use limit and stop prices, execution styles, and manage orders. ```python from zipline.api import ( order, order_value, order_percent, order_target, order_target_value, order_target_percent, get_order, get_open_orders, cancel_order, symbol ) from zipline.finance.execution import LimitOrder, StopOrder, StopLimitOrder def handle_data(context, data): asset = symbol('AAPL') # Basic order: buy/sell a specific number of shares order(asset, 100) # Buy 100 shares order(asset, -50) # Sell 50 shares # Order by dollar value order_value(asset, 10000) # Buy $10,000 worth order_value(asset, -5000) # Sell $5,000 worth # Order by portfolio percentage order_percent(asset, 0.10) # Invest 10% of portfolio value # Target a specific number of shares (adjusts position) order_target(asset, 200) # Adjust position to exactly 200 shares order_target(asset, 0) # Close entire position # Target a specific dollar value order_target_value(asset, 50000) # Adjust to $50,000 position # Target a portfolio weight order_target_percent(asset, 0.25) # Adjust to 25% of portfolio # Orders with limit/stop prices order(asset, 100, limit_price=150.00) # Limit order order(asset, 100, stop_price=145.00) # Stop order order(asset, 100, limit_price=150.00, stop_price=145.00) # Stop-limit # Using execution style objects order(asset, 100, style=LimitOrder(150.00)) order(asset, 100, style=StopOrder(145.00)) order(asset, 100, style=StopLimitOrder(150.00, 145.00)) # Managing orders order_id = order(asset, 100) if order_id: order_info = get_order(order_id) print(f"Order status: {order_info.status}") # Get all open orders for an asset open_orders = get_open_orders(asset) for o in open_orders: cancel_order(o.id) # Get all open orders across all assets all_open = get_open_orders() # Returns dict: {asset: [orders]} ``` -------------------------------- ### run_pipeline Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Computes pipeline values from a start date to an end date. ```APIDOC ## POST /run_pipeline ### Description Computes values for a given pipeline from a specified start date to an end date. This is the standard method for running a Zipline pipeline. ### Method POST ### Endpoint /run_pipeline ### Parameters #### Query Parameters - **pipeline** (zipline.pipeline.Pipeline) - Required - The pipeline object to run. - **start_date** (pd.Timestamp) - Required - The start date for the computation. - **end_date** (pd.Timestamp) - Required - The end date for the computation. - **hooks** (list[implements(PipelineHooks)]) - Optional - Hooks for instrumenting Pipeline execution. ### Response #### Success Response (200) - **result** (pd.DataFrame) - A DataFrame containing the computed results. The columns of the result correspond to the entries in `pipeline.columns`. For each date between `start_date` and `end_date`, `result` will contain a row for each asset that passed `pipeline.screen`. ``` -------------------------------- ### Initialize Zipline Environment Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb Sets up the interactive environment for Zipline, loading necessary libraries like numpy and matplotlib. ```python %pylab inline figsize(12, 12) ``` -------------------------------- ### Splits API Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Get stock splits for given assets on a specific date. ```APIDOC ## get_splits(assets, dt) ### Description Returns any splits for the given sids and the given dt. ### Method GET ### Endpoint /api/assets/splits ### Parameters #### Query Parameters - **assets** (container) - Required - Assets for which we want splits. - **dt** (datetime) - Required - The date for which we are checking for splits. Note: this is expected to be midnight UTC. ### Response #### Success Response (200) - **splits** (list[tuple]) - List of splits, where each split is an (asset, ratio) tuple. ### Response Example { "splits": [ ["AAPL", 2.0], ["MSFT", 1.5] ] } ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Set up a Python virtual environment for your Zipline development. This isolates project dependencies. ```bash $ python3 -m venv venv $ source venv/bin/activate ``` -------------------------------- ### Install macOS Dependencies Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/install.md Required packages for macOS users using the Homebrew package manager. ```bash $ brew install freetype pkg-config gcc openssl hdf5 ta-lib ``` -------------------------------- ### Display Zipline Run Help Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/beginner-tutorial.md Use this command to view all available options for running a Zipline backtest. ```bash $ zipline run --help ``` -------------------------------- ### GET get_adjustments Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Retrieves a list of corporate action adjustments for specified assets between two timestamps. ```APIDOC ## GET get_adjustments ### Description Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets. ### Parameters #### Request Body - **assets** (list or Asset) - Required - The asset or assets whose adjustments are desired. - **field** (string) - Required - The desired field: 'open', 'high', 'low', 'close', 'volume', 'price', or 'last_traded'. - **dt** (pd.Timestamp) - Required - The timestamp for the desired value. - **perspective_dt** (pd.Timestamp) - Required - The timestamp from which the data is being viewed back from. ### Response #### Success Response (200) - **adjustments** (list[Adjustment]) - The list of adjustments applied to the field. ``` -------------------------------- ### zipline.api.attach_pipeline Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Registers a pipeline to be computed at the start of each day. This allows for pre-computation of complex data transformations. ```APIDOC ## POST /zipline/api/attach_pipeline ### Description Registers a pipeline to be computed at the start of each day. This allows for pre-computation of complex data transformations. ### Method POST ### Endpoint /zipline/api/attach_pipeline ### Parameters #### Request Body - **pipeline** (Pipeline) - Required - The pipeline to have computed. - **name** (str) - Required - The name of the pipeline. - **chunks** (int or iterator, optional) - The number of days to compute pipeline results for. Increasing this number will make it longer to get the first results but may improve the total runtime of the simulation. If an iterator is passed, we will run in chunks based on values of the iterator. Default is True. - **eager** (bool, optional) - Whether or not to compute this pipeline prior to before_trading_start. Default is True. ### Response #### Success Response (200) - **pipeline** (Pipeline) - Returns the pipeline that was attached unchanged. #### Response Example ```json { "pipeline": "" } ``` ``` -------------------------------- ### Zipline CLI Execution Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/whatsnew/0.7.0.txt This snippet demonstrates how to run Zipline algorithms directly from the command line. ```APIDOC ## Zipline CLI Execution ### Description Run Zipline algorithms directly from the command line. This command allows you to specify the algorithm file, symbols, date range, and output file for performance data. ### Method CLI Command ### Endpoint N/A (Command Line Interface) ### Parameters #### Command Line Arguments - **-f** (string) - Required - Path to the Python file containing the Zipline algorithm. - **--symbols** (string) - Required - Comma-separated list of stock symbols to trade. - **--start** (string) - Required - Start date for the algorithm in 'YYYY-MM-DD' format. - **--end** (string) - Required - End date for the algorithm in 'YYYY-MM-DD' format. - **-o** (string) - Optional - Path to save the performance DataFrame pickle file. ### Request Example ```bash python run_algo.py -f dual_moving_avg.py --symbols AAPL --start 2011-1-1 --end 2012-1-1 -o dma.pickle ``` ### Response #### Success Response - Performance DataFrame saved to the specified pickle file or available in memory. #### Response Example (Output is a pickle file containing a pandas DataFrame) ``` -------------------------------- ### Import necessary libraries in Python Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb Imports common libraries used in Zipline projects. Ensure these are installed. ```python import warnings import os import pandas as pd import matplotlib.pyplot as plt ``` -------------------------------- ### Build Zipline Documentation Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md Run this script to build the documentation. Ensure you are using Python 3. The script handles checking out the gh-pages branch and copying the built documentation. ```python python /docs/deploy.py ``` -------------------------------- ### default_populate_initial_workspace Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md The default implementation for populating the initial workspace, returning it without modifications. ```APIDOC ## POST /default_populate_initial_workspace ### Description Provides the default implementation for `populate_initial_workspace`. This function returns the `initial_workspace` argument without any modifications. ### Method POST ### Endpoint /default_populate_initial_workspace ### Parameters #### Request Body - **initial_workspace** (dict[array-like]) - Required - The initial workspace before populating with cached terms. - **root_mask_term** (Term) - Required - The root mask term, typically `AssetExists()`, used for computing dates. - **execution_plan** (ExecutionPlan) - Required - The execution plan for the pipeline being run. - **dates** (pd.DatetimeIndex) - Required - All dates requested in the pipeline run, including look-back windows. - **assets** (pd.Int64Index) - Required - All assets existing for the window being computed. ### Response #### Success Response (200) - **populated_initial_workspace** (dict[term, array-like]) - The workspace to begin computations with. ``` -------------------------------- ### Last Traded Datetime API Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Get the last traded datetime for an asset from the perspective of a given date. ```APIDOC ## get_last_traded_dt(asset, dt, data_frequency) ### Description Given an asset and dt, returns the last traded dt from the viewpoint of the given dt. If there is a trade on the dt, the answer is dt provided. ### Method GET ### Endpoint /api/assets/last_traded ### Parameters #### Query Parameters - **asset** (Asset) - Required - The asset for which to find the last traded datetime. - **dt** (datetime) - Required - The reference date. - **data_frequency** (string) - Required - The frequency of the data ('daily' or 'minute'). ### Response #### Success Response (200) - **last_traded_dt** (datetime) - The last traded datetime. ### Response Example { "last_traded_dt": "2023-10-26T00:00:00+00:00" } ``` -------------------------------- ### Fetcher Assets API Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Get a list of assets available for the current date as defined by the fetcher data. ```APIDOC ## get_fetcher_assets(dt) ### Description Returns a list of assets for the current date, as defined by the fetcher data. ### Method GET ### Endpoint /api/assets/fetcher ### Parameters #### Query Parameters - **dt** (datetime) - Required - The date for which to retrieve assets. ### Response #### Success Response (200) - **list** (list[Asset]) - A list of Asset objects. ### Response Example { "assets": [ { "asset_name": "AAPL", "symbol": "AAPL", "start_date": "2007-01-03T00:00:00+00:00", "end_date": "2023-10-26T00:00:00+00:00" }, { "asset_name": "MSFT", "symbol": "MSFT", "start_date": "2007-01-03T00:00:00+00:00", "end_date": "2023-10-26T00:00:00+00:00" } ] } ``` -------------------------------- ### GET /transactions Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Calculates and retrieves transactions, commissions, and closed orders based on current open orders. ```APIDOC ## GET /transactions ### Description Creates a list of transactions based on open orders, slippage, and commission models. ### Parameters #### Query Parameters - **bar_data** (zipline._protocol.BarData) - Required - Current market data. ### Response #### Success Response (200) - **transactions_list** (List) - List of resulting transactions. - **commissions_list** (List) - List of commissions incurred. - **closed_orders** (List) - List of orders that have been filled. ``` -------------------------------- ### Run Zipline via Command Line Interface Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/whatsnew/0.7.0.txt Executes a trading algorithm file from the terminal and saves the performance results to a pickle file. ```bash python run_algo.py -f dual_moving_avg.py --symbols AAPL --start 2011-1-1 --end 2012-1-1 -o dma.pickle ``` -------------------------------- ### Run Backtest with a Specific Bundle Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/bundles.md Execute a backtest using the `run` command, specifying the data bundle with the `--bundle` option. You can also use `--bundle-timestamp` to select data from a specific past ingestion date. ```bash $ zipline run --bundle --algofile algo.py ... ``` -------------------------------- ### Ingest Quandl Data Bundle using Zipline CLI Source: https://context7.com/stefan-jansen/zipline-reloaded/llms.txt Command-line instruction to ingest the default Quandl data bundle into Zipline. This prepares market data for backtesting. ```bash # Command line: Ingest the default Quandl bundle # $ zipline ingest -b quandl ``` -------------------------------- ### Get All Open Orders Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Retrieves all currently open orders. If an asset is specified, it returns only the open orders for that particular asset. ```python get_open_orders(asset=None) ``` -------------------------------- ### Test Arguments for Zipline Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb Provides default start and end dates for automated testing of zipline algorithms. Requires pandas. ```python def _test_args(): """Extra arguments to use when zipline's automated tests run this example.""" import pandas as pd return { "start": pd.Timestamp("2014-01-01", tz="utc"), "end": pd.Timestamp("2014-11-01", tz="utc"), } ``` -------------------------------- ### Execute a Backtest Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb Run a backtest for a specific algorithm file within a defined date range and save the output to a pickle file. ```python !zipline run -f ../../zipline/examples/buyapple.py --start 2016-1-1 --end 2018-1-1 -o buyapple_out.pickle --no-benchmark ``` -------------------------------- ### Upload to PyPI Test Server Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/release-process.md Use twine to upload the sdist to the test PyPI server for initial testing. You will need credentials for this. ```bash pip install twine twine upload --repository-url https://test.pypi.org/legacy/ dist/zipline-.tar.gz ``` -------------------------------- ### Compute Rolling Pearson Correlation Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Examples showing how to compute rolling Pearson correlation coefficients between asset returns and a target slice. ```python returns = Returns(window_length=10) returns_slice = returns[sid(24)] aapl_correlations = returns.pearsonr( target=returns_slice, correlation_length=30, ) ``` ```python aapl_correlations = RollingPearsonOfReturns( target=sid(24), returns_length=10, correlation_length=30, ) ``` -------------------------------- ### Zipline Run Command Options Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/beginner-tutorial.md This is the help text for the `zipline run` command, outlining various options for configuring a backtest. ```python Usage: zipline run [OPTIONS] Run a backtest for the given algorithm. Options: -f, --algofile FILENAME The file that contains the algorithm to run. -t, --algotext TEXT The algorithm script to run. -D, --define TEXT Define a name to be bound in the namespace before executing the algotext. For example '-Dname=value'. The value may be any python expression. These are evaluated in order so they may refer to previously defined names. --data-frequency [daily|minute] The data frequency of the simulation. [default: daily] --capital-base FLOAT The starting capital for the simulation. [default: 10000000.0] -b, --bundle BUNDLE-NAME The data bundle to use for the simulation. [default: quandl] --bundle-timestamp TIMESTAMP The date to lookup data on or before. [default: ] -s, --start DATE The start date of the simulation. -e, --end DATE The end date of the simulation. -o, --output FILENAME The location to write the perf data. If this is '-' the perf will be written to stdout. [default: -] --trading-calendar TRADING-CALENDAR The calendar you want to use e.g. LSE. NYSE is the default. --print-algo / --no-print-algo Print the algorithm to stdout. --benchmark-file The csv file that contains the benchmark returns (date, returns columns) --benchmark-symbol The instrument's symbol to be used as a benchmark. (should exist in the ingested bundle) --benchmark-sid The sid of the instrument to be used as a benchmark. (should exist in the ingested bundle) --no-benchmark This flag is used to set the benchmark to zero. Alpha, beta and benchmark metrics are not calculated --help Show this message and exit. ``` -------------------------------- ### Activate Conda Environment Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/install.md Activate the newly created Conda environment before installing Zipline. This command is for Conda versions 4.6 and later. ```bash $ conda activate env_zipline ``` -------------------------------- ### Execute Zipline Algorithm Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/notebooks/tutorial.ipynb Runs a backtest using the %%zipline magic command with specified start/end dates and output file. The algorithm logic follows the standard initialize and handle_data structure. ```python %%zipline --start 2016-1-1 --end 2018-1-1 -o perf_ipython.pickle --no-benchmark from zipline.api import symbol, order, record def initialize(context): context.asset = symbol('AAPL') def handle_data(context, data): order(context.asset, 10) record(AAPL=data.current(context.asset, 'price')) ``` -------------------------------- ### Run Zipline Tests with Pytest Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Execute the Zipline test suite using Pytest. Ensure TA-lib is installed and other dependencies are met. ```bash $ pytest tests ``` -------------------------------- ### List Available Zipline Bundles Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/bundles.md Run this command to see all registered data bundles and their ingestion timestamps. This helps in identifying available datasets for backtesting. ```bash $ zipline bundles ``` -------------------------------- ### GET get_adjusted_value Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Retrieves a scalar value for a specific asset field at a given timestamp, including applied corporate action adjustments. ```APIDOC ## GET get_adjusted_value ### Description Returns a scalar value representing the value of the desired asset’s field at the given dt with adjustments applied. ### Parameters #### Request Body - **asset** (Asset) - Required - The asset whose data is desired. - **field** (string) - Required - The desired field: 'open', 'high', 'low', 'close', 'volume', 'price', or 'last_traded'. - **dt** (pd.Timestamp) - Required - The timestamp for the desired value. - **perspective_dt** (pd.Timestamp) - Required - The timestamp from which the data is being viewed back from. - **data_frequency** (str) - Required - The frequency of the data to query ('daily' or 'minute'). ### Response #### Success Response (200) - **value** (float, int, or pd.Timestamp) - The adjusted value of the field. ``` -------------------------------- ### Get Transactions Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Generates a list of transactions, commissions, and closed orders based on current open orders, slippage, and commission models. ```python get_transactions(bar_data) ``` -------------------------------- ### Configure Commission and Slippage Models Source: https://context7.com/stefan-jansen/zipline-reloaded/llms.txt Defines transaction costs and market impact simulation parameters within the initialize function. Supports per-share, per-trade, and per-dollar commission models alongside volume-based or fixed slippage. ```python from zipline.api import set_commission, set_slippage from zipline.finance.commission import PerShare, PerTrade, PerDollar from zipline.finance.slippage import VolumeShareSlippage, FixedSlippage def initialize(context): # Commission models for US equities # Per-share commission (default: $0.001/share, no minimum) set_commission(us_equities=PerShare(cost=0.005, min_trade_cost=1.00)) # Flat fee per trade set_commission(us_equities=PerTrade(cost=9.99)) # Percentage of trade value set_commission(us_equities=PerDollar(cost=0.0015)) # 0.15% of trade value # Slippage models # Volume-based slippage (default model) # Limits fill to 2.5% of historical volume with 10% price impact set_slippage(us_equities=VolumeShareSlippage( volume_limit=0.025, # Max 2.5% of bar's volume price_impact=0.1 # Price impact coefficient )) # Fixed spread slippage (simpler model) set_slippage(us_equities=FixedSlippage(spread=0.01)) # $0.01 spread # For futures trading # set_commission(us_futures=PerTrade(cost=2.50)) # set_slippage(us_futures=VolumeShareSlippage(volume_limit=0.05)) ``` -------------------------------- ### Zipline Backtest Simulation Output Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/beginner-tutorial.md Example output from a Zipline backtest simulation, showing the stock symbol, simulation status, and trading day information. ```text AAPL [2018-01-03 04:30:51.843465] INFO: Performance: Simulated 503 trading days out of 503. [2018-01-03 04:30:51.843598] INFO: Performance: first open: 2016-01-04 14:31:00+00:00 [2018-01-03 04:30:51.843672] INFO: Performance: last close: 2017-12-29 21:00:00+00:00 ``` -------------------------------- ### Create a New Development Branch Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md Navigate into the cloned directory and create a new branch for your changes. ```bash $ cd zipline-reloaded $ git checkout -b some-short-descriptive-name ``` -------------------------------- ### Getting the Zipline Environment Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/whatsnew/0.8.0.txt Retrieve the current environment string, which defaults to 'zipline'. This allows algorithms to adapt behavior between Quantopian and local Zipline instances. ```python env = get_environment() if env == 'zipline': # Local Zipline specific logic pass ``` -------------------------------- ### Set QUANDL API Key Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/index.md Set the QUANDL_API_KEY environment variable to authenticate with NASDAQ Data Link for downloading market data. ```bash $ export QUANDL_API_KEY="your_key_here" ``` -------------------------------- ### Create Virtual Environment with virtualenvwrapper Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/development-guidelines.md An alternative method to create a virtual environment using the virtualenvwrapper tool. ```bash $ mkvirtualenv zipline ``` -------------------------------- ### Specialize USEquityPricing Data Set Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Demonstrates specializing a generic data set (EquityPricing) for a specific domain (US_EQUITIES). Requires importing the domain object. ```python from zipline.pipeline.domain import US_EQUITIES USEquityPricing = EquityPricing.specialize(US_EQUITIES) ``` -------------------------------- ### Compute Average Dollar Volume Source: https://github.com/stefan-jansen/zipline-reloaded/blob/main/docs/source/api-reference.md Example of overriding the compute method for a custom factor. This specific implementation calculates the average dollar volume over a specified window. ```python def compute(today, assets, out, close, volume): """Override this method with a function that writes a value into out.""" ```