Convert Figma logo to code with AI

quantopian logozipline

Zipline, a Pythonic Algorithmic Trading Library

17,609
4,718
17,609
364

Top Related Projects

9,713

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

15,357

Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.

13,247

Download market data from Yahoo! Finance's API

An Algorithmic Trading Library for Crypto-Assets in Python

Python Backtesting library for trading strategies

Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

Quick Overview

Zipline is an open-source algorithmic trading simulator written in Python. It provides a robust and flexible platform for backtesting trading strategies, allowing users to simulate trading in historical market conditions with realistic constraints and transaction costs.

Pros

  • Comprehensive backtesting framework with support for various asset classes
  • Integration with Quantopian's research environment and data sources
  • Extensible architecture allowing for custom data sources and metrics
  • Active community and ongoing development

Cons

  • Steep learning curve for beginners
  • Limited real-time trading capabilities
  • Dependency on external data sources for market data
  • Performance can be slow for large datasets or complex strategies

Code Examples

  1. Creating a simple moving average crossover strategy:
from zipline.api import order_target, record, symbol
from zipline.finance import commission, slippage

def initialize(context):
    context.asset = symbol('AAPL')
    context.short_ma = 50
    context.long_ma = 200

def handle_data(context, data):
    short_mavg = data.history(context.asset, 'price', context.short_ma, '1d').mean()
    long_mavg = data.history(context.asset, 'price', context.long_ma, '1d').mean()

    if short_mavg > long_mavg:
        order_target(context.asset, 100)
    elif short_mavg < long_mavg:
        order_target(context.asset, -100)

    record(short_mavg=short_mavg, long_mavg=long_mavg)
  1. Adding custom transaction costs:
def initialize(context):
    context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0))
    context.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
  1. Accessing fundamental data:
def handle_data(context, data):
    current_price = data.current(context.asset, 'price')
    pe_ratio = data.current(context.asset, 'pe_ratio')
    
    if pe_ratio < 15 and current_price < 100:
        order_target_percent(context.asset, 0.1)

Getting Started

To get started with Zipline:

  1. Install Zipline:
pip install zipline
  1. Create a new Python file (e.g., my_algorithm.py) and define your trading strategy:
from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))
  1. Run the backtest:
zipline run -f my_algorithm.py --start 2020-1-1 --end 2021-1-1 -o results.pickle
  1. Analyze the results using Pandas:
import pandas as pd
results = pd.read_pickle('results.pickle')
print(results.head())

Competitor Comparisons

9,713

Lean Algorithmic Trading Engine by QuantConnect (Python, C#)

Pros of Lean

  • More active development and larger community support
  • Supports multiple asset classes (stocks, forex, crypto, options)
  • Offers cloud-based backtesting and live trading capabilities

Cons of Lean

  • Steeper learning curve due to more complex architecture
  • Requires more setup and configuration compared to Zipline

Code Comparison

Zipline example:

from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

Lean example:

public class BasicTemplateAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2013, 10, 7);
        SetEndDate(2013, 10, 11);
        SetCash(100000);
        AddEquity("SPY", Resolution.Minute);
    }

    public override void OnData(Slice data)
    {
        if (!Portfolio.Invested)
        {
            SetHoldings("SPY", 1);
        }
    }
}

Both frameworks offer powerful backtesting capabilities, but Lean provides a more comprehensive ecosystem for algorithmic trading. Zipline is simpler to use and focuses primarily on US equities, while Lean offers multi-asset support and cloud-based features. The choice between the two depends on the trader's specific needs and level of expertise.

15,357

Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.

Pros of qlib

  • More comprehensive and feature-rich, offering advanced machine learning capabilities for quantitative investment
  • Actively maintained with frequent updates and a growing community
  • Supports a wider range of data sources and asset classes

Cons of qlib

  • Steeper learning curve due to its complexity and extensive features
  • May be overkill for simpler trading strategies or backtesting needs
  • Requires more computational resources for advanced ML models

Code Comparison

qlib example:

from qlib.contrib.model.pytorch_lstm import LSTMModel
from qlib.contrib.data.handler import Alpha158
from qlib.workflow import R

model = LSTMModel()
dataset = Alpha158()
R.run(model=model, dataset=dataset)

zipline example:

from zipline.api import order, record, symbol
from zipline.algorithm import TradingAlgorithm

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data)
13,247

Download market data from Yahoo! Finance's API

Pros of yfinance

  • Lightweight and easy to use for fetching financial data
  • Provides access to a wide range of Yahoo Finance data
  • Actively maintained and frequently updated

Cons of yfinance

  • Limited to Yahoo Finance data, which may not be as comprehensive as other sources
  • Lacks advanced backtesting and algorithmic trading capabilities
  • May experience occasional issues due to changes in Yahoo Finance's API

Code Comparison

yfinance

import yfinance as yf

ticker = yf.Ticker("AAPL")
data = ticker.history(period="1mo")
print(data.head())

Zipline

from zipline.api import order, record, symbol
from zipline.finance import commission, slippage

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

Summary

yfinance is a simple and efficient library for fetching financial data from Yahoo Finance, while Zipline is a more comprehensive backtesting and algorithmic trading library. yfinance is easier to use for quick data retrieval, but Zipline offers more advanced features for developing and testing trading strategies.

An Algorithmic Trading Library for Crypto-Assets in Python

Pros of Catalyst

  • Supports cryptocurrency trading and backtesting
  • Offers real-time trading capabilities
  • Includes built-in data sources for crypto exchanges

Cons of Catalyst

  • Less active development and community support
  • More limited documentation compared to Zipline
  • Narrower focus on cryptocurrency markets

Code Comparison

Zipline example:

from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

Catalyst example:

from catalyst.api import order, record, symbol

def initialize(context):
    context.asset = symbol('btc_usdt')

def handle_data(context, data):
    order(context.asset, 0.1)
    record(BTC=data.current(context.asset, 'price'))

Both frameworks use similar syntax for basic operations, but Catalyst focuses on cryptocurrency pairs instead of traditional stock symbols. The main difference lies in the assets being traded and the data sources used.

Python Backtesting library for trading strategies

Pros of Backtrader

  • More flexible and customizable, allowing for easier implementation of complex trading strategies
  • Supports a wider range of data sources and formats
  • Active community and regular updates

Cons of Backtrader

  • Steeper learning curve, especially for beginners
  • Less comprehensive documentation compared to Zipline
  • Slower performance for large datasets or complex strategies

Code Comparison

Backtrader:

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.sma = bt.indicators.SimpleMovingAverage(self.data.close, period=20)

    def next(self):
        if self.data.close[0] > self.sma[0]:
            self.buy()
        elif self.data.close[0] < self.sma[0]:
            self.sell()

Zipline:

def initialize(context):
    context.asset = symbol('AAPL')
    context.sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20)

def handle_data(context, data):
    sma = context.sma.compute(data)[context.asset]
    if data.current(context.asset, 'close') > sma:
        order_target_percent(context.asset, 1)
    elif data.current(context.asset, 'close') < sma:
        order_target_percent(context.asset, -1)

Both Backtrader and Zipline are popular backtesting frameworks for algorithmic trading. Backtrader offers more flexibility and customization options, while Zipline provides a more structured approach with better performance for large datasets. The choice between the two depends on the specific requirements of your trading strategy and your level of experience with backtesting frameworks.

Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

Pros of finmarketpy

  • More focused on financial market analysis and trading strategies
  • Includes tools for backtesting, market data analysis, and trade execution
  • Actively maintained with recent updates

Cons of finmarketpy

  • Smaller community and less documentation compared to Zipline
  • Narrower scope, primarily focused on financial markets

Code Comparison

finmarketpy:

from finmarketpy.backtest import Backtest
from finmarketpy.economics import Market

market = Market(market_data='path/to/data.csv')
backtest = Backtest(market, strategy=my_strategy)
results = backtest.run()

Zipline:

from zipline.api import order, record, symbol
from zipline import run_algorithm

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

run_algorithm(start=start_date, end=end_date, initialize=initialize, handle_data=handle_data)

Both libraries offer backtesting capabilities, but Zipline provides a more structured approach with predefined functions like initialize and handle_data. finmarketpy offers more flexibility in terms of market data input and strategy implementation. Zipline has a larger ecosystem and more extensive documentation, making it easier for beginners to get started. However, finmarketpy's focus on financial markets may be more suitable for specific trading and analysis tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://media.quantopian.com/logos/open_source/zipline-logo-03_.png :target: https://www.zipline.io :width: 212px :align: center :alt: Zipline

=============

|Gitter| |pypi version status| |pypi pyversion status| |travis status| |appveyor status| |Coverage Status|

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backtesting and live-trading engine powering Quantopian <https://www.quantopian.com>_ -- a free, community-centered, hosted platform for building and executing trading strategies. Quantopian also offers a fully managed service for professionals <https://factset.quantopian.com>_ that includes Zipline, Alphalens, Pyfolio, FactSet data, and more.

  • Join our Community! <https://groups.google.com/forum/#!forum/zipline>_
  • Documentation <https://www.zipline.io>_
  • Want to Contribute? See our Development Guidelines <https://www.zipline.io/development-guidelines>_

Features

  • Ease of Use: Zipline tries to get out of your way so that you can focus on algorithm development. See below for a code example.
  • "Batteries Included": many common statistics like moving average and linear regression can be readily accessed from within a user-written algorithm.
  • PyData Integration: Input of historical data and output of performance statistics are based on Pandas DataFrames to integrate nicely into the existing PyData ecosystem.
  • Statistics and Machine Learning Libraries: You can use libraries like matplotlib, scipy, statsmodels, and sklearn to support development, analysis, and visualization of state-of-the-art trading systems.

Installation

Zipline currently supports Python 2.7, 3.5, and 3.6, and may be installed via either pip or conda.

Note: Installing Zipline is slightly more involved than the average Python package. See the full Zipline Install Documentation_ for detailed instructions.

For a development installation (used to develop Zipline itself), create and activate a virtualenv, then run the etc/dev-install script.

Quickstart

See our getting started tutorial <https://www.zipline.io/beginner-tutorial>_.

The following code implements a simple dual moving average algorithm.

.. code:: python

from zipline.api import order_target, record, symbol

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


def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 300:
        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=100, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()

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

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

You can then run this algorithm using the Zipline CLI. First, you must download some sample pricing and asset data:

.. code:: bash

$ zipline ingest
$ zipline run -f dual_moving_average.py --start 2014-1-1 --end 2018-1-1 -o dma.pickle --no-benchmark

This will download asset pricing data data sourced from Quandl, and stream it through the algorithm over the specified time range. Then, the resulting performance DataFrame is saved in dma.pickle, which you can load and analyze from within Python.

You can find other examples in the zipline/examples directory.

Questions?

If you find a bug, feel free to open an issue <https://github.com/quantopian/zipline/issues/new>_ and fill out the issue template.

Contributing

All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome. Details on how to set up a development environment can be found in our development guidelines <https://www.zipline.io/development-guidelines>_.

If you are looking to start working with the Zipline codebase, navigate to the GitHub issues tab and start looking through interesting issues. Sometimes there are issues labeled as Beginner Friendly <https://github.com/quantopian/zipline/issues?q=is%3Aissue+is%3Aopen+label%3A%22Beginner+Friendly%22>_ or Help Wanted <https://github.com/quantopian/zipline/issues?q=is%3Aissue+is%3Aopen+label%3A%22Help+Wanted%22>_.

Feel free to ask questions on the mailing list <https://groups.google.com/forum/#!forum/zipline>_ or on Gitter <https://gitter.im/quantopian/zipline>_.

.. note::

Please note that Zipline is not a community-led project. Zipline is maintained by the Quantopian engineering team, and we are quite small and often busy.

Because of this, we want to warn you that we may not attend to your pull request, issue, or direct mention in months, or even years. We hope you understand, and we hope that this note might help reduce any frustration or wasted time.

.. |Gitter| image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/quantopian/zipline?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge .. |pypi version status| image:: https://img.shields.io/pypi/v/zipline.svg :target: https://pypi.python.org/pypi/zipline .. |pypi pyversion status| image:: https://img.shields.io/pypi/pyversions/zipline.svg :target: https://pypi.python.org/pypi/zipline .. |travis status| image:: https://travis-ci.org/quantopian/zipline.svg?branch=master :target: https://travis-ci.org/quantopian/zipline .. |appveyor status| image:: https://ci.appveyor.com/api/projects/status/3dg18e6227dvstw6/branch/master?svg=true :target: https://ci.appveyor.com/project/quantopian/zipline/branch/master .. |Coverage Status| image:: https://coveralls.io/repos/quantopian/zipline/badge.svg :target: https://coveralls.io/r/quantopian/zipline

.. _Zipline Install Documentation : https://www.zipline.io/install