Get your heart rate from the fitbit API in Python!

Multi-function wearable terminal fitbit charge 2!

FullSizeRender.jpg のコピー.jpg

For some reason, I recently got the popular wearable terminal fitbit charge2, so I'd like to play with it. Since fitbit has an official API, we will use this to get the heart rate in Python and graph it.

【environment】 ・ OS X EL Capitan · Python 3.5.2

API preparation

Get the ID etc. required for API

Creating an application

Log in to https://dev.fitbit.com/login with your fitbit account and create a new application from the ** REGISTER AN APP * tab.

item name Contents
Application Name Application name(suitable)
Description Application description(suitable)
Application Website URL of the application(suitable)
Organization Affiliation organization
Organization Website URL of your organization
OAuth 2.0 Application Type App type(Select Client or Personal)
Callback URL http://127.0.0.1:8080/Enter
Default Access Type Since the data is not changed here, Read-Select Only

Get Client ID and Client Secret

When you create the application, you can get the (OAuth 2.0) Client ID and Client Secret from ** MANAGE MY APPS **, so make a note of this. スクリーンショット 2017-02-01 23.33.24.png

Set OAuth 2.0 Application Type to Personal

Open the ** Edit Application Settings ** page from * MANAGE MY APPS * and set OAuth 2.0 Application Type to Personal. スクリーンショット 2018-01-16 0.10.01.png If you want to get time series data such as minutes, you need to set it to Personal. (Reference: https://dev.fitbit.com/build/reference/web-api/activity/)

Get Access Token and Refresh Token

It's a little troublesome from here. Start the terminal. Move to an appropriate directory and copy and paste the following command to the terminal to execute it.

Terminal


git clone https://github.com/orcasgit/python-fitbit.git 

How to use the terminal here If you get an error with the git command here

Next, copy and paste the following command to the terminal and execute it. Replace [OAuth 2.0 Client ID] and [Client Secret] with the values you got earlier.

python-fitbit/gather_keys_oauth2.py 【OAuth 2.0 Client ID】 【Client Secret】


Then the browser will start and スクリーンショット 2017-02-01 12.12.52.png Since such an authentication screen is displayed, check the necessary items and [Allow](I checked all for the time being).

When you return to the terminal,

Terminal


access_token = XXXXXXXXXXXXXXXXXXXXXX
refresh_token == YYYYYYYYYYYYYYYYYYYYYYYYY

Is displayed, so make a note of this. Obtained ・ Client ID ・ Client Secret ・ Ass and Ken ・ Refresh Token Make a note of the value of and save it.

Get data using Python

Python coding was done in Jupyter.

Because it uses the python-fitbit library

Terminal


pip install fitbit

I will do it. python-fitbit GitHub python-fitbit commentary

Data acquisition


import fitbit
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

#ID etc. that you wrote down
CLIENT_ID =  "XXXXXXXXXXXXXXXXXXXXXXX"
CLIENT_SECRET  = "XXXXXXXXXXXXXXXXXXXXXXX"
ACCESS_TOKEN =  "XXXXXXXXXXXXXXXXXXXXXXX"
REFRESH_TOKEN =  "XXXXXXXXXXXXXXXXXXXXXXX"

#Date you want to get
DATE = "2017-01-31"

#ID etc. settings
authd_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET
                             ,access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
#Get heart rate (in 1 second)
data_sec = authd_client.intraday_time_series('activities/heart', DATE, detail_level='1sec') #'1sec', '1min', or '15min'
heart_sec = data_sec["activities-heart-intraday"]["dataset"]
heart_sec[:10]

Output result


[{'time': '00:00:02', 'value': 56},
 {'time': '00:00:07', 'value': 55},
 {'time': '00:00:12', 'value': 54},
 {'time': '00:00:17', 'value': 54},
 {'time': '00:00:32', 'value': 54},
 {'time': '00:00:37', 'value': 56},
 {'time': '00:00:42', 'value': 55},
 {'time': '00:00:52', 'value': 58},
 {'time': '00:01:07', 'value': 58},
 {'time': '00:01:09', 'value': 57}]

I have a heart rate! I'm getting data for 24 hours from midnight, but I'm not getting data every second without getting everything, but rather I'm getting less seconds.

By setting the argument detail_level to "1min" and "15min", you can get it in 1-minute or 15-minute units.

Process the data and plot

Data frame of dict type data


heart_df = pd.DataFrame.from_dict(heart_sec)
print(heart_df.shape)
heart_df.head()
スクリーンショット 2017-02-02 0.30.25.png

From_dict is very convenient because it converts dict type data to dataframe in one shot.

index to time series data


heart_df.index = pd.to_datetime([DATE + " " + t for t in heart_df.time])
heart_df.head()
スクリーンショット 2017-02-02 0.34.26.png Convert index to time series data because it is easy to plot. 1. 1. Create a string that connects date and time in list comprehension notation 2. Convert string list to datetimeIndex with to_datetime. 3. 3. Change the index of the dataframe.

pandas plot

plot


heart_df.plot(y="value", figsize=(20,5))
heart_df.head()

0JblsRxM2NAAAAAAElFTkSuQmCC.png

Your heart rate is low during sleep from 1:30 to 8:00. Well analysis is coming again!

Recommended

"Kimchi pot where you can eat 1/2 of the vegetables you need in a day" @ Seven-Eleven

Recommended Posts

Get your heart rate from the fitbit API in Python!
Save your heart rate to SpreadSheets in real time (?) Using Python x fitbit API!
[Python] Get the text of the law from the e-GOV Law API
Put the exchange rate obtained from Oanda REST API in Python into MongoDB
Getting the arXiv API in Python
Get data from Quandl in Python
Hit the Sesami API in Python
Get the desktop path in Python
Get the script path in Python
Get the value while specifying the default value from dict in Python
Hit the web API in Python
Use the Flickr API from Python
Get upcoming weather from python weather api
Get the desktop path in Python
Get the host name in Python
Access the Twitter API in Python
How to get followers and followers from python using the Mastodon API
Hit the New Relic API in Python to get the server status
Get exchange rates from open exchange rates in Python
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Get Google Fit API data in Python
Get Youtube data in Python using Youtube Data API
Get battery level from SwitchBot in Python
Try hitting the YouTube API in Python
Get the EDINET code list in Python
Get Precipitation Probability from XML in Python
[Python] Get the main color from the screenshot
Get metric history from MLflow in Python
Get your own IP address in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Get time series data from k-db.com in Python
Get the contents of git diff from python
[Python] Get the files in a folder with Python
Get the weather in Osaka via WebAPI (python)
Get the caller of a function in Python
Try using the BitFlyer Ligntning API in Python
Get image URL using Flickr API in Python
Tips for hitting the ATND API in Python
Get the X Window System window title in Python
Use Python in your environment from Win Automation
How to get the files in the [Python] folder
Hit the Firebase Dynamic Links API in Python
Get only articles from web pages in Python
Try accessing the YQL API directly from Python 3
Try using the DropBox Core API in Python
Get users belonging to your organization from Garoon REST API with Python + Requests
Evernote API in Python
Get date in Python
C API in Python 3
How to get the variable name itself in python
Translator in Python from Visual Studio 2017 (Microsoft Translator Text API)
How to get the number of digits in Python
Initial settings when using the foursquare API in python
[Python] Get the numbers in the graph image with OCR
Output the time from the time the program was started in python
[python] Get the list of classes defined in the module
Get LEAD data using Marketo's REST API in Python
Get schedule from Garoon SOAP API with Python + Zeep
Get data from GPS module at 10Hz in Python
Get the return code of the Python script from bat