1

I'm using the google finance module to get stock data in Python. I would like to isolate the LastTradePrice from the list and convert it into an integer. Any suggestions? Thanks.

from googlefinance import getQuotes
import json

stockinfo = getQuotes('VSMGX')

stockdata = json.dumps(stockinfo, indent=1)

The stockdata looks like this

[
 {
  "ID": "904726512134516",
  "LastTradeDateTimeLong": "Jan 8, 4:00PM EST",
  "Index": "MUTF",
  "LastTradeWithCurrency": "$22.26",
  "LastTradeTime": "4:00PM EST",
  "StockSymbol": "VSMGX",
  "LastTradePrice": "22.26",
  "LastTradeDateTime": "2016-01-08T16:00:00Z"
 }
]
Bandito
  • 21
  • 2
  • 2
    You really want it is an integer? `22.26` would come back as `22`. Anything wrong with `[float(d['LastTradePrice']) for d in stockdata]`. BTW `info1` doesn't exist - did you mean `stockinfo`? – AChampion Jan 09 '16 at 18:46
  • Yeah, I should be using a float. Thank you! Your answer worked – Bandito Jan 09 '16 at 20:40
  • Oops, I just wrote the same code as @AChampion, token for token! Well, it _is_ an idiom :-) – alexis Jan 09 '16 at 20:53

2 Answers2

1

If all records have a last trade price, just use a list comprehension:

tradePrices = [ float(d["LastTradePrice"]) for d in stockdata ]

Edit: Convert it to float as @mattsap recommended. Well spotted!

alexis
  • 48,685
  • 16
  • 101
  • 161
0

Actually, you want a float, since the lastTradePrice has decimals. Iterate over the list and extract the dictionary's value for the key of last trade price.

lastTradedPrices = []
for data in stockdata:
    lastTradedPrices.append(float(data["LastTradePrice"]))
mattsap
  • 3,790
  • 1
  • 15
  • 36