Python Algorithmic Trading Library

Related tags

Finance pyalgotrade
Overview

PyAlgoTrade

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
Comments
  • Optimizing code fail in 0.13

    Optimizing code fail in 0.13

    Pip install PyAlgoTrade 0.13

    When running the Optimizing examples from tutorial, code crashes systems.

    First ran as server and client on same machine. started server first, then client. Code ran for a bit,then system crashes... There is no logging for post mortem of code.

    Second, Ran single file started up, but again crashed entire system.

    Running OpenSuse 12.2, The both CPU were pinned @100%. No issue with memory.

    opened by BMeridian 22
  • Python 2 to 3 Errors with Proposed Fixes (Getting Started)

    Python 2 to 3 Errors with Proposed Fixes (Getting Started)

    Just did the getting started tutorial, and here are the errors that I got because of using Python 3. Unless I'm using the 2to3 tool wrong, there may be a few syntactic issues in the code (for Python 3 atleast). tools/yahoofinance.py:

    Line 21: Current: import urllib2 Error: urllib2 module cannot be found Reason: Since I'm using Python 3, urllib2 is no apart of urllib, and urllib is split up into different modules, specifically urllib.request and urllib.errors. My change: import urllib.request as urllib2

    Line 130: Current:except Exception, e Error: invalid syntax Reason: Python 3 semantics My change: except Exception as e

    Line 48: Current: while not buff[0].isalnum() Error: 'int' object does not have attribute isalnum() Reason: isalnum() is only applicable to strings. My change: while not str(buff[0]).isalbum()

    Line 67: Current: f.write(bars) Error: TypeError: must be str, not bytes Reason: See error My change: f.write(str(bars))

    After that compiled, I went over to the actual strategy code. Here's my list of changes to the errors received:

    utils/csvutils.py

    line 30: Current: self.__fieldNames = self.reader.next() Error: AttributeError: '_csv.reader' object has no attribute 'next' Reason: Python 3 changes My change: ```self.__fieldNames = next(self.reader())

    More to come later...

    opened by drshrey 17
  • How to trade intraday

    How to trade intraday

    Hi,

    If a I have a file of intraday data that spans several days. What I would like to do is to calculate sma on each day, and only start trading when sma for one day start to have value. In short, I would like to trade in each day seperately on sma, but I would like to keep the trading statistics in the same Strategy object.

    Right now, if I supply a feed with many days' intraday data into feed

      feed = ninjatraderfeed.Feed(Frequency.MINUTE)
      feed.addBarsFromCSV(instrument, 'index_f.csv')
    

    then I do this in the Strategy object,

       self.slow_ma = ma.SMA(feed[instrument].getCloseDataSeries(), slow_window)
       self.fast_ma = ma.SMA(feed[instrument].getCloseDataSeries(), fast_window)
    

    I would like to confirm if this SMA calculation starts each day fresh? My experiment shows it doent. If it doesnt, how do I make it calculate SMA each day fresh, so if my fast_window = 5, each day I will have 4 None values at the beginning of the DataSeries self.fast_ma

    opened by tesla1060 8
  • import quandl

    import quandl

    I used "pip install Quandl" This what I get:

    from pyalgotrade.tools import quandl
    

    ImportError: cannot import name quandl

    I already install Quandl and pyalgotrade. I am using windows 8. Why is not working?

    opened by LastAncientOne 7
  • Tutorial: download orcl-2000.csv fail, HTTP url not found

    Tutorial: download orcl-2000.csv fail, HTTP url not found

    I execute this command: $ python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')" And receive error:

    Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/site-packages/pyalgotrade/tools/yahoofinance.py", line 54, in download_daily_bars bars = download_csv(instrument, datetime.date(year, 1, 1), datetime.date(year, 12, 31), "d") File "/usr/local/lib/python2.7/site-packages/pyalgotrade/tools/yahoofinance.py", line 40, in download_csv return csvutils.download_csv(url) File "/usr/local/lib/python2.7/site-packages/pyalgotrade/utils/csvutils.py", line 59, in download_csv response.raise_for_status() File "/usr/local/lib/python2.7/site-packages/requests/models.py", line 929, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://ichart.finance.yahoo.com/table.csv?s=orcl&a=0&b=1&c=2000&d=11&e=31&f=2000&g=d&ignore=.csv

    How's that going?

    opened by RavenUP 6
  • Update: Add setShares method for back-testing broker

    Update: Add setShares method for back-testing broker

    Hi, Nice to see you, gbeced! Thanks for you great project which helps me work faster.

    Sometimes we need to give the man some initial "btc" to do the trade, not only the cash. So I made this PR : )

    Best Regards, winkidney

    opened by winkidney 6
  • What does SMA mean when using Frequency.TRADE?

    What does SMA mean when using Frequency.TRADE?

    I'm confused about sample code in http://gbeced.github.io/pyalgotrade/docs/v0.18/html/bitstamp_example.html

    usually, when I use Frequency.DAY and SMA(10) it means 10 days average price. What does SMA(10) mean when using Frequency.TRADE?

    and how to use daily SMA in a barfeed with Frequency.TRADE?

    opened by ericyue 6
  • Allow broker tests to be re-used across different broker implementations.

    Allow broker tests to be re-used across different broker implementations.

    Here we split broker_backtesting_test module into two separate files, one with tests specific the backtesting broker and another with tests can be used with different broker implementations.

    opened by j-white 6
  • Minute Tickdata

    Minute Tickdata

    What is the best way / proper way to get minute tickdata in as csv. Any special rules on the time format or colums placments?

    Is there any specific way to pull in a numpy array instead?

    opened by jcrubino 6
  • Runtime Warnings from matplotlib in SMA crossover sample

    Runtime Warnings from matplotlib in SMA crossover sample

    Hi, I started experimenting with pyalgotrade today. I used the SMA crossover strategy sample posted here: http://gbeced.github.io/pyalgotrade/docs/v0.16/html/sample_sma_crossover.html I added a print pyalgotrade.__version__(the 0.16 output below). Plots are similar to your web site on my end. I receive the following RuntimeWarning however and I am therefore wondering what I am doing wrong?

    My guess is that data is missing in the early periods of the MA. For reference, this is a Win7 PC with python 2.7.

    Best regards, Matthias

    C:\dvl\pybacktest_comparison>python pyalgo_sample.py
    0.16
    Sharpe ratio: 1.12
    C:\Anaconda\lib\site-packages\matplotlib\transforms.py:644: RuntimeWarning: invalid value encountered in sign
      dx0 = np.sign(vertices[:, 0] - x0)
    C:\Anaconda\lib\site-packages\matplotlib\transforms.py:645: RuntimeWarning: invalid value encountered in sign
      dy0 = np.sign(vertices[:, 1] - y0)
    C:\Anaconda\lib\site-packages\matplotlib\transforms.py:646: RuntimeWarning: invalid value encountered in sign
      dx1 = np.sign(vertices[:, 0] - x1)
    C:\Anaconda\lib\site-packages\matplotlib\transforms.py:647: RuntimeWarning: invalid value encountered in sign
      dy1 = np.sign(vertices[:, 1] - y1)
    
    opened by MatthiasKauer 5
  • Remove methods .get and .set

    Remove methods .get and .set

    Hey:

    Restarted working on this again and using the .getXXX and .setXXX getting in the way of sorts. Are you planning or were you considering removing the method leader of "get" and "set." Its not pythonic, its more java-ish...

    Using snippets from tutorial: Now: def onStart(self): print "Initial portfolio value: $%.2f" % self.getBroker().getEquity()

    New could be: def onStart(self): print "Initial portfolio value: $%.2f" % self.broker().equity()

    Now: def onEnterOk(self, position): execInfo = position.getEntryOrder().getExecutionInfo() print "%s: BUY at $%.2f" % (execInfo.getDateTime(), execInfo.getPrice())

    New could be: def onEnterOk(self, position): execInfo = position.entryOrder().executionInfo() print "%s: BUY at $%.2f" % (execInfo.dateTime(), execInfo.price())

    A way to accomlish this would be: to create new 'defs' in the current classes with the shorten names. and then wrapper orginal functions.

    or better yet. Create new def's with shorter names then call new function with old name.

    Example

    def richQuick(parms); 'do something that makes money'

    def getRichQuick(parms): richQuick(parms) print 'Future Waring: get and set methods will be deprecated soon use shorter names''

    What do you think??

    opened by BMeridian 5
  • pyalgotrade setup

    pyalgotrade setup

    I understand that this runs in python accesses information in a rather open way, but this is just a headless or "text on screen" and memorize all the commands type of script.

    There is no user menu or txt based menu?

    There are plots as shown at the bottom of this page http://gbeced.github.io/pyalgotrade/docs/v0.20/html/sample_quandl.html

    Quandl it seems has been acquired so, can we still access the data or can i point the software to a different data source like SQL, csv or a pandas dataframe?

    opened by datatalking 1
  • Cannot find doc for creating new feeds

    Cannot find doc for creating new feeds

    I've a PostgreSQL database with a lot of candle data that I want to use for backtesting. I want to create a PostgreSQL feed in order to use those data directly, instead of exporting them into a CSV and then using the CSV itself. But I'm encountering some difficulties to inherit BaseBarFeed because there are abstract methods like join, peekDateTime and so on that I don't know how to override.

    Is there somethere a clear tutorial on about to create a custom feed?

    opened by jepessen 0
  • Backtesting with quantity in decimal point unit

    Backtesting with quantity in decimal point unit

    Hello, I have a question.

    I am trying backtesting for cryptocurrencies.

    To do so I defined my own strategy that is inherited from BacktestingStrategy and ran it.

    All is done but whenever I put decimal point value that is less than zero (e.g, 0.025) to quantity parameter of enterLong or enterShort, it seems that zero value is passed instead.

    How do I make an order with quantity in decimal point unit?

    opened by ghwn 0
  • Duplicate bars found for ['ADA-USD']! Exception raised by membf.py

    Duplicate bars found for ['ADA-USD']! Exception raised by membf.py

    I developed this script to download 1m chart of ADA-USD:

    #!/usr/bin/env python3
    
    import yfinance
    import os
    from datetime import date, timedelta
    
    start_1m = date.today() - timedelta(days=7)
    
    # Getting 1m charts
    data = yfinance.download( 'ADA-USD', start=start_1m, end=today, interval="1m")
    data.to_csv("data/ADA-USD_1mn.csv")
    

    and when getting bars of this csv file, I got this exception from membf.py:

        raise Exception("Duplicate bars found for %s on %s" % (list(ret.keys()), smallestDateTime))
    
    Exception: Duplicate bars found for ['ADA-USD'] on 2021-09-10 00:00:00
    

    But there is no duplication in the CSV file. I checked this with the Linux uniq cmd.

    Can someone help me ti understand this error PLZ?

    opened by bileltechno 1
  • Custom CSV file feed does not work

    Custom CSV file feed does not work

    I was trying to use my own csv data feed to import the data into the strategy using tutorial from the documentation. However, when onBars function is called it yields the following error:AttributeError: 'dict' object has no attribute 'getInstruments'

    When I've used quandlfeed csv files which were downloaded as a result of quandl.build_feed and used guide from http://gbeced.github.io/pyalgotrade/docs/v0.20/html/sample_quandl.html it still yields the same error. It looks like somethinhg is wrong with csv data import. Thank you

    opened by proskurin 1
Zipline, a Pythonic Algorithmic Trading Library

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backte

Quantopian, Inc. 15.7k Jan 2, 2023
Python library for backtesting trading strategies & analyzing financial markets (formerly pythalesians)

finmarketpy (formerly pythalesians) finmarketpy is a Python based library that enables you to analyze market data and also to backtest trading strateg

Cuemacro 3k Dec 30, 2022
Python Backtesting library for trading strategies

backtrader Yahoo API Note: [2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v

DRo 9.8k Dec 30, 2022
:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

Backtesting.py Backtest trading strategies with Python. Project website Documentation the project if you use it. Installation $ pip install backtestin

null 3.1k Dec 31, 2022
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.

TensorTrade: Trade Efficiently with Reinforcement Learning TensorTrade is still in Beta, meaning it should be used very cautiously if used in producti

null 4k Dec 30, 2022
Github.com/CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks

CryptoSignal - #1 Quant Trading & Technical Analysis Bot - 2,100 + stars, 580 + forks https://github.com/CryptoSignal/Crypto-Signal Development state:

Github.com/Signal - 2,100 + stars, 580 + forks 4.2k Jan 1, 2023
ffn - a financial function library for Python

ffn - Financial Functions for Python Alpha release - please let me know if you find any bugs! If you are looking for a full backtesting framework, ple

Philippe Morissette 1.4k Jan 1, 2023
Q-Fin: A Python library for mathematical finance.

Q-Fin A Python library for mathematical finance. Installation https://pypi.org/project/QFin/ pip install qfin Bond Pricing Option Pricing Black-Schol

Roman Paolucci 247 Jan 1, 2023
Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Beibo is a Python library that uses several AI prediction models to predict stocks returns over a defined period of time.

Santosh 54 Dec 10, 2022
Indicator divergence library for python

Indicator divergence library This module aims to help to find bullish/bearish divergences (regular or hidden) between two indicators using argrelextre

null 8 Dec 13, 2022
Technical Analysis Library using Pandas and Numpy

Technical Analysis Library in Python It is a Technical Analysis library useful to do feature engineering from financial time series datasets (Open, Cl

Darío López Padial 3.4k Jan 2, 2023
High-performance TensorFlow library for quantitative finance.

TF Quant Finance: TensorFlow based Quant Finance Library Table of contents Introduction Installation TensorFlow training Development roadmap Examples

Google 3.5k Jan 1, 2023
A python wrapper for Alpha Vantage API for financial data.

alpha_vantage Python module to get stock data/cryptocurrencies from the Alpha Vantage API Alpha Vantage delivers a free API for real time financial da

Romel Torres 3.8k Jan 7, 2023
Portfolio and risk analytics in Python

pyfolio pyfolio is a Python library for performance and risk analysis of financial portfolios developed by Quantopian Inc. It works well with the Zipl

Quantopian, Inc. 4.8k Jan 8, 2023
Python sync/async framework for Interactive Brokers API

Introduction The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy as possible. The ma

Ewald de Wit 2k Dec 30, 2022
bt - flexible backtesting for Python

bt - Flexible Backtesting for Python bt is currently in alpha stage - if you find a bug, please submit an issue. Read the docs here: http://pmorissett

Philippe Morissette 1.6k Jan 5, 2023
ARCH models in Python

arch Autoregressive Conditional Heteroskedasticity (ARCH) and other tools for financial econometrics, written in Python (with Cython and/or Numba used

Kevin Sheppard 1k Jan 4, 2023
personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

personal finance tracker, written in python 3 and using the wxPython GUI toolkit.

wenbin wu 23 Oct 30, 2022
An Algorithmic Trading Library for Crypto-Assets in Python

Service Master Develop CI Badge Catalyst is an algorithmic trading library for crypto-assets written in Python. It allows trading strategies to be eas

Enigma 2.4k Jan 5, 2023