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
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
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.
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