An api, written in Python, for Investopedia's paper trading stock simulator.

Overview

investopedia-trading-api

An API, written in Python, for Investopedia's paper trading stock simulator. Pull requests welcome.

This library is now Python 3 compatible!

Installation

For this API to be useful you need an Investopedia trading account, which you can make here.

You can install the library with pip:

pip install InvestopediaApi

Documentation and examples:

Importing everything:

from InvestopediaApi import ita

ita is the name of the file that contains everything of relevance for interacting with Investopedia.

The main class is Account, which logs you into the simulator upon instantiation.

Log into the simulator:

from InvestopediaApi import ita
client = ita.Account("emailaddress", "password")

Currently, Investopedia Api has 4 "meta" functions:

  1. ita.Account.get_portfolio_status
  2. ita.Account.get_current_securities
  3. ita.Account.get_open_trades
  4. ita.get_quote

get_portfolio_status returns a named tuple with 4 elements: account_val, buying_power, cash, and annual_return.

from InvestopediaApi import ita

client = ita.Account("email", "password")

status = client.get_portfolio_status()
print(status.account_val)
print(status.buying_power)
print(status.cash)
print(status.annual_return)

get_current_securities returns a Portfolio object with 3 attributes: bought, shorted, and options. Each of those is a list of Security objects with the following attributes: symbol, description, quantity, purchase_price, current_price, current_value, and gain_loss

from Investopedia import ita

client = ita.Account("email", "password")

portfolio = client.get_current_securities()

# Portfolio is not a list, it is a namedtuple object with 3 attributes: bought, shorted, options.
# Each of bought, shorted, and options is a list of Security objects, which have attributes
# symbol, description, quantity, purchase_price, current_price, current_value, and gain_loss

bought_securities = portfolio.bought
shorted_securities = portfolio.shorted
options = portfolio.options

for bought in bought_securities:
    print(bought.symbol)
    print(bought.description)
    print(bought.purchase_price)
    # etc.

# Repeat above loop for shorted securities and options

get_open_trades returns a list of "open" trades - that is, trades that have been made but not yet executed by the Investopedia platform. It returns a list of Trade namedtuple objects which have the following elements: date_time, description, symbol, and quantity.

from InvestopediaApi import ita

client = ita.Account("email", "password")

open_trades = client.get_open_trades()

for open_trade in open_trades:
    print(open_trade.date_time)
    print(open_trade.description)
    print(open_trade.symbol)
    print(open_trade.quantity)

get_quote returns the price of a security given its symbol. Unlike the other 3 meta functions, this is not part of the Account class. Returns false if the security is not found or another error occurs.

from InvestopediaApi import ita

client = ita.Account("email", "password")
print(ita.get_quote("GOOG"))

Making trades

Of course, the most important function in this API is the trade function. This takes, at minimum, a security symbol (string), an orderType (Action class), and a quantity (integer).

The trade function is best illustrated with examples:

Buying 10 shares of Google (GOOG) at market price:

client.trade("GOOG", ita.Action.buy, 10)

Selling 10 shares of Google at market price:

client.trade("GOOG", ita.Action.sell, 10)

Shorting 10 shares of Google:

client.trade("GOOG", ita.Action.short, 10)

Buying 10 shares of Google with a limit order at $500

client.trade("GOOG", ita.Action.buy, 10, "Limit", 500)

You can browse through the code (it's only in one file) to get a more thorough understanding of the possibilities.

Testing

All Tests: python -m unittest discover

Feature Tests

Feature tests require a config file to be set up InvestopediaApi/tests/config.py. Instructions are in InvestopediaApi/tests/config.example.py.

Comments
  • added option trading

    added option trading

    Not sure why GitHub thinks I changed the whole file. Probably in how I updated my fork with your repo. I only added the function trade_option

    Examples: client.trade_option("GOOG", Action.buy, "Call", 945, 170616, 1) client.trade_option("GOOG", Action.buy, "Put", 932.50, 170616, 10, "Limit", 6.25) client.trade_option(symbol, ordertype, optiontype, strikeprice, expire_date, quantity, pricetype, targetprice, duration)

    Successfully tested option orders with limits, stops, Duration.day_order. Raises exception on error like with client.trade().

    Date currently gets entered as YYMMDD (ex. "170616" for 2017-06-16). not sure if good idea.

    opened by stellarore 5
  • gets all current securities, open trades, investopedia quotes

    gets all current securities, open trades, investopedia quotes

    Added function to load all current securities from a portfolio, load all currently open trades, and get quotes from the investopedia site.

    Running with python 3.6.1.

    I started with @Scorpio1987 's fork which may have been the wrong decision. Sorry, it's my first time on Github.

    opened by stellarore 4
  • Not-so-brief Comments

    Not-so-brief Comments

    Hi. I've found your library through your reddit post- I'd skip the formalities and dive right into the comments. Take note that these comments are valid for commit 8d6dbfd. Firstly you are using too many comments- I counted about 41 comments in a 135 line file. Comments are fine, don't get me wrong, but you should really take a look at your code and see if the intent behind it is obvious even without comments.

    Secondly it feels as though we are writing C here- why do this:

    handle = login(_, _)
    trade(handle, ...)
    

    When we ~~can~~ should instead do this with a more OO way:

    client = login(_, _)
    client.trade(...)
    

    It has the additional benefit of not exposing too big an API surface- for example if one day you changed from mechanize to some other library your users wouldn't complain as much simply because you haven't explicitly returned a Browser object. However if you did then they would come to rely on it and ultimately write code that depends on it. In short, you want to hide the implementation and expose the interface.

    Thirdly please consider more intuitive variable names- login(username, password) suggests that it takes in a username, but in reality submits an email address? (See line 18). Also what you are having in the trade function is essentially an enum- there are a list of possible actions, from what I see in the README,

    • Buy (1)
    • Sell (2)

    So you might want to consider either using the enum library in Python 3 or using the backported enum module if you have to target Python 2.x. That way you can write:

    class Action(Enum):
        buy = 1
        sell = 2
    
    client.trade("GOOG", Action.buy, 10)
    

    Which gives you sort of a "type safety" if you write type checks in the trade method, and also reduces the chances of errors. After all, selling and buying shares is quite a big deal.

    Also, in line 47: "This could probably be more elegant...". Please, make it more elegant. In it's current form it requires a LOT of brainpower to even try and parse what you are trying to express with the code. A slight deviation from the technical points but please try to follow the naming conventions- in Python classes are written in CapitalisedCamelCase, while functions, methods, and variables are written in snake_case.

    In the getPortfolioStatus function you are returning what looks like an arbitrary tuple with all sorts of numbers inside. What you should be doing here is returning a namedtuple. That way the individual components that make up the portfolio can be easily and correctly accessed:

    portfolio = client.get_portfolio_status()
    portfolio.account_value
    portfolio.cash_value
    #etc
    
    opened by eugene-eeo 4
  • get_portfolio_status() returns AttributeError

    get_portfolio_status() returns AttributeError

    3 lines:

    from InvestopediaApi import ita inv = ita.Account("email", "pwd") inv.get_portfolio_status()

    returns

    Traceback (most recent call last): File "/Users/Ember/Documents/BitBot/main.py", line 3, in inv.get_portfolio_status() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/InvestopediaApi/ita.py", line 67, in get_portfolio_status account_value = parsed_html.find('span', attrs={'id': acct_val_id}).text AttributeError: 'NoneType' object has no attribute 'text'

    any ideas? thanks.

    opened by MSXR 3
  • How to install investopedia-trading-api in ubuntu

    How to install investopedia-trading-api in ubuntu

    I cant install investopedia-trading-api in my ubuntu system. I have downloaded the zip file and unzipped it and used this code to install the api

    sudo python setup.py install and it cerrated a build folder in current directory and this is the result

    running install
    running build
    running build_py
    package init file 'investopedia-trading-api/__init__.py' not found (or not a regular file)
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/investopedia-trading-api
    copying investopedia-trading-api/investopedia.py -> build/lib.linux-x86_64-2.7/investopedia-trading-api
    package init file 'investopedia-trading-api/__init__.py' not found (or not a regular file)
    running install_lib
    running install_egg_info
    Removing /usr/local/lib/python2.7/dist-packages/investopedia_trading_api-1.0.egg-info
    Writing /usr/local/lib/python2.7/dist-packages/investopedia_trading_api-1.0.egg-info
    
    

    but when it tried to import investopedia in python its giving me this result

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named investopedia
    
    

    any idea what is happening here?

    opened by ghost 2
  • error get portfolio_status()

    error get portfolio_status()

    Error getting status.

    >>> status = client.get_portfolio_status()
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "investopedia.py", line 64, in get_portfolio_status
     account_value = parsed_html.find('span', attrs={'id':acct_val_id}).text
     AttributeError: 'NoneType' object has no attribute 'text'
    
    opened by JoePython1 2
  • No status report when doing an action

    No status report when doing an action

    When I do

    client.trade("GOOG", Action.buy, 10)
    

    I get no report of success / failure. It seems that it failed (because closed?) How to have a status report?

    opened by josephernest 2
  • Failed to handle prices more than 1000

    Failed to handle prices more than 1000

    ita.get_quote("GOOG")

    The code simply uses float() to do type cast, without handling the corner cases where values greater than 3 digits uses comma as separator.

    Traceback (most recent call last): File "./launcher.py", line 53, in main(parse_args()) File "./launcher.py", line 48, in main app.run() File "/home/tcheng/Repositories/spice/spice/watcher.py", line 31, in run self.check_stock_prices() File "/home/tcheng/Repositories/spice/spice/watcher.py", line 56, in check_stock_prices print(ita.get_quote("GOOG")) File "/home/tcheng/Repositories/spice/venv/lib/python3.6/site-packages/InvestopediaApi/ita.py", line 261, in get_quote return float(quote) ValueError: could not convert string to float: '1,029.27'

    opened by tycheng 1
  • AttributeError: 'module' object has no attribute '_base'

    AttributeError: 'module' object has no attribute '_base'

    I wrote the following script:

    from investopedia import *
    client = Account("emailaddress","password") #replaced with my info
    
    status = client.get_portfolio_status()
    print status.account_val
    print status.buying_power
    print status.cash
    print status.annual_return
    

    I was able to install all the modules by running py -2.7 setup.py install for each dependency.

    I am receiving the following error:

    Traceback (most recent call last):
    File "C:/Users/Z/PycharmProjects/investopedia/test.py", line 1, in <module>
        from investopedia import *
      File "C:\Users\Z\PycharmProjects\investopedia\investopedia.py", line 4, in <module>
        from bs4 import BeautifulSoup
      File "C:\Users\Z\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\__init__.py", line 29, in <module>
        from .builder import builder_registry
      File "C:\Users\Z\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\builder\__init__.py", line 297, in <module>
        from . import _html5lib
      File "C:\Users\Z\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\builder\_html5lib.py", line 57, in <module>
        class TreeBuilderForHtml5lib(html5lib.treebuilders._base.TreeBuilder):
    AttributeError: 'module' object has no attribute '_base'
    

    Do you know how to resolve this?

    opened by hasanzuav 1
  • Account statement

    Account statement

    Help pls..

    client = Account("[email protected]","123") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/investopedia.py", line 37, in init br.select_form(nr=2) File "/usr/local/lib/python2.7/dist-packages/mechanize/_mechanize.py", line 524, in select_form raise FormNotFoundError("no form matching "+description) mechanize._mechanize.FormNotFoundError: no form matching nr 2

    opened by ShikariShambhu 1
  • Intraday trading and data using this API?

    Intraday trading and data using this API?

    Can we fetch intra day data for intra day simulated trading? Does this API fetches intraday/EOD data or we have to use our own data feed? Where we can find the documentation for this API?

    opened by ghost 1
  • Is there any way to fix the login issue

    Is there any way to fix the login issue

    from InvestopediaApi import ita client = ita.Account('[email protected]','notrealpass') status = client.get_portfolio_status() this is what im getting back: Traceback (most recent call last): File "H:/stocks.py", line 2, in client = ita.Account('[email protected]','53471978a') File "C:\Users\aospe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\InvestopediaApi\ita.py", line 40, in init login_form = login_page.soup.select("form#account-api-form")[0] IndexError: list index out of range

    any advice is appreciated ty also apologies if the previous one answered the issue already and im being stupid

    opened by username69420-nice 1
  • Login fixed

    Login fixed

    Fixed some old html, and now buying and shorting stocks works. Havent checked selling though, as stock market is closed. ita.get_quote doesn't work though.

    opened by Bulmenisaurus 0
  • Error when trying to log in.

    Error when trying to log in.

    I was trying to use this api, but encountered problems upon logging in. Here is the full error:

    Traceback (most recent call last):
      File "/Users/meow/programming/PycharmProjects/testing/Investopedia trading.py", line 7, in <module>
        client = ita.Account(account_info[0], account_info[1])
      File "/Users/meow/Maths100%/venv/lib/python3.8/site-packages/InvestopediaApi/ita.py", line 40, in __init__
        login_form = login_page.soup.select("form#account-api-form")[0]
    IndexError: list index out of range
    

    account_info[0] and account_info[1] is the login information. Seeing how old the commits are, I'll probably look for a more active API.

    opened by Bulmenisaurus 4
  • Is this API still useable?

    Is this API still useable?

    Is this code still viable, given the fact that Investopedia has implemented a recaptcha on its simulator login page? I'm getting the following error message:

    InvestopediaApi.ita.LoginError: Login Error: Invalid Username or Password

    I've double checked both my username and password, but it does not appear to work. Looking at the loggin page from a year ago shows that there wasn't a recaptcha, so maybe this is not working anymore?

    opened by Jvinniec 2
  • 2 new functions and 1 modified and slight add-ons

    2 new functions and 1 modified and slight add-ons

    Hello,

    For my own usage, i needed to complete the set of tools with functions allowing to cancel open trades [cancel_open_trades()] or close open positions [close_open_positions()]. These functions accept a list of symbols as parameter or can operate on all trades/positions if no parameter is specified.

    I also modified the get_current_securities and made slight addon/adjustments to other functions.

    I am quite new to python but have a good knowledge of R. Please forgive my bad english.

    Best regards, mdjames.

    opened by mdjames094 0
Owner
Kirk Thaker
Kirk Thaker
Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI

Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI. Used REST and WebSocket API to connect to two of the most popular crypto exchanges in the world.

Francis 8 Sep 15, 2022
Stock trading bot made using the Robinhood API / Python library...

High-Low Stock trading bot made using the Robinhood API / Python library... Index Installation Use Development Notes Installation To Install and run t

Reed Graff 1 Jan 7, 2022
See trending stock tickers on Reddit and check Stock perfomance

See trending stock tickers on Reddit and check Stock perfomance

Abbas 1.5k Jan 6, 2023
Stock Market Insights is a Dashboard that gives the 360 degree view of the particular company stock

Stock Market Insights is a Dashboard that gives the 360 degree view of the particular company stock.It extracts specific data from multiple sources like Social Media (Twitter,Reddit ,StockTwits) , News Articles and applies NLP techniques to get sentiments and insights.

Ganesh N 3 Sep 10, 2021
Trading bot - A Trading bot With Python

Trading_bot Trading bot intended for 1) Tracking current prices of tokens 2) Set

Tymur Kotkov 29 Dec 1, 2022
Utilizing the freqtrade high-frequency cryptocurrency trading framework to build and optimize trading strategies. The bot runs nonstop on a Rasberry Pi.

Freqtrade Strategy Repository Please test all scripts and dry run them before using them in live mode Contact me on discord if you have any questions!

Michael Fourie 90 Jan 1, 2023
This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners and alerts system.

Python Trading Bot w/ Thinkorswim Description This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners

Trey Thomas 201 Jan 3, 2023
Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Alexandr Savinov 326 Jan 3, 2023
alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API. It allows rapid trading algo development easily, with support for both REST and streaming data interfaces

Alpaca 1.5k Jan 9, 2023
Freqtrade is a free and open source crypto trading bot written in Python.

Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning.

Kazune Takeda 5 Dec 30, 2021
An advanced crypto trading bot written in Python

Jesse Jesse is an advanced crypto trading framework which aims to simplify researching and defining trading strategies. Why Jesse? In short, Jesse is

Jesse 4.4k Jan 9, 2023
This is a DCA crypto trading bot built for Binance written in Python

This is a DCA crypto trading bot built for Binance written in Python. It works by allowing you to DCA at an interval of your choosing and reports back on your average buy price as well as a chart consisting of each DCA.

Andrei 55 Oct 17, 2022
Jackrabbit Relay is an API endpoint for stock, forex and cryptocurrency exchanges that accept REST webhooks.

JackrabbitRelay Jackrabbit Relay is an API endpoint for stock, forex and cryptocurrency exchanges that accept REST webhooks. Disclaimer Please note RA

Rose Heart 23 Jan 4, 2023
Stock market bot that will be used to learn about API calls and database connections.

Stock market bot that will be used to learn about API calls and database connections.

null 1 Dec 24, 2021
Trading through Binance's API using Python & sqlite

pycrypt Automate trading crypto using Python to pull data from Binance's API and analyse trends. May or may not consistently lose money but oh well it

Maxim 4 Sep 2, 2022
A Terminal User Interface (TUI) for automated trading with Komodo Platform's AtomicDEX-API

PytomicDEX Makerbot A Terminal User Interface (TUI) for automated trading with Komodo Platform's AtomicDEX-API Install sudo apt install wget curl jq g

null 6 Aug 25, 2022
This is a straightforward python implementation to specifically grab basic infos about IPO companies in China from Sina Stock website.

SinaStockBasicInfoCollect This is a straightforward python implementation to specifically grab basic infos about IPO companies in China from Sina Stoc

CrosSea 1 Dec 9, 2021
Enigma simulator with python and clean code.

Enigma simulator with python and clean code.

Mohammad Dori 3 Jul 21, 2022