0

I have a little code that doesn't work;

yahoo = Share('YHOO')
a = yahoo.get_price() #get price of stock
print "ok" if 45 <= a <= 50 else "no"

It is always printing "no" even when the stock price is 45.55

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Mr. R.A.
  • 3
  • 1

2 Answers2

3

Assuming that you're using yahoo-finance (in which case, it would have been helpful to say so in your question), Share.get_price() returns a string:

>>> from yahoo_finance import Share
>>> yahoo = Share('YHOO')
>>> print yahoo.get_open()
'36.60'
>>> print yahoo.get_price()
'36.84'

So, you'll have to convert it to a Decimal object before doing any math or numeric comparison with it:

from decimal import Decimal

yahoo = Share('YHOO')
a = Decimal(yahoo.get_price())
print "ok" if 45 <= a <= 50 else "no"

Decimal is preferable to float if you're dealing with currency information, to avoid rounding errors.

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • Your solution works great. It all makes logical now (converting to decimal before comparing it with math). Also forget to mention the modules that I imported. Thanks! – Mr. R.A. Feb 27 '17 at 01:34
0

it may be the case that you get a string instead of a number

>>> a=45.55   #float
>>> 45 <= a <= 50
True
>>> a="45.55"  #string
>>> 45 <= a <= 50
False
>>> 

to know the type do

>>> type("45.55")
<type 'str'>
>>> type(45.55)
<type 'float'>
>>> 

for your code to work properly you need to get one of the numeric types int, long or float for the build-in, (also Fraction and Decimal build-in too, but you need to import them)

to fix your code just cast it to the correct numeric type like float or Decimal

Copperfield
  • 8,131
  • 3
  • 23
  • 29