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
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
Algorithms-in-Python - Programs related to DSA in Python for placement practice

Algorithms-in-Python Programs related to DSA in Python for placement practice CO

MAINAK CHAUDHURI 2 Feb 02, 2022
RRT algorithm and its optimization

RRT-Algorithm-Visualisation This is a project that aims to develop upon the RRT

Sarannya Bhattacharya 7 Mar 06, 2022
Apriori - An algorithm for frequent item set mining and association rule learning over relational databases

Apriori Apriori is an algorithm for frequent item set mining and association rul

Mohammad Nazari 8 Jan 10, 2022
A simple library for implementing common design patterns.

PyPattyrn from pypattyrn.creational.singleton import Singleton class DummyClass(object, metaclass=Singleton): # DummyClass is now a Singleton!

1.7k Jan 01, 2023
Rover. Finding the shortest pass by Dijkstra’s shortest path algorithm

rover Rover. Finding the shortest path by Dijkstra’s shortest path algorithm Задача Вы — инженер, проектирующий роверы-беспилотники. Вам надо спроекти

1 Nov 11, 2021
QDax is a tool to accelerate Quality-Diveristy (QD) algorithms through hardware accelerators and massive parallelism

QDax: Accelerated Quality-Diversity QDax is a tool to accelerate Quality-Diveristy (QD) algorithms through hardware accelerators and massive paralleli

Adaptive and Intelligent Robotics Lab 183 Dec 30, 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
:computer: Data Structures and Algorithms in Python

Algorithms in Python Implementations of a few algorithms and datastructures for fun and profit! Completed Karatsuba Multiplication Basic Sorting Rabin

Prakhar Srivastav 2.9k Jan 01, 2023
Pathfinding algorithm based on A*

Pathfinding V1 What is pathfindingV1 ? This program is my very first path finding program, using python and turtle for graphic rendering. How is it wo

Yan'D 6 May 26, 2022
Resilient Adaptive Parallel sImulator for griD (rapid)

Rapid is an open-source software library that implements a novel “parallel-in-time” (Parareal) algorithm and semi-analytical solutions for co-simulation of integrated transmission and distribution sy

Richard Lincoln 7 Sep 07, 2022
How on earth can I ever think of a solution like that in an interview?!

fuck-coding-interviews This repository is created by an awkward programmer who always struggles with coding problems on LeetCode, even with some Easy

Vinta Chen 613 Jan 08, 2023
This repository provides some codes to demonstrate several variants of Markov-Chain-Monte-Carlo (MCMC) Algorithms.

Demo-of-MCMC These files are based on the class materials of AEROSP 567 taught by Prof. Alex Gorodetsky at University of Michigan. Author: Hung-Hsiang

Sean 1 Feb 05, 2022
Sign data using symmetric-key algorithm encryption.

Sign data using symmetric-key algorithm encryption. Validate signed data and identify possible validation errors. Uses sha-(1, 224, 256, 385 and 512)/hmac for signature encryption. Custom hash algori

Artur Barseghyan 39 Jun 10, 2022
Algorithmic virtual trading using the neostox platform

Documentation Neostox doesnt have an API Support, so this is a little selenium code to automate strategies How to use Clone this repository and then m

Abhishek Mittal 3 Jul 20, 2022
Official implementation of "Path Planning using Neural A* Search" (ICML-21)

Path Planning using Neural A* Search (ICML 2021) This is a repository for the following paper: Ryo Yonetani*, Tatsunori Taniai*, Mohammadamin Barekata

OMRON SINIC X 82 Jan 07, 2023
marching Squares algorithm in python with clean code.

Marching Squares marching Squares algorithm in python with clean code. Tools Python 3 EasyDraw Creators Mohammad Dori Run the Code Installation Requir

Mohammad Dori 3 Jul 15, 2022
TikTok X-Gorgon & X-Khronos Generation Algorithm

TikTok X-Gorgon & X-Khronos Generation Algorithm X-Gorgon and X-Khronos headers are required to call tiktok api. I will provide you API as rental or s

TikTokMate 31 Dec 01, 2022
Python package to monitor the power consumption of any algorithm

CarbonAI This project aims at creating a python package that allows you to monitor the power consumption of any python function. Documentation The com

Capgemini Invent France 36 Nov 11, 2022
Sorting-Algorithms - All information about sorting algorithm you need and you can visualize the code tracer

Sorting-Algorithms - All information about sorting algorithm you need and you can visualize the code tracer

Ahmed Hossam 15 Oct 16, 2022