Convert Figma logo to code with AI

gbeced logopyalgotrade

Python Algorithmic Trading Library

4,391
1,386
4,391
51

Top Related Projects

17,609

Zipline, a Pythonic Algorithmic Trading Library

Python Backtesting library for trading strategies

An Algorithmic Trading Library for Crypto-Assets in Python

13,247

Download market data from Yahoo! Finance's API

Python wrapper for TA-Lib (http://ta-lib.org/).

2,172

bt - flexible backtesting for Python

Quick Overview

PyAlgoTrade is an open-source Python library for backtesting stock trading strategies. It provides a framework for developing and testing algorithmic trading strategies, offering features like event-driven architecture, real-time trading support, and technical analysis tools.

Pros

  • Comprehensive backtesting capabilities for stock trading strategies
  • Supports both historical and real-time data
  • Includes built-in technical analysis indicators and chart plotting
  • Extensible architecture allowing for custom strategy development

Cons

  • Limited to stock trading, not suitable for other asset classes
  • Documentation could be more extensive and up-to-date
  • Learning curve can be steep for beginners
  • Less active development compared to some other trading libraries

Code Examples

  1. Creating a simple moving average crossover strategy:
from pyalgotrade import strategy
from pyalgotrade.technical import ma

class MACrossover(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, short_period, long_period):
        super(MACrossover, self).__init__(feed, 1000)
        self.__instrument = instrument
        self.__position = None
        self.__short_sma = ma.SMA(feed[instrument].getCloseDataSeries(), short_period)
        self.__long_sma = ma.SMA(feed[instrument].getCloseDataSeries(), long_period)

    def onBars(self, bars):
        if self.__short_sma[-1] is None or self.__long_sma[-1] is None:
            return

        if self.__short_sma[-1] > self.__long_sma[-1] and self.__position is None:
            self.__position = self.enterLong(self.__instrument, 100)
        elif self.__short_sma[-1] < self.__long_sma[-1] and self.__position is not None:
            self.__position.exitMarket()
            self.__position = None
  1. Running a backtest:
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed

# Load data
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Create and run the strategy
myStrategy = MACrossover(feed, "orcl", 10, 30)
myStrategy.run()

# Plot the results
plt = plotter.StrategyPlotter(myStrategy)
plt.plot()
  1. Accessing technical indicators:
from pyalgotrade.technical import rsi

# Calculate RSI
rsi_series = rsi.RSI(feed["orcl"].getCloseDataSeries(), 14)
rsi_value = rsi_series[-1]

Getting Started

To get started with PyAlgoTrade:

  1. Install the library:

    pip install pyalgotrade
    
  2. Import required modules:

    from pyalgotrade import strategy
    from pyalgotrade.barfeed import yahoofeed
    
  3. Create a strategy class inheriting from strategy.BacktestingStrategy

  4. Implement the onBars method to define your trading logic

  5. Load data and run the backtest:

    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("symbol", "data.csv")
    myStrategy = MyStrategy(feed, "symbol")
    myStrategy.run()
    

Competitor Comparisons

17,609

Zipline, a Pythonic Algorithmic Trading Library

Pros of Zipline

  • More comprehensive and feature-rich backtesting framework
  • Better integration with Pandas for data manipulation
  • Larger community and more active development

Cons of Zipline

  • Steeper learning curve due to its complexity
  • Heavier resource usage, potentially slower for simple strategies

Code Comparison

PyAlgoTrade:

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__position = None
        self.__instrument = instrument

    def onBars(self, bars):
        if self.__position is None:
            self.__position = self.enterLong(self.__instrument, 100)

Zipline:

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

def handle_data(context, data):
    if context.portfolio.positions[context.asset].amount == 0:
        order_target_percent(context.asset, 1.0)

Both frameworks allow for strategy implementation, but Zipline's approach is more concise and integrates better with Pandas data structures. PyAlgoTrade's syntax is more explicit, which might be easier for beginners to understand. Zipline's initialize and handle_data functions provide a clearer separation of setup and trading logic.

Python Backtesting library for trading strategies

Pros of Backtrader

  • More active development and larger community support
  • Extensive documentation and examples
  • Flexible architecture allowing for easy customization and extension

Cons of Backtrader

  • Steeper learning curve for beginners
  • Can be slower for large datasets compared to PyAlgoTrade

Code Comparison

PyAlgoTrade:

from pyalgotrade import strategy
from pyalgotrade.technical import ma

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)

Backtrader:

import backtrader as bt

class MyStrategy(bt.Strategy):
    params = (('period', 15),)
    
    def __init__(self):
        self.sma = bt.indicators.SimpleMovingAverage(period=self.params.period)

Both frameworks offer similar functionality for implementing trading strategies, but Backtrader's syntax is generally more concise and intuitive. PyAlgoTrade uses a more traditional object-oriented approach, while Backtrader leverages Python's decorators and built-in methods for a more streamlined experience.

An Algorithmic Trading Library for Crypto-Assets in Python

Pros of Catalyst

  • More comprehensive ecosystem for crypto trading, including data feeds and exchanges
  • Supports live trading in addition to backtesting
  • Active development and community support

Cons of Catalyst

  • Steeper learning curve due to more complex architecture
  • Limited to cryptocurrency markets, unlike PyAlgoTrade's broader scope
  • Requires more setup and configuration for full functionality

Code Comparison

Catalyst example:

from catalyst import run_algorithm

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

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

run_algorithm(capital_base=10000, data_frequency='daily', initialize=initialize, handle_data=handle_data)

PyAlgoTrade example:

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.marketOrder(self.__instrument, 1)

feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()
13,247

Download market data from Yahoo! Finance's API

Pros of yfinance

  • Simpler API for fetching financial data from Yahoo Finance
  • More actively maintained with frequent updates
  • Supports downloading multiple symbols in a single call

Cons of yfinance

  • Limited to Yahoo Finance data only
  • Lacks built-in backtesting and strategy evaluation tools
  • No support for real-time data streaming

Code Comparison

yfinance:

import yfinance as yf

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

PyAlgoTrade:

from pyalgotrade.barfeed import yahoofeed
from pyalgotrade import strategy

feed = yahoofeed.Feed()
feed.addBarsFromCSV("AAPL", "apple.csv")

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info(bar.getClose())

myStrategy = MyStrategy(feed, "AAPL")
myStrategy.run()

PyAlgoTrade offers a more comprehensive framework for backtesting and strategy implementation, while yfinance focuses on simple data retrieval from Yahoo Finance. yfinance is easier to use for quick data access, but PyAlgoTrade provides more tools for advanced algorithmic trading strategies.

Python wrapper for TA-Lib (http://ta-lib.org/).

Pros of ta-lib-python

  • Extensive library of technical analysis functions
  • Highly optimized C implementation for performance
  • Well-established and widely used in the financial industry

Cons of ta-lib-python

  • Requires separate installation of TA-Lib C library
  • Less focus on backtesting and strategy development
  • Steeper learning curve for beginners

Code Comparison

ta-lib-python:

import talib
import numpy as np

close = np.random.random(100)
output = talib.SMA(close, timeperiod=10)

PyAlgoTrade:

from pyalgotrade import strategy
from pyalgotrade.technical import ma

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 10)

ta-lib-python focuses on providing a wide range of technical indicators, while PyAlgoTrade offers a more comprehensive framework for backtesting and strategy development. ta-lib-python is better suited for advanced users who need high-performance technical analysis functions, while PyAlgoTrade provides an easier entry point for beginners looking to develop and test trading strategies.

2,172

bt - flexible backtesting for Python

Pros of bt

  • More active development with recent updates
  • Flexible and extensible architecture
  • Better documentation and examples

Cons of bt

  • Steeper learning curve for beginners
  • Less comprehensive built-in indicators and strategies

Code Comparison

bt:

import bt

data = bt.get('spy,agg', start='2010-01-01')
s = bt.Strategy('s1', [bt.algos.RunMonthly(),
                       bt.algos.SelectAll(),
                       bt.algos.WeighEqually(),
                       bt.algos.Rebalance()])
test = bt.Backtest(s, data)
res = bt.run(test)

PyAlgoTrade:

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info(bar.getClose())

feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()

Both libraries offer backtesting capabilities, but bt provides a more concise and flexible approach, while PyAlgoTrade offers a more traditional object-oriented structure. bt's code is more readable and requires less boilerplate, making it easier to prototype strategies quickly.

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

PyAlgoTrade


This project is deprecated and is no longer mantained. You may be interested in taking a look at Basana.


Build Status Coverage Status

PyAlgoTrade is an event driven algorithmic trading Python library. Although the initial focus was on backtesting, paper trading is now possible using:

and live trading is now possible using:

To get started with PyAlgoTrade take a look at the tutorial and the full documentation.

Main Features

  • Event driven.
  • Supports Market, Limit, Stop and StopLimit orders.
  • Supports any type of time-series data in CSV format like Yahoo! Finance, Google Finance, Quandl and NinjaTrader.
  • Bitcoin trading support through Bitstamp.
  • Technical indicators and filters like SMA, WMA, EMA, RSI, Bollinger Bands, Hurst exponent and others.
  • Performance metrics like Sharpe ratio and drawdown analysis.
  • Handling Twitter events in realtime.
  • Event profiler.
  • TA-Lib integration.

Installation

PyAlgoTrade is developed and tested using Python 2.7/3.7 and depends on:

You can install PyAlgoTrade using pip like this:

pip install pyalgotrade