Python based framework providing a simple and intuitive framework for algorithmic trading

Overview

Header Harvest is a Python based framework providing a simple and intuitive framework for algorithmic trading. Visit Harvest's website for details, tutorials, and documentation.


codecov run tests website Code style: Black

Comments? Questions? Join our discussion

⚠️ WARNING ⚠️ Harvest is currently at v0.1.1. The program is unstable and cointains many bugs. Use with caution, and contributions are greatly appreciated.

Example

Below is a minimal example of a crossover strategy for TWTR implemented with Harvest, tested on historical stock prices.

from harvest.algo import *
from harvest.trader import *
from harvest.api import *

class Watch(BaseAlgo):
    def config(self):
        self.watchlist = ["TWTR"]
        self.interval = "5MIN"

    def main(self):
        sma_long = self.sma(period=50)
        sma_short = self.sma(period=20)
        if self.crossover(sma_long, sma_short):
            self.buy()
        elif self.crossover(sma_short, sma_long):
            self.sell()

if __name__ == "__main__":
    t = tester.BackTester()
    t.set_algo(Watch())
    t.start()

If you want to see how this algorithm performs in real life, just change one line to enable paper trading:

- t = tester.BackTester()
+ t = trader.Trader()

Confident in your strategy? Deploy it using a broker of your choice (Currently only supports Robinhood). Again, you just need to change one line:

- t = trader.Trader()
+ t = trader.Trader(robinhood.Robinhood())

With Harvest, the process of testing, simulating, and deploying your strategies is a piece of cake 🍰

Installation

There are few prerequisites:

  • Python 3.8+
  • pip

Once you have them, install via pip:

pip install harvest-python

Next, install the dependencies necessary for the brokerage of your choice:

pip install harvest-python[BROKER]

Replace BROKER with a brokerage/data source of your choice:

  • Robinhood
  • Alpaca
  • Webull
  • Kraken
  • Polygon
  • Yahoo

Now you're all set!

Contributing

Contributions are greatly appreciated. Check out the CONTRIBUTING document for details, and ABOUT for the long-term goals of this project.

Currently looking for...

  • Python devs to code the framework
  • Backend devs for the Flask backend
  • Frontend devs to make the web GUI based on Svelte
  • UX/UI designers for the web GUI

Disclaimer

  • Harvest is not officially associated with Robinhood, Alpaca, WebBull, Kraken, Polygon, or Yahoo.
  • Many of the brokers were also not designed to be used for algo-trading. Excessive access to their API can result in your account getting locked.
  • Tutorials and documentation solely exist to provide technical references of the code. They are not recommendations of any specific securities or strategies.
  • Use Harvest at your own responsibility. Developers of Harvest take no responsibility for any financial losses you incur by using Harvest. By using Harvest, you certify you understand that Harvest is a software in early development and may contain bugs and unexpected behaviors.
Comments
  • Create a web server

    Create a web server

    Updated - implement the following: Updated 8/14:

    • [x] A Flask web server to return a web interface, and provide an API for harvest's status. Possibly use socket.io for real-time data.
    • [x] A React frontend. For now, it should be very simple, more like a proof-of-concept. Svelte is a good candidate for the framework.
    • [ ] Update functions in harvest to automatically log certain actions (like buying stocks) and send the data to the frontend
    • [x] #39
    enhancement help wanted 
    opened by tfukaza 12
  • Add new brokers

    Add new brokers

    Using documentation in _base.py and the example of robinhood.py, implement

    This issue is marked as a good first issue, because it is supposed to be a litmus test of how easy it is to add a new broker support to Harvest, which is one of its selling point.

    enhancement good first issue 
    opened by tfukaza 9
  • Improve modularity of code

    Improve modularity of code

    One issue with the way the code is organized currently is that each module frequently makes references to each other. For example, the Storage class gets the current time by referencing trader.timestamp, and Trader updates the timestamp by referencing Streamer. This can make the code messy and make the ownership of the attributes unclear.

    My current idea is to bundle common runtime attributes like timestamp and watchlist, as well as info like current stock positions, into a single class/dictionary. Every module will share a reference to a single instance of this class/dict.

    enhancement feedback 
    opened by tfukaza 7
  • Split `DummyBroker` into `DummyStreamer` and `PaperBroker`

    Split `DummyBroker` into `DummyStreamer` and `PaperBroker`

    Currently the functionality of DummyBroker is a little confusing - when used as a streamer, it generates dummy data as its name implies, but when used as a broker, it paper trades. Now that brokers have the mode attribute, DummyBroker should be split into separate brokers as described in the title.

    Also, the following name convention is suggested for brokers:

    • [Name] for classes that function as streamers && brokers
    • [Name]Streamer for classes that only work as streamers
    • [Name]Broker for classes that only work as brokers
    enhancement 
    opened by tfukaza 6
  • Have the trader class support multiple algos

    Have the trader class support multiple algos

    • [ ] Replace the self.algo in the trader class with a list and replace the set_algo function with a list.
    • [ ] Update the trader run function to iterate through the algos and run each
    enhancement good first issue 
    opened by shershah010 6
  • [💡Feature Request] Harvest GUI Interface

    [💡Feature Request] Harvest GUI Interface

    Software like splunk or xsoar have local servers with guis fro users to interface with there system. These servers also make it easier for distributed environments and the ability to run inside a docker container while being able to easily access it outside the container. I think if Harvest had a similar feature, it would be pretty sweet.

    I think that this feature is pretty big and probably won't fit into the second milestone, but could be a good third or fourth milestone.

    Here are some mockups of how the web app would look:

    Home Streamer Broker Storage Algo Process

    enhancement question 
    opened by shershah010 4
  • Code cleanup

    Code cleanup

    Harvest currently outputs using the print() function. This is not ideal, since users have no way to control the format of the outputted messages or disable them if necessary. Replace print() statements with info() from python logging module. Link to documentation

    enhancement good first issue 
    opened by tfukaza 4
  • [🪰BUG]Yahoo earnings not working

    [🪰BUG]Yahoo earnings not working

    Yahoo earnings not working and missing package dependency in setup.py. please add get earnings between dates.

    install_requires=[ 'pandas', 'finta', 'pyyaml', 'tqdm', 'pytz' ],

    bug 
    opened by pradeephyd 4
  • Better modularity

    Better modularity

    Major Changes

    • Create Positions and Position class to manage currently owned assets. It also has helper methods to automatically update attributes such as % profit.
    • Create Account class to manage account.
    • Create Function class. This class stores various function pointers, so modules can access necessary functions directly rather than daisy chaining references. e.g. self.trader.storage.load is now self.func.load. This is also useful in testing, as we can pass in alternate functions during tests.
    • Update code to use the new classes.

    Minor Changes

    • Changed interval attribute in Trader to watchlist_cfg
    • Changed watchlist_global in Trader to watchlist
    • Several code quality improvements.
    opened by tfukaza 3
  • BackTester now allows period to be specified; Passes test cases

    BackTester now allows period to be specified; Passes test cases

    Allow users to specify the date range of backtesting data.

    BackTester.start() will take 3 new params:

    • start: start date and time of backtest, in format "MM-DD-YYYY:HH:MM:SS", or None to use the max range.
    • end: start date and time of backtest, in format "MM-DD-YYYY:HH:MM:SS", or None to use current time
    • period: The range of backtesting, in format "{N}DAYS". If start is not specified, start will be set to end - period. If end is not specified, end = start + period.

    Some modifications were also made to _base_storage.py

    As you can see, there is much more work to be done - many edge cases are not handled, and code needs much more organizing. I'm opening a PR early to get some feedback on the changes I made so far as well as suggestions to better organize the code.

    opened by tfukaza 3
  • [💡Feature Request] Better Logging

    [💡Feature Request] Better Logging

    Create a python file that creates a logger and have all files that log import this file. This file should create a logger and configure it.

    Suggested logging strategy

    • DEBUG: Called at the start of every function and prints the message name and all arguments. Typically not shown to user.
    • INFO: Let users know of important things that occur. To give users confidence that the program is running as expected.
    • WARNING: Something bad happened and harvest can automatically fix the issue without any user input. For example if the user tries to get stock data from over a period of time that their account allows, we can fix that start time.
    • ERROR: Something unexpected happened but can easily be fixed. Like the user tried to add a stock ticker that does not exists or tried to add a stock ticker to a broker that only supports crypto or API call failed, we could try redoing the api call.
    • raise Exception: Something really bad happened and the entire system must be shutdown because there is no way to recover. This could be a call to a function that should return something without a solid null case. For example returning an empty list is a fine null case but an empty dictionary or None isn't (since no one checks for the None case).

    Let me know if this sounds good or if there is anything I should change.

    enhancement question 
    opened by shershah010 3
  • [🪲BUG] Number of digits in RH crypto order is not checked

    [🪲BUG] Number of digits in RH crypto order is not checked

    Describe the bug Sometimes, when placing crypto orders on Robinhood, an error is returned by the API indicating the the number of digits in the order quantity is too much.

    To Reproduce For example, if you try to buy 0.00000001 DOGE, the order will fail.

    Expected behavior It appears that on Robinhood, the number of digits D_o allowed in the order quantity is N - D_p, where N is some constant and D_p is the number of digits in the current price of the cryptocurrency.

    To fix this bug, you must:

    • [ ] Investigate the value of N
    • [ ] Add checks to buy/sell functions so order quantities are automatically rounded down to the proper number of digits.
    bug good first issue 
    opened by tfukaza 0
  • [🪲BUG] YahooStreamer wrong timestamp

    [🪲BUG] YahooStreamer wrong timestamp

    Describe the bug For every DataFrame YahooStreamer returns, the latest data has a wrong timestamp. Screen Shot 2021-08-01 at 12 41 02 AM In this case, the timestamp should be 2021-08-01 07:40:00+00:00

    To Reproduce Run a Trader with YahooStreamer, and enable debug output. Note the timestamps of the DataFrames returned.

    bug good first issue 
    opened by tfukaza 0
Owner
Favorite buzzwords: autonomous, ambient, edge
Repository for Comparison based sorting algorithms in python

Repository for Comparison based sorting algorithms in python. This was implemented for project one submission for ITCS 6114 Data Structures and Algorithms under the guidance of Dr. Dewan at the Unive

Devashri Khagesh Gadgil 1 Dec 20, 2021
A priority of preferences for teacher assignment problem

Genetic-Algorithm-for-Assignment-Problem A priority of preferences for teacher assignment problem Keywords k-partition; clustering; education 4.0 Abst

hades 2 Oct 31, 2022
Repository for data structure and algorithms in Python for coding interviews

Python Data Structures and Algorithms This repository contains questions requiring implementation of data structures and algorithms concepts. It is us

Prabhu Pant 1.9k Jan 01, 2023
sudoku solver using CSP forward-tracking algorithms.

Sudoku sudoku solver using CSP forward-tracking algorithms. Description Sudoku is a logic-based game that consists of 9 3x3 grids that create one larg

Cindy 0 Dec 27, 2021
Supplementary Data for Evolving Reinforcement Learning Algorithms

evolvingrl Supplementary Data for Evolving Reinforcement Learning Algorithms This dataset contains 1000 loss graphs from two experiments: 500 unique g

John Co-Reyes 42 Sep 21, 2022
Python sample codes for robotics algorithms.

PythonRobotics Python codes for robotics algorithm. Table of Contents What is this? Requirements Documentation How to use Localization Extended Kalman

Atsushi Sakai 17.2k Jan 01, 2023
This is a demo for AAD algorithm.

Asynchronous-Anisotropic-Diffusion-Algorithm This is a demo for AAD algorithm. The subroutine of the anisotropic diffusion algorithm is modified from

3 Mar 21, 2022
Slight modification to one of the Facebook Salina examples, to test the A2C algorithm on financial series.

Facebook Salina - Gym_AnyTrading Slight modification of Facebook Salina Reinforcement Learning - A2C GPU example for financial series. The gym FOREX d

Francesco Bardozzo 5 Mar 14, 2022
Esse repositório tem como finalidade expor os trabalhos feitos para disciplina de Algoritmos computacionais e estruturais do CEFET-RJ no ano letivo de 2021.

Exercícios de Python 🐍 Esse repositório tem como finalidade expor os trabalhos feitos para disciplina de Algoritmos computacionais e estruturais do C

Rafaela Bezerra de Figueiredo 1 Nov 20, 2021
A collection of Python Scripts made for fun, while exploring Python 🐍

JFF-Python-Scripts A collection of Python Scripts made for fun, while exploring Python 🐍 Inspiration 💡 Many of the programs in this repository are i

Pushkar Patel 16 Oct 07, 2022
Xor encryption and decryption algorithm

Folosire: Pentru encriptare: python encrypt.py parola fișier pentru criptare fișier encriptat(de tip binar) Pentru decriptare: python decrypt.p

2 Dec 05, 2021
A pure Python implementation of a mixed effects random forest (MERF) algorithm

Mixed Effects Random Forest This repository contains a pure Python implementation of a mixed effects random forest (MERF) algorithm. It can be used, o

Manifold 199 Dec 06, 2022
🧬 Performant Evolutionary Algorithms For Python with Ray support

🧬 Performant Evolutionary Algorithms For Python with Ray support

Nathan 49 Oct 20, 2022
FingerPy is a algorithm to measure, analyse and monitor heart-beat using only a video of the user's finger on a mobile cellphone camera.

FingerPy is a algorithm using python, scipy and fft to measure, analyse and monitor heart-beat using only a video of the user's finger on a m

Thiago S. Brasil 37 Oct 21, 2022
A lightweight, pure-Python mobile robot simulator designed for experiments in Artificial Intelligence (AI) and Machine Learning, especially for Jupyter Notebooks

aitk.robots A lightweight Python robot simulator for JupyterLab, Notebooks, and other Python environments. Goals A lightweight mobile robotics simulat

3 Oct 22, 2021
Robotic Path Planner for a 2D Sphere World

Robotic Path Planner for a 2D Sphere World This repository contains code implementing a robotic path planner in a 2D sphere world with obstacles. The

Matthew Miceli 1 Nov 19, 2021
Path tracing obj - (taichi course final project) a path tracing renderer that can import and render obj files

Path tracing obj - (taichi course final project) a path tracing renderer that can import and render obj files

5 Sep 10, 2022
A collection of design patterns/idioms in Python

python-patterns A collection of design patterns and idioms in Python. Current Patterns Creational Patterns: Pattern Description abstract_factory use a

Sakis Kasampalis 36.2k Jan 05, 2023
This repository explores an implementation of Grover's Algorithm for knights on a chessboard.

Grover Knights Welcome to my Knights project! Project Description: I explore an implementation of a quantum oracle for knights on a chessboard.

Will Sun 8 Feb 22, 2022
Genius Square puzzle solver in Python

Genius Square puzzle solver in Python

James 3 Dec 15, 2022