kirkthaker / investopedia-trading-api Goto Github PK
View Code? Open in Web Editor NEWAn api, written in Python, for Investopedia's paper trading stock simulator.
License: Other
An api, written in Python, for Investopedia's paper trading stock simulator.
License: Other
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
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,
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
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.
Getting form error now.
>> client.trade("SPY", Action.short, 20)
Tried changing simTradePreview to simTrade and didnt work either.
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'
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?
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?
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'
Dear kirkthaker. Please have a look at my pull request. best regards.
Update details (from StackOverflow)
This is a question involving Python, Beautiful Soup, and HTML, as well as the Investopedia API.
The first part involved is this block of Python that takes an input and executes a function based off of the given input (action is raw_input
):
if action == 'trade':
symbol = raw_input("Symbol: ")
order_type = raw_input("Order Type: ")
quantity = raw_input("Quantity: ")
if order_type == 'buy':
client.trade(str(symbol), ita.Action.buy, int(quantity))
elif order_type == 'sell':
client.trade(str(symbol), ita.Action.sell, int(quantity))
elif order_type == 'short':
client.trade(str(symbol), ita.Action.short, int(quantity))
The second parameter (ita.Action.[order_type])
, written as directed in the API documentation, and as indicated in the code itself, refers to this block:
# input transaction type
[option.attrs.pop("selected", "") for option in trade_form.select("select#transactionTypeDropDown")[0]("option")]
trade_form.select("select#transactionTypeDropDown")[0].find("option", {"value": str(orderType.value)})["selected"] = True
That block uses .find
from Beautiful Soup to target a drop-down menu that is formatted as such:
<select name="transactionTypeDropDown" id="transactionTypeDropDown" style="width: auto;">
<option value="1">Buy</option>
<option value="2">Sell</option>
<option value="3">Sell Short</option>
<option value="4">Buy to Cover</option>
</select>
In the API's documentation, the examples are listed to operate as follows:
client.trade("GOOG", ita.Action.buy, 10)
However, AttributeError is reporting that 'int' object has no attribute 'value'
, in that given line, even when I've attempted to run the line as it is written in the documentation on its own.
File "/fakepath/MMIAS/ita/ita.py", line 233, in trade
trade_form.select("select#transactionTypeDropDown")[0].find("option", {"value": str(orderType.value)})["selected"] = True
AttributeError: 'int' object has no attribute 'value'
I am assuming that the 'int'
object in question is the option value from the drop-down menu, and with that, I am assuming that that an int, perhaps 1 - 4, is occupying the orderType
parameter. So, why would it be suggested that the parameter be ita.Action.[buy/sell/short/etc]
, rather than just an integer value? And why does it return the same error if an integer value fulfills that parameter? Help me understand.
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?
Gain_loss field is not returned when calling get_current_securities() function.
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.
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?
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?
I have this error when I run simple example to get prices
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.investopedia.c
om', port=80): Max retries exceeded with url: /accounts/login.aspx?returnurl=htt
p%3A%2F%2Fwww.investopedia.com%2Fsimulator%2F (Caused by NewConnectionError('<ur
llib3.connection.HTTPConnection object at 0x0000000003FC6668>: Failed to establi
sh a new connection: [WinError 10061] No connection could be made because the ta
rget machine actively refused it',))
On login through python, this error pops up (credentials blanked out)
TimeoutError: Waiting for selector ::-p-xpath(//div[contains(@class,"v-main__wrap")])
failed: Waiting failed: 30000ms exceeded
at new WaitTask (file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/node_modules/puppeteer-core/lib/esm/puppeteer/common/WaitTask.js:47:34)
at IsolatedWorld.waitForFunction (file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/node_modules/puppeteer-core/lib/esm/puppeteer/api/Realm.js:22:26)
at PQueryHandler.waitFor (file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/node_modules/puppeteer-core/lib/esm/puppeteer/common/QueryHandler.js:167:95)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async CdpFrame.waitForSelector (file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/node_modules/puppeteer-core/lib/esm/puppeteer/api/Frame.js:466:21)
at async CdpPage.waitForSelector (file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/node_modules/puppeteer-core/lib/esm/puppeteer/api/Page.js:1287:20)
at async file:///Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/auth.js:91:9
Traceback (most recent call last):
File "/Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/main.py", line 16, in
client = InvestopediaApi(credentials)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/investopedia_api.py", line 10, in init
Session.login(credentials)
File "/Users/roman/PycharmProjects/MaybeInvest/investopedia_simulator_api/session_singleton.py", line 97, in login
raise InvestopediaAuthException("Unable to login with credentials '%s', '%s'" % (credentials['username'],credentials['password']))
session_singleton.InvestopediaAuthException: Unable to login with credentials '', ''
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.