PyAlgoTrade Documentation

repository·master·Indexed 26 days ago

https://github.com/gbeced/pyalgotrade

An event-driven algorithmic trading library for Python used for backtesting, paper trading, and live trading. It supports Market, Limit, Stop, and StopLimit orders, and provides integration for Bitcoin trading via Bitstamp. The library includes technical analysis indicators (SMA, WMA, EMA, RSI, Bollinger Bands, Hurst exponent), performance metrics like the Sharpe ratio, and bar feeds for CSV, Yahoo! Finance, Google Finance, Quandl, and NinjaTrader. Note: The project is deprecated and compatible with Python 2.7 and 3.7.

Tokens
6.6K
Snippets
4
Records
69
Agent score
88%

What's inside PyAlgoTrade

  1. Overview of PyAlgoTrade features

    master

    PyAlgoTrade is an event-driven algorithmic trading library designed for backtesting, paper trading, and live trading.

    Key capabilities include:

    • Order Types: Supports Market, Limit, Stop, and StopLimit orders.
    • Data Support: Accepts time-series data in CSV format (e.g., Yahoo! Finance, Google Finance, Quandl, NinjaTrader).
    • Trading Support: Bitcoin trading via Bitstamp (for paper and live trading).
    • Technical Analysis: Includes indicators like SMA, WMA, EMA, RSI, Bollinger Bands, and Hurst exponent, with TA-Lib integration.
    • Metrics: Provides performance metrics such as Sharpe ratio and drawdown analysis.
    • Real-time Events: Handles Twitter events in real-time and includes an event profiler.
  2. Core components of PyAlgoTrade

    master

    PyAlgoTrade is composed of six main components:

    • Strategies: Classes you define to implement trading logic (e.g., when to buy or sell).
    • Feeds: Data providing abstractions (e.g., CSV feeds for bar data, or Twitter feeds for event-based trading).
    • Brokers: Responsible for executing orders.
    • DataSeries: Abstractions used to manage time series data.
    • Technicals: Filters (modeled as DataSeries decorators) used to perform calculations on DataSeries, such as SMA (Simple Moving Average) or RSI (Relative Strength Index).
    • Optimizer: Classes that allow for horizontal scaling by distributing backtesting across different processes or computers.
  3. Use basic feeds for time series data

    master
    Feeds provide abstractions for time series data. When included in the event dispatch loop, they emit events as new data becomes available and are responsible for updating the DataSeries associated with each piece of data provided by the feed. For bar-specific data, refer to the bar feed documentation.
  4. Use Strategy Analyzers to attach calculations to strategy executions

    master
    Strategy analyzers in pyalgotrade.stratanalyzer provide an extensible framework to attach various performance and statistical calculations to your strategy executions. You can use the base StrategyAnalyzer class or its specialized implementations to monitor strategy performance.
  5. Install dependencies for Twitter support

    master
    To use Twitter events within your PyAlgoTrade strategies, you must have the tweepy library installed. Note that Twitter support provides a real-time feed, which is intended for paper trading or real trading scenarios; it is not supported during backtesting.
  6. Plot strategy execution with StrategyPlotter

    master

    PyAlgoTrade allows you to visualize strategy execution by attaching a StrategyPlotter to your strategy during the run. To plot a strategy, you typically follow these steps:

    1. Load a data feed (e.g., from a CSV file).
    2. Run the strategy using the bars supplied by the feed, ensuring a StrategyPlotter is attached.
    3. Call the plotting method to generate the visualization.

    Below is a complete example of a strategy execution that includes plotting.

  7. Optimize strategies using pyalgotrade.optimizer.worker and server

    master

    For distributed optimization across multiple machines, use a server-worker architecture:

    1. Server: Run a script that uses a server module to provide bars and parameter combinations to workers, and records results. It listens for incoming connections (e.g., on port 5000).
    2. Worker: Run one or more worker scripts using the pyalgotrade.optimizer.worker module. Workers connect to the server, receive parameters and data, run the strategy, and report results back.

    Note: Run only one server and one or more workers.

  8. Switch from Paper Trading to Live Trading on Bitstamp

    master

    When moving from a simulated environment to real execution on Bitstamp, replace the broker implementation:

    • Paper Trading: Use pyalgotrade.bitstamp.broker.PaperTradingBroker.
    • Live Trading: Use pyalgotrade.bitstamp.broker.LiveBroker.

    Warning: Live trading involves real financial risk. Ensure you have thoroughly backtested and paper traded your strategy before using LiveBroker.

  9. Integrate Quandl CSV time-series data into a strategy

    master
    You can integrate price data combined with any time-series data in CSV format from Quandl into a PyAlgoTrade strategy. This allows you to use external datasets (like gold prices or economic indicators) alongside standard market data to drive trading logic.
  10. Use TA-Lib indicators with DataSeries

    master

    The pyalgotrade.talibext.indicator module allows you to call TA-Lib functions directly using pyalgotrade.dataseries.DataSeries or pyalgotrade.dataseries.bards.BarDataSeries instances instead of raw numpy arrays.

    Each function in this module typically receives one or more dataseries and the number of values to use from those series.

    • If the parameter name is ds, pass a pyalgotrade.dataseries.DataSeries instance.
    • If the parameter name is barDs, pass a pyalgotrade.dataseries.bards.BarDataSeries instance.
    def onBars(self, bars):
        # Example using DataSeries (close prices)
        closeDs = self.getFeed().getDataSeries("orcl").getCloseDataSeries()
        upper, middle, lower = pyalgotrade.talibext.indicator.BBANDS(closeDs, 100, matype=talib.MA_T3)
        if upper != None:
            print "%s" % upper[-1]
    
        # Example using BarDataSeries
        barDs = self.getFeed().getDataSeries("orcl")
        sar = indicator.SAR(barDs, 100)
        if sar != None:
            print "%s" % sar[-1]