Created
August 17, 2020 15:38
-
-
Save enkeboll/a72ea43048ce43dc0d6ac7b7078b7884 to your computer and use it in GitHub Desktop.
IEX Lambda App Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Automation demo - Andy.ipynb | |
Automatically generated by Colaboratory. | |
Original file is located at | |
https://colab.research.google.com/drive/1ehWn8-jcItWIFNFhKWUdZBOF0DAdMvll | |
## Automating the process | |
First, two important things to do to follow along with lecture: | |
1. Register for a free [SendGrid account](https://signup.sendgrid.com/) and verify a [single sender address](https://sendgrid.com/docs/ui/sending-email/sender-verification/) | |
2. Register for a free [Heroku account](https://signup.heroku.com/) | |
The goal of today is to automate the retreival of data from an API, formatting as an excel file, and delivery to our email. We're going to use IEX today, because it's easy. | |
""" | |
import requests | |
import os | |
import pandas as pd | |
from datetime import datetime | |
from urllib.parse import urljoin | |
# for sending an email | |
import email, smtplib, ssl | |
from email import encoders | |
from email.mime.base import MIMEBase | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
base_url = 'https://cloud.iexapis.com/stable/' | |
endpoint = 'stock/{}/quote' | |
IEX_KEY = os.getenv('IEX_API_KEY') | |
SENDGRID_KEY = os.getenv('SENDGRID_API_KEY') | |
params = {'token': IEX_KEY} | |
stocks = ['AAPL', 'LULU', 'KR'] | |
quotes = [] | |
for stock in stocks: | |
request_time = datetime.utcnow() | |
resp = requests.get(urljoin(base_url, endpoint.format(stock)), params=params) | |
print(resp.json()) | |
if resp.status_code == 200: | |
quote = resp.json() | |
quote['request_time'] = request_time | |
quotes.append(quote) | |
quotes | |
df = pd.DataFrame(quotes) | |
df | |
datetime.utcnow().isoformat()[:16] | |
output_filename = 'quotes-{}.xlsx'.format(datetime.utcnow().isoformat()[:16]) | |
df.to_excel(output_filename) | |
# !ls | |
# send email with attachment using any SMTP service | |
# copied and pasted from https://realpython.com/python-send-email/#adding-attachments-using-the-email-package | |
subject = "IEX Stock Report for {}".format(datetime.utcnow().isoformat()[:16]) | |
body = "Wow Andy, you're looking great today!" | |
sender_email = "andy.enkeboll@flatironschool.com" | |
receiver_email = "andy.enkeboll+stockreport@flatironschool.com" | |
password = SENDGRID_KEY | |
# Create a multipart message and set headers | |
message = MIMEMultipart() | |
message["From"] = sender_email | |
message["To"] = receiver_email | |
message["Subject"] = subject | |
# Add body to email | |
message.attach(MIMEText(body, "plain")) | |
# Open PDF file in binary mode | |
with open(output_filename, "rb") as attachment: | |
# Add file as application/octet-stream | |
# Email client can usually download this automatically as attachment | |
part = MIMEBase("application", "octet-stream") | |
part.set_payload(attachment.read()) | |
# Encode file in ASCII characters to send by email | |
encoders.encode_base64(part) | |
# Add header as key/value pair to attachment part | |
part.add_header( | |
"Content-Disposition", | |
f"attachment; filename= {output_filename}", | |
) | |
# Add attachment to message and convert message to string | |
message.attach(part) | |
text = message.as_string() | |
# Log in to server using secure context and send email | |
context = ssl.create_default_context() | |
with smtplib.SMTP_SSL("smtp.sendgrid.net", 465, context=context) as server: | |
server.login('apikey', password) # 'apikey' is sendgrid specific! | |
server.sendmail(sender_email, receiver_email, text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment