from yahoo_finance import Share yahoo = Share('YHOO') yahoo.get_historical2('2014-04-25', '2014-05-29')
def action_WolfBot_History(intent_request): """ Performs dialog management and fulfillment for doing stock history Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting. """ symbol = get_slots(intent_request)['symbol'] #get symbol data if symbol is None: try: utter = intent_request["inputTranscript"] except: utter = "This is empty" #extract symbol from utter try: #break the string into a list, and then pick the one with the $ symbol phrase_list = utter.split(" ") for element in phrase_list: if "$" in element: symbol_manual = element.strip("$") get_slots( intent_request )['symbol'] = symbol_manual #force the value in, this allows to break out of the strict slot criteria symbol = symbol_manual else: symbol = "" except: #if there's no element, aka no check $ return close( intent_request['sessionAttributes'], 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Closing1... Try again with a valid symbol. E.g. $AMZN' }) # prepping the values slots = get_slots(intent_request) symbol = get_slots(intent_request)['symbol'] #using last days method, force values into intent_request try: if get_slots(intent_request)['days'] is not None: get_slots(intent_request)['start_date'] = str( datetime.date.today() - datetime.timedelta( days=int(get_slots(intent_request)['days']))) get_slots(intent_request)['end_date'] = str(datetime.date.today()) except KeyError: pass start_date = get_slots(intent_request)['start_date'] end_date = get_slots(intent_request)['end_date'] source = intent_request['invocationSource'] # verify symbol try: #scrub out the dollar symbol if '$' in symbol: symbol = symbol.strip('$') symbol_result = Share(symbol) if symbol_result.get_price() is None: return close( intent_request['sessionAttributes'], 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Closing2... {}'.format(symbol) }) except: return close( intent_request['sessionAttributes'], 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Closing3... {} {} {} {}'.format(symbol, start_date, end_date, sys.exc_info()[0]) }) #start sussing it out if source == "DialogCodeHook": #determine the symbol symbol = get_slots(intent_request)['symbol'] # Using date questioning method (default) # Perform basic validation on the supplied input slots. # Use the elicitSlot dialog action to re-prompt for the first violation detected. validation_result = validate_action_WolfBot_History( symbol, start_date, end_date) if not validation_result['isValid']: slots[validation_result['violatedSlot']] = None return elicit_slot(intent_request['sessionAttributes'], intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message']) #scrub out the dollar symbol - why is this everywhere? because I don't know what keeps adding the $ back into symbol lol if '$' in symbol: symbol = symbol.strip('$') symbol_result_history = Share(symbol) try: symbol_result = lookup2(symbol) symbol_history = symbol_result_history.get_historical2( start_date, end_date) except: return close( intent_request['sessionAttributes'], 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Closing4... Try again with a valid symbol. E.g. $AMZN' }) #formatting trade_time = symbol_result["trade_time"].split(" UTC") trade_time = trade_time[0] #building the content to deliver content = "" #build with first day and last day content = "{} starts at {:.2f} on {} and ends at {:.2f} on {}".format( symbol, float(symbol_history[0]["Adj_Close"]), symbol_history[0]["Date"], float(symbol_history[-1]["Adj_Close"]), symbol_history[-1]["Date"]) #staging imgur client - use https://api.imgur.com/oauth2/addclient client_id = 'GET_YOUR_OWN' client_secret = 'GET_YOUR_OWN' client = ImgurClient(client_id, client_secret) # filter the output output_filter = [] for element_dict in symbol_history: output_filter.append({ k: element_dict[k] for k in element_dict.keys() & {'Date', 'Adj_Close'} }) # set up X data X_date = [] for element_dict in output_filter: X_date.append(element_dict['Date']) # set up Y data Y_close = [] for element_dict in output_filter: Y_close.append(element_dict['Adj_Close']) # use xticks because matplotlib doesn't like strings plt.plot(Y_close) plt.xticks(range(len(X_date)), X_date) plt.title("{} Starts: {} Ends: {}".format(symbol, start_date, end_date)) #make sure its empty try: os.remove('/tmp/foo.png') except: pass #save, generate, delete plt.savefig('/tmp/foo.png') callback = client.upload_from_path("/tmp/foo.png", config=None, anon=True) imgur_link = callback['link'] plt.gcf().clear() os.remove('/tmp/foo.png') ''' return close(intent_request['sessionAttributes'], 'Fulfilled', {'contentType': 'PlainText', 'content': content + " " + imgur_link}) ''' #using response card response = { "sessionAttributes": intent_request["sessionAttributes"], "dialogAction": { "type": "Close", 'fulfillmentState': "Fulfilled", "message": { "content": "Showing ${} between {} and {}".format(symbol_result["symbol"], start_date, end_date), "contentType": "PlainText" }, "responseCard": { "version": 1, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [{ "title": "{}".format(symbol_result["name"]), "subTitle": "{} {} ({}) {}".format(symbol_result["price"], symbol_result["change"], symbol_result["pc_change"], trade_time), "imageUrl": "{}".format(imgur_link), "buttons": [{ "text": "Buy", "value": "buy" }, { "text": "Sell", "value": "sell" }] }] } } } return response