Since you launched the notebook from within venv
, you can access the dependencies installed in that virtual environment by using an import
statement in the notebook. If you install more dependencies later on, remember to relaunch the notebook from the terminal virtual environment before running the import
statement in the notebook.
In the project directory, create a new file called .env
(notice the dot in front of this filename) formatted like .env.example
to store your credentials from the Twilio Console.
This code imports the Python dependencies and loads the environment variables stored in .env
so you can access the Twilio REST API with your credentials.
import requests
import pandas as pd
import os
from dotenv import load_dotenv
load_dotenv()
This makes an HTTP GET
request to the Twilio API to retrieve all of your SMS messages. The data is saved to a variable called messages
that we can use while running subsequent cells. The resulting output is a log statement with a count of your SMS messages and a JSON object of those messages.
accountSID = os.getenv('ACCOUNT_SID')
authToken = os.getenv('AUTH_TOKEN')
url = f'https://api.twilio.com/2010-04-01/Accounts/{accountSID}/Messages.json'
response = requests.get(url, auth=(accountSID, authToken))
messages = response.json()['messages']
print('Number of messages: ', len(messages))
# json is a built-in module for Python - no install required
import json
print(json.dumps(messages, indent=2))
Now that you know how the response from the Twilio API is formatted, you can handle the data like a SQL table using the primary pandas data structure called a DataFrame. Run this code in the next cell of the notebook to see the first five rows of SMS messages.
df = pd.DataFrame(messages)
df.head()
Tidy up the data by displaying only the Date
, Price
, and Direction
of your messages, renaming the columns and formatting the data.
df = df.rename(columns={'price': 'Price', 'direction': 'Direction', 'date_sent': 'Date'})
df['Date'] = pd.to_datetime(df.Date).dt.strftime('%m/%d/%Y')
print(df[['Date','Price', 'Direction']])
ax = df.plot(kind='scatter',x='Date',y='Price')
df[['Date','Price','Direction']].apply(lambda row: ax.text(*row),axis=1);
Show this data in a bar graph, adding up the prices and displaying this information over time.
df['Price'] = df['Price'].astype(float)
df['Date'] = pd.to_datetime(df['Date'])
df['Price'].groupby(df['Date'].dt.to_period('D')).sum().plot(kind='bar', color='red')