Get the trading price of virtual currency and create a chart with API of Zaif exchange

environment

- MacOS Sierra 10.12.6
- Python 3.5.3 :: Anaconda 4.4.0 (x86_64)
- Jupyter 4.3.0

background

――Zaif exchange is a valuable virtual currency exchange with virtual currencies that can be bought and sold in pairs with Japanese yen only here, such as NEM and Monacoin, as well as Bitcoin. --The Zaif exchange can make its website so heavy that it can't even log in, let alone trade, if the volume of transactions surges, such as when Bitcoin-related (mainly negative) news is reported.

problem

--If you cannot log in to the Zaif exchange, it will be accurate (especially) for cryptocurrencies that are not traded in pairs with Japanese yen other than the Zaif exchange, or are traded only on the Zaif exchange such as Zaif tokens. You will not be able to know the price movement.

Solution

--The Zaif exchange publishes an API that allows you to obtain trading price information and make transactions, and even if the website is heavy, the API often survives. Therefore, if you periodically acquire the trading price with the API and display the chart, you can check the price movement even if you can not log in to the website. -** Click here for the created one (chart is updated every 5 minutes): ** https://zaifcharts.hateblo.jp/ --Click here for how to buy and sell with API after checking the chart: Buy and sell virtual currency using Zaif API

specification

Create a script that acquires trading price information from the Zaif exchange and writes it to a csv file, and a script that creates a chart from the written csv file, and execute them regularly with cron.

Obtain trading price information from Zaif exchange

--Import required modules such as pandas, numpy, json, etc.

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
from datetime import datetime
import time
import json
import requests
import csv
import sys, codecs

--Get the current time (to make it the horizontal axis of the chart)

date = datetime.now().strftime("%Y/%m/%d %H:%M:%S")

--Get the latest trading price using the API of Zaif exchange (only BTC is described below, the same applies to other virtual currencies)

response = requests.get('https://api.zaif.jp/api/1/last_price/btc_jpy')
if response.status_code != 200:
    raise Exception('return status code is {}'.format(response.status_code))
res_dict = json.loads(response.text)
btc_price = res_dict['last_price']
#[Current time, selling price]Create a list of
btc_list = [date, btc_price]

--Write the acquired trading price to a csv file (only BTC is described below, the same applies to other virtual currencies)

f = open("/var/www/html/zaif/btc.csv", "a")
writer = csv.writer(f, lineterminator='\n')
writer.writerow(btc_list)
f.close()

If you execute a script that includes an operation to write to a file with cron, the following error may be output and you may not be able to execute it.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 720: ordinal not in range(128)

This time, I avoided the error by writing ʻexport LANG = ja_JP.UTF-8;` in crontab as shown below.

0,5,10,15,20,25,30,35,40,45,50,55 * * * * export LANG=ja_JP.UTF-8; runipy /home/user/Get_Zaif_data.ipynb

Create a chart from the acquired trading price information

--Import required modules such as matplotlib

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
from datetime import datetime
import time
import json
import requests
import csv
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
%matplotlib inline
import seaborn as sns
sns.set_style('whitegrid')
rcParams['figure.figsize'] = 20, 10
from matplotlib.dates import DateFormatter

--Read csv file and create Dataframe (The following describes only BTC, the same applies to other virtual currencies)

btc_df = pd.read_csv("/var/www/html/zaif/btc.csv", names = ("date", "BTC price"))

--Extract only the period for creating the chart (3 days in the example below)

btc_df = btc_df[-864:-1]

--Mold the date column of btc_df into hh: mm format

date_df = btc_df["date"].str[10:16]
btc_df = pd.concat([date_df, btc_df["BTC price"]], axis=1)

--Calculate BTC bollinger band (The following describes only BTC, the same applies to other virtual currencies)

rm = btc_df.set_index("date").rolling(window=24).mean()
rstd = btc_df.set_index("date").rolling(window=24).std()
upper_band = rm + rstd * 2
lower_band = rm - rstd * 2

--Create a chart from Dataframe (The following describes only BTC, the same applies to other virtual currencies)

ax = btc_df.set_index("date").plot()
rm.columns = ["Rolling mean"]
rm.plot(ax=ax, color="#8FBC8F")
upper_band.columns = ["Upper band"]
upper_band.plot(ax=ax, color="#F4A460")
lower_band.columns = ["Lower band"]
lower_band.plot(ax=ax, color="#F4A460")
plt.legend(loc='best',
           fontsize=14,
           borderaxespad=0.,)
plt.tick_params(labelsize=14)
plt.savefig("/var/www/html/zaif/btc.png ")

--Created chart btc_chart.png

Summary

--By creating a chart from the trading price information obtained from the API, you can now check the price movements of virtual currencies traded on the Zaif exchange even if you cannot log in to the Zaif exchange website. --Even if you can log in to the Zaif exchange website, it is convenient to have a page that can list the charts of each virtual currency (on the Zaif exchange website, you can see the charts of multiple virtual currencies at once. Can't).

Recommended Posts

Get the trading price of virtual currency and create a chart with API of Zaif exchange
Get the stock price of a Japanese company with Python and make a graph
Get coincheck virtual currency information with API ♪
Create a clean DB for testing with FastAPI and unittest the API with pytest
Create a batch of images and inflate with ImageDataGenerator
Create a tweet heatmap with the Google Maps API
Get comments and subscribers with the YouTube Data API
Get the id of a GPU with low memory usage
Get UNIXTIME at the beginning of today with a command
Make a BLE thermometer and get the temperature with Pythonista3
Get the number of PVs of Qiita articles you posted with API
Create a function to get the contents of the database in Go
Create a REST API to operate dynamodb with the Django REST Framework
Create a compatibility judgment program with the random module of python.
Create a virtual environment with Python!
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Get the number of searches with a regular expression. SeleniumBasic VBA Python
I tried to get the authentication code of Qiita API with Python.
Hit a method of a class instance with the Python Bottle Web API
Read the graph image with OpenCV and get the coordinates of the final point of the graph
The story of making a sound camera with Touch Designer and ReSpeaker
Make a DNN-CRF with Chainer and recognize the chord progression of music
I tried to get the movie information of TMDb API with Python
Get and estimate the shape of the head using Dlib and OpenCV with python
Get the average salary of a job with specified conditions from indeed.com
[Python] Create a virtual environment with Anaconda
Operation of virtual currency automatic trading script
Get the minutes of the Diet via API
Article that can be a human resource who understands and masters the mechanism of API (with Python code)
Create a virtual environment with Python_Mac version
Get holidays with the Google Calendar API
Get the filename of a directory (glob)
Create a simple app that incorporates the Fetch API of Ajax requests in Flask and explain it quickly
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Create a simple reception system with the Python serverless framework Chalice and Twilio
Get a list of articles posted by users with Python 3 Qiita API v2
Create an easy-to-read pdf of laws and government ordinances using the law api
Zip-compress any file with the [shell] command to create a file and delete the original file.
Create a Django project and application in a Python virtual environment and start the server
Use twitter API to get the number of tweets related to a certain keyword
Create a filter to get an Access Token in the Graph API (Flask)
How to get a list of files in the same directory with python
I tried to create a model with the sample of Amazon SageMaker Autopilot
[Introduction to Python] How to get the index of data with a for statement
After hitting the Qiita API with Python to get a list of articles for beginners, we will visit the god articles
[Python] Get the files in a folder with Python
Get the caller of a function in Python
Create a virtual environment with conda in Python
Get stock price data with Quandl API [Python]
Get a list of IAM users with Boto3
Build a virtual environment with pyenv and venv
Get Gmail subject and body with Python and Gmail API
A discussion of the strengths and weaknesses of Python
Create a command to get the work log
Create a translation tool with the Translate Toolkit
Create a table of contents with IPython notebook
Automate background removal for the latest portraits in a directory with Python and API
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
Get the value of a specific key in a list from the dictionary type in the list with Python
Try to create a battle record table with matplotlib from the data of "Schedule-kun"