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
Dynamic Programming-Join Optimization Algorithm

DP-JOA Join optimization is the process of optimizing the joining, or combining, of two or more tables in a database. Here is a simple join optimizati

Haoze Zhou 3 Feb 03, 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
🌟 Python algorithm team note for programming competition or coding test

🌟 Python algorithm team note for programming competition or coding test

Seung Hoon Lee 3 Feb 25, 2022
Visualisation for sorting algorithms. Version 2.0

Visualisation for sorting algorithms v2. Upped a notch from version 1. This program provides animates simple, common and popular sorting algorithms, t

Ben Woo 7 Nov 08, 2022
A library for benchmarking, developing and deploying deep learning anomaly detection algorithms

A library for benchmarking, developing and deploying deep learning anomaly detection algorithms Key Features • Getting Started • Docs • License Introd

OpenVINO Toolkit 1.5k Jan 04, 2023
A Python implementation of Jerome Friedman's Multivariate Adaptive Regression Splines

py-earth A Python implementation of Jerome Friedman's Multivariate Adaptive Regression Splines algorithm, in the style of scikit-learn. The py-earth p

431 Dec 15, 2022
Nature-inspired algorithms are a very popular tool for solving optimization problems.

Nature-inspired algorithms are a very popular tool for solving optimization problems. Numerous variants of nature-inspired algorithms have been develo

NiaOrg 215 Dec 28, 2022
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
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
Data Model built using Logistic Regression Algorithm on Python.

Logistic-Regression Problem Statement: Your client is a retail banking institution. Term deposits are a major source of income for a bank. A term depo

Hemanth Babu Muthineni 0 Dec 25, 2021
Algorithms and data structures for educational, demonstrational and experimental purposes.

Algorithms and Data Structures (ands) Introduction This project was created for personal use mostly while studying for an exam (starting in the month

50 Dec 06, 2022
This python algorithm creates a simple house floor plan based on a user-provided CSV file.

This python algorithm creates a simple house floor plan based on a user-provided CSV file. The algorithm generates possible router placements and evaluates where a signal will be reached in every roo

Joshua Miller 1 Nov 12, 2021
Programming Foundations Algorithms With Python

Programming-Foundations-Algorithms Algorithms purpose to solve a specific proplem with a sequential sets of steps for instance : if you need to add di

omar nafea 1 Nov 01, 2021
Provide player's names and mmr and generate mathematically balanced teams

Lollo's matchmaking algorithm Provide player's names and mmr and generate mathematically balanced teams How to use Fill the input.json file with your

4 Aug 04, 2022
GoldenSAML Attack Libraries and Framework

WhiskeySAML and Friends TicketsPlease TicketsPlease: Python library to assist with the generation of Kerberos tickets, remote retrieval of ADFS config

Secureworks 43 Jan 03, 2023
Machine Learning algorithms implementation.

Machine Learning Algorithms Machine Learning algorithms implementation. What can I find here? ML Algorithms KNN K-Means-Clustering SVM (MultiClass) Pe

David Levin 1 Dec 10, 2021
A Python project for optimizing the 8 Queens Puzzle using the Genetic Algorithm implemented in PyGAD.

8QueensGenetic A Python project for optimizing the 8 Queens Puzzle using the Genetic Algorithm implemented in PyGAD. The project uses the Kivy cross-p

Ahmed Gad 16 Nov 13, 2022
A selection of a few algorithms used to sort or search an array

Sort and search algorithms This repository has some common search / sort algorithms written in python, I also included the pseudocode of each algorith

0 Apr 02, 2022
Given a list of tickers, this algorithm generates a recommended portfolio for high-risk investors.

RiskyPortfolioGenerator Given a list of tickers, this algorithm generates a recommended portfolio for high-risk investors. Working in a group, we crea

Victoria Zhao 2 Jan 13, 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