I am using this python library to grab a response from the google places API.
Using the places function from the above library returns the object you see below. You can see that is just gives me a boolean on whether the restaurant is open or closed. How can I see the hours it is open for each day of the week? If this library isnt capable of it, can anyone show me an example that is?
Here is the line of code making the request for full context.
import googlemaps # https://googlemaps.github.io/google-maps-services-python/docs/index.html
gmaps = googlemaps.Client(key='apiKey')
response = gmaps.places(query=charlestonBars[idx], location=charleston)
[ { 'business_status': 'OPERATIONAL',
'formatted_address': '467 King St, Charleston, SC 29403, United States',
'geometry': { 'location': {'lat': 32.7890988, 'lng': -79.9386229},
'viewport': { 'northeast': { 'lat': 32.79045632989271,
'lng': -79.93725907010727},
'southwest': { 'lat': 32.78775667010727,
'lng': -79.93995872989272}}},
'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/bar-71.png',
'icon_background_color': '#FF9E67',
'icon_mask_base_uri': 'https://maps.gstatic.com/mapfiles/place_api/icons/v2/bar_pinlet',
'name': "A.C.'s Bar & Grill",
------->'opening_hours': {'open_now': True},
'photos': [ { 'height': 1816,
'html_attributions': [ '<a '
'href="https://maps.google.com/maps/contrib/106222166168758671498">Lisa '
'Royce</a>'],
'photo_reference': 'ARywPAKpP_eyNL_y625xWYrQvSjAI91TzEx4XgT1rwCxjFyQjEAwZb2ha9EgE2RcKJalrZhjp0yTWa6QqvPNU9c7GeNBTDtzXVI0rHq2RXtTySGu8sjcB76keFugOmsl1ix4NnDVh0NO0vt_PO3nIZ-R-ytOzzIRhJgPAJd3SxKNQNfEyVp5',
'width': 4032}],
'place_id': 'ChIJk6nSrWt6_ogRE9KiNXVG5KA',
'plus_code': { 'compound_code': 'Q3Q6+JG Charleston, South Carolina',
'global_code': '8742Q3Q6+JG'},
'price_level': 1,
'rating': 4.3,
'reference': 'ChIJk6nSrWt6_ogRE9KiNXVG5KA',
'types': [ 'bar',
'restaurant',
'point_of_interest',
'food',
'establishment'
What you need to use is the Place Details of Places API
Before we proceed with the solution, we must understand that there's a difference in the result of a Place Search and a Place Details request.
According to the documentation:
"Place Search requests and Place Details requests do not return the same fields. Place Search requests return a subset of the fields that are returned by Place Details requests. If the field you want is not returned by Place Search, you can use Place Search to get a place_id, then use that Place ID to make a Place Details request."
Now what you used on your code according to the python library documentation is the places(*args, **kwargs) which is the Place Search.
The Google Maps API documentation you provided on your comment above where you can get the expected result of hours each day is from Place Details which is the place(*args, **kwargs) from the python library documentation.
As quoted above, to request the detail of a place, you need the place_id which you can get by doing a Places Search request like you did on your question. So what you only need to do is get the place_id of the location you want through Place Search, then use that place_id to get the Place Details result that includes the opening_hours field result.
Here's what it looks like on a python code:
# I used pprint to print the result on the console
from pprint import pprint
import googlemaps #import googlemaps python library
# Instantiate the client using your own API key
API_KEY = 'API_KEY'
map_client = googlemaps.Client(API_KEY)
# Store the location you want, in my case, I tried using 'Mall of Asia'
location_name = 'Mall of Asia'
# Instantiate Place Search request using `places(*args, **kwargs)` from the library
# Use the `stored location` as an argument for query
place_search = map_client.places(location_name)
# Get the search results
search_results = place_search.get('results')
# Store the place_id from the result to be used
place_id = (search_results[0]['place_id'])
# Instantiate Place Details request using the `place(*args, **kwargs)` from the library
# Use the stored place_id as an argument for the request
place_details = map_client.place(place_id)
# Get the Place Details result
details_results = place_details.get('result')
# Print the result specifying what you only need which is the `opening_hours` field
pprint(details_results['opening_hours'])
The result of this sample request would be this:
{'open_now': False,
'periods': [{'close': {'day': 0, 'time': '2200'},
'open': {'day': 0, 'time': '1000'}},
{'close': {'day': 1, 'time': '2200'},
'open': {'day': 1, 'time': '1000'}},
{'close': {'day': 2, 'time': '2200'},
'open': {'day': 2, 'time': '1000'}},
{'close': {'day': 3, 'time': '2200'},
'open': {'day': 3, 'time': '1000'}},
{'close': {'day': 4, 'time': '2200'},
'open': {'day': 4, 'time': '1000'}},
{'close': {'day': 5, 'time': '2200'},
'open': {'day': 5, 'time': '1000'}},
{'close': {'day': 6, 'time': '2200'},
'open': {'day': 6, 'time': '1000'}}],
'weekday_text': ['Monday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Tuesday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Wednesday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Thursday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Friday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Saturday: 10:00\u202fAM\u2009–\u200910:00\u202fPM',
'Sunday: 10:00\u202fAM\u2009–\u200910:00\u202fPM']}
That would be all and I hope this helps! Feel free to comment below if this does not meet your expected results.
Related
I found an old thread ( how can I close position on OKX V5 based on CCXT Python? ) but is not working.
I'm having problem in closing my current margin-spot position. Here's my code:
params = {'tdMode': 'cross', 'ccy': 'USDT'}
order = await self.okx.create_order(
symbol='XRP/USDT', type='market', side='sell',
amount=99.43, price=0.39024, params=params
)
Result:
{'amount': 99.431119,
'average': 0.39005,
'clientOrderId': 'e847386590ce4dBCce71dedc37e12254',
'cost': 38.78310796595,
'datetime': '2022-12-02T17:29:58.048Z',
'fee': {'cost': 0.03878310796595, 'currency': 'USDT'},
'fees': [{'cost': 0.03878310796595, 'currency': 'USDT'}],
'filled': 99.431119,
'id': '518962064594153472',
Places the first order correctly. Now to close this order I use barrely the same code, changing sides:
params = {'tdMode': 'cross', 'ccy': 'USDT'}
order = await self.okx.create_order(
symbol='XRP/USDT', type='market', side='buy',
amount=99.43, price=0.39017, params=params
)
Problem is that the amount in the second order seeems to be 'contracts'/'price' instead:
result:
{'amount': 99.43111,
'average': 0.39015,
'clientOrderId': 'e847386590ce4dBC328bc6dfc937795f',
'cost': 99.43110980145,
'datetime': '2022-12-02T17:36:47.913Z',
'fee': {'cost': 0.254853543, 'currency': 'XRP'},
'fees': [{'cost': 0.254853543, 'currency': 'XRP'}],
'filled': 254.853543,
'id': '518963783692562432',
What am I doing wrong ?
Are you changing the default tgtCcy value?
Can you try to place the market order without the price (market orders execute at the market price so you don't need to specify it)?
I am trying to write a code to return a list of stock tickers when entering a sector name.
for example, MSFT is in the technology sector in yfinance and I want the remaining companies that belong to this particular sector.
import yfinance as yf
msft= yf.Ticker("MSFT")
print(msft.info['sector'])
this code will return "Technology", how to get a dataframe
that contains other stocks.
and is it possible to get a more specific sector category such as "Communication" which is more specific than "technology"?
That data can be retrieved pretty easily with a package called yahooquery. Disclaimer: I am the author of the package.
To get stocks in the technology sector, you can do the following:
from yahooquery import Screener
s = Screener()
# data is a dictionary containing the keys passed to the function
data = s.get_screeners('ms_technology', count=25)
# the majority of the data will be in the quotes key
data['ms_technology']['quotes'][0]
{'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Delayed Quote', 'triggerable': True, 'currency': 'USD', 'priceHint': 2, 'longName': 'Apple Inc.', 'financialCurrency': 'USD', 'regularMarketOpen': 123.75, 'averageDailyVolume3Month': 106246233, 'averageDailyVolume10Day': 137149760, 'fiftyTwoWeekLowChange': 74.6375, 'fiftyTwoWeekLowChangePercent': 1.4042143, 'fiftyTwoWeekRange': '53.1525 - 145.09', 'fiftyTwoWeekHighChange': -17.299995, 'fiftyTwoWeekHighChangePercent': -0.119236305, 'fiftyTwoWeekLow': 53.1525, 'fiftyTwoWeekHigh': 145.09, 'dividendDate': 1613001600, 'earningsTimestamp': 1611765000, 'earningsTimestampStart': 1619607540, 'earningsTimestampEnd': 1620043200, 'trailingAnnualDividendRate': 0.807, 'trailingPE': 34.659615, 'trailingAnnualDividendYield': 0.0066551208, 'marketState': 'POSTPOST', 'epsTrailingTwelveMonths': 3.687, 'epsForward': 4.68, 'epsCurrentYear': 4.45, 'priceEpsCurrentYear': 28.716856, 'sharesOutstanding': 16788100096, 'bookValue': 3.936, 'fiftyDayAverage': 132.6306, 'fiftyDayAverageChange': -4.840599, 'fiftyDayAverageChangePercent': -0.036496848, 'twoHundredDayAverage': 122.9772, 'twoHundredDayAverageChange': 4.8127975, 'twoHundredDayAverageChangePercent': 0.039135687, 'marketCap': 2145351368704, 'forwardPE': 27.305557, 'priceToBook': 32.466972, 'sourceInterval': 15, 'exchangeDataDelayedBy': 0, 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EST', 'gmtOffSetMilliseconds': -18000000, 'esgPopulated': False, 'tradeable': True, 'firstTradeDateMilliseconds': 345479400000, 'postMarketChangePercent': 0.7434107, 'postMarketTime': 1614646799, 'postMarketPrice': 128.74, 'postMarketChange': 0.9500046, 'regularMarketChange': 6.529999, 'regularMarketTime': 1614632402, 'regularMarketPrice': 127.79, 'regularMarketDayHigh': 127.93, 'regularMarketDayRange': '122.79 - 127.93', 'regularMarketDayLow': 122.79, 'regularMarketVolume': 116307692, 'regularMarketPreviousClose': 121.26, 'bid': 128.74, 'ask': 128.75, 'bidSize': 10, 'askSize': 11, 'exchange': 'NMS', 'market': 'us_market', 'messageBoardId': 'finmb_24937', 'fullExchangeName': 'NasdaqGS', 'shortName': 'Apple Inc.', 'regularMarketChangePercent': 5.385122, 'displayName': 'Apple', 'symbol': 'AAPL'}
Put the data into a pandas DataFrame:
df = pd.DataFrame(data['ms_technology']['quotes'])
Retrieve multiple screeners at once:
data = s.get_screeners(['ms_technology', 'ms_utilities', 'ms_real_estate'])
Finally, view the list of available predefined screeners with the following:
# Will return a list
s.available_screeners
You're looking for 'industry' to get a more granular description:
msft= yf.Ticker("MSFT")
print(msft.info['industry'])
print(msft.info) to view the json file to see what is available. yFinance does not provide the same amount of information for all ticker symbols.
This is from an R guy.
I have this mess in a Pandas column: data['crew'].
array(["[{'credit_id': '54d5356ec3a3683ba0000039', 'department': 'Production', 'gender': 1, 'id': 494, 'job': 'Casting', 'name': 'Terri Taylor', 'profile_path': None}, {'credit_id': '56407fa89251417055000b58', 'department': 'Sound', 'gender': 0, 'id': 6745, 'job': 'Music Editor', 'name': 'Richard Henderson', 'profile_path': None}, {'credit_id': '5789212392514135d60025fd', 'department': 'Production', 'gender': 2, 'id': 9250, 'job': 'Executive In Charge Of Production', 'name': 'Jeffrey Stott', 'profile_path': None}, {'credit_id': '57892074c3a36835fa002886', 'department': 'Costume & Make-Up', 'gender': 0, 'id': 23783, 'job': 'Makeup Artist', 'name': 'Heather Plott', 'profile_path': None}
It goes on for quite some time. Each new dict starts with a credit_id field. One sell can hold several dicts in an array.
Assume I want the names of all Casting directors, as shown in the first entry. I need to check check the job entry in every dict and, if it's Casting, grab what's in the name field and store it in my data frame in data['crew'].
I tried several strategies, then backed off and went for something simple.
Running the following shut me down, so I can't even access a simple field. How can I get this done in Pandas.
for row in data.head().iterrows():
if row['crew'].job == 'Casting':
print(row['crew'])
EDIT: Error Message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-138-aa6183fdf7ac> in <module>()
1 for row in data.head().iterrows():
----> 2 if row['crew'].job == 'Casting':
3 print(row['crew'])
TypeError: tuple indices must be integers or slices, not str
EDIT: Code used to get the array of dict (strings?) in the first place.
def convert_JSON(data_as_string):
try:
dict_representation = ast.literal_eval(data_as_string)
return dict_representation
except ValueError:
return []
data["crew"] = data["crew"].map(lambda x: sorted([d['name'] if d['job'] == 'Casting' else '' for d in convert_JSON(x)])).map(lambda x: ','.join(map(str, x))
To create a DataFrame from your sample data, write:
df = pd.DataFrame(data=[
{ 'credit_id': '54d5356ec3a3683ba0000039', 'department': 'Production',
'gender': 1, 'id': 494, 'job': 'Casting', 'name': 'Terri Taylor',
'profile_path': None},
{ 'credit_id': '56407fa89251417055000b58', 'department': 'Sound',
'gender': 0, 'id': 6745, 'job': 'Music Editor',
'name': 'Richard Henderson', 'profile_path': None},
{ 'credit_id': '5789212392514135d60025fd', 'department': 'Production',
'gender': 2, 'id': 9250, 'job': 'Executive In Charge Of Production',
'name': 'Jeffrey Stott', 'profile_path': None},
{ 'credit_id': '57892074c3a36835fa002886', 'department': 'Costume & Make-Up',
'gender': 0, 'id': 23783, 'job': 'Makeup Artist',
'name': 'Heather Plott', 'profile_path': None}])
Then you can get your data with a single instruction:
df[df.job == 'Casting'].name
The result is:
0 Terri Taylor
Name: name, dtype: object
The above result is Pandas Series object with names found.
In this case, 0 is the index value for the record found and
Terri Taylor is the name of (the only in your data) Casting Director.
Edit
If you want just a list (not Series), write:
df[df.job == 'Casting'].name.tolist()
The result is ['Terri Taylor'] - just a list.
I think, both my solutions should be quicker than "ordinary" loop
based on iterrows().
Checking the execution time, you may try also yet another solution:
df.query("job == 'Casting'").name.tolist()
==========
And as far as your code is concerned:
iterrows() returns each time a pair containing:
the key of the current row,
a named tuple - the content of this row.
So your loop should look something like:
for row in df.iterrows():
if row[1].job == 'Casting':
print(row[1]['name'])
You can not write row[1].name because it refers to the index value
(here we have a collision with default attributes of the named tuple).
I'm trying to create small web app which will work with user Google Calendar data. Everything works fine except getting start datetime for events with 'recurrence' in item.keys().
Question: How can I get start time of event from given data:
{'kind': 'calendar#event',
'sequence': 0,
'htmlLink': 'link',
'creator': {my info},
'location': '...',
'summary': '...',
'etag': '"etag"',
'organizer': {org_info},
'status': 'confirmed',
'reminders': {'useDefault': True},
'created': '2016-09-18T07:02:56.000Z',
'id': event_id,
'iCalUID': 'iCalUID',
'start': {'timeZone': 'Europe/Moscow', 'dateTime': '2016-09-07T14:35:00+03:00'},
'updated': '2016-09-18T07:02:56.612Z',
'description': '...',
'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;INTERVAL=2;BYDAY=WE'],
'end': {'timeZone': 'Europe/Moscow', 'dateTime': '2016-09-07T16:10:00+03:00'}}
My idea was to parse somehow RRULE, I've found way to get list of datetimes from it, but how to get this event start time is still question for me.
I'm getting data with service.events().list(...).execute()
I know that in the new API (i found this only today) item has nice called originStartTime, but old events don't have thing.
StackOverflow magic: I was trying to find solution for 2 days, only after posting the question I've found method or function which does exactly what I needed events().instances()
I'm building API for my app in Python and Flask. I'm trying to output some data in JSON format, however I get weirdly formatted data from my sql query. I would like to see numbers (i.e. field initial_price) as number, not as a Decimal('3.99'), similarly with id and timestamp format.
Also, is it the right way to produce JSON?
This is output from my API:
$ curl 127.0.0.1:5000/1/product?code="9571%2F702"
[{'update_time': datetime.datetime(2013, 1, 7, 22, 25, 50), 'code': '9571/702', 'description': '', 'gender': '', 'brand': 'Zara', 'initial_price': Decimal('3.99'), 'image_link': 'http://static.zara.net/photos//2012/I/0/3/p/9571/702/401/9571702401_1_1_3.jpg', 'currency': 'GBP', 'colors': 'NAVY', 'link': 'http://www.zara.com/webapp/wcs/stores/servlet/product/uk/en/zara-neu-W2012-s/341501/883021/', 'current_price': Decimal('990.00'), 'original_category': 'Girl (2-14 years)', 'id': 1623L, 'name': '"I LOVE ..." T-SHIRT'},
{'update_time': datetime.datetime(2013, 1, 7, 22, 25, 50), 'code': '9571/702', 'description': '', 'gender': '', 'brand': 'Zara', 'initial_price': Decimal('3.99'), 'image_link': 'http://static.zara.net/photos//2012/I/0/3/p/9571/702/401/9571702401_1_1_3.jpg', 'currency': 'GBP', 'colors': 'LIGHT', 'link': 'http://www.zara.com/webapp/wcs/stores/servlet/product/uk/en/zara-neu-W2012-s/341501/883021/', 'current_price': Decimal('990.00'), 'original_category': 'Girl (2-14 years)', 'id': 1624L, 'name': '"I LOVE ..." T-SHIRT'},
{'update_time': datetime.datetime(2013, 1, 7, 22, 25, 50), 'code': '9571/702', 'description': '', 'gender': '', 'brand': 'Zara', 'initial_price': Decimal('3.99'), 'image_link': 'http://static.zara.net/photos//2012/I/0/3/p/9571/702/401/9571702401_1_1_3.jpg', 'currency': 'GBP', 'colors': 'ECRU', 'link': 'http://www.zara.com/webapp/wcs/stores/servlet/product/uk/en/zara-neu-W2012-s/341501/883021/', 'current_price': Decimal('990.00'), 'original_category': 'Girl (2-14 years)', 'id': 1625L, 'name': '"I LOVE ..." T-SHIRT'}]
My code is as following:
from flask import Flask, url_for, session, redirect, escape, request
from subprocess import Popen, PIPE
import socket
import MySQLdb
import urllib
#app.route('/1/product')
def product_search():
[some not important stuff here...]
#creating list of codes with lowest Damerau-Levenshtein numbers
best_matching_codes = []
for k, v in lv:
if v == min:
best_matching_codes.append(k)
#returning JSON with best matching products info
products_json = []
for code in best_matching_codes:
cur = db.cursor()
query = "SELECT * FROM %s WHERE code LIKE '%s'" % (PRODUCTS_TABLE_NAME, product_code)
cur.execute(query)
columns = [desc[0] for desc in cur.description]
rows = cur.fetchall()
for row in rows:
products_json.append(dict((k,v) for k,v in zip(columns,row)))
return str(products_json)
Use the json module. It will output proper json from a dict:
import json
return json.dumps(products_json)
Using str does not produce valid json!
You need to use a json library to produce json.
Add to top:
import json
Change last line to:
return json.dumps(products_json)