取引価格データ取得(テスト用サンプル)

取引価格データを取得するAPIを呼び出し、JSON形式のレスポンスをCSV形式に整形するプログラムのサンプルとなります。

呼び出しAPI概要

「取引価格データを取得するAPI」の仕様。

※返却されるデータはテスト用サンプルデータとなります。

エンドポイントURL

http://itbibo.php.xdomain.jp/wp-json/api/v1/trades

※リクエスト送信はサーバに負担をかけないように必要最低限でお願いいたします。

入力パラメタ

パラメタ名必須説明
symbol文字列シンボル
limit数値デフォルト:20

リクエスト制限

  • 規定時間当たりのリクエスト数が許容値を超えると、HTTP 429 エラーを返却するようにしています。(エラーが起きやすいように許容値を低く設定しています。)
  • IP アドレス制限を行うため、リクエスト元IPアドレス等を記録しています。

リクエストサンプル

http://itbibo.php.xdomain.jp/wp-json/api/v1/trades?symbol=BTCUSDT&limit=3

※リクエスト送信はサーバに負担をかけないように必要最低限でお願いいたします。

戻り値

戻り値(正常時)のサンプルは以下の通り。

[
  {
    "id": 101234568,
    "price": "45659.89",
    "qty": "0.006",
    "time": 1628725167,
    "isBuyerMaker": false,
    "isBestMatch": true
  },
  {
    "id": 101234576,
    "price": "45667.89",
    "qty": "0.014",
    "time": 1628705460,
    "isBuyerMaker": true,
    "isBestMatch": true
  },
  {
    "id": 101234575,
    "price": "45666.89",
    "qty": "0.013",
    "time": 1628705460,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

戻り値(エラー時)のサンプルは以下の通り。

{
  "code": 429,
  "message": "Too Many Requests. Requests per minute limit is 4.",
  "data": {
    "status": 429
  }
}

APIを呼び出し結果をCSV形式に整形するプログラム

JSON → CSV整形 プログラム

pythonで作成しています。( python のインストール方法はこちら)

get_currency_rate.py
# ======================================================================
# Project Name    : Crypto assets tax calculate
# File Name       : get_currency_rate.py
# Encoding        : UTF-8
# Creation Date   : 2021-10-31
# Update Date     : 2022-09-04
# ======================================================================
import sys
import os
import requests
import pprint
import math
import json
from collections import OrderedDict
import time
from datetime import datetime, timedelta, timezone
import numpy as np
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN

# --------------------------------------------------------------------
# 初期設定
# --------------------------------------------------------------------
# タイムゾーンの設定
w_tz_JST = timezone(timedelta(hours=+9), 'JST')
dt_tokyo_now = datetime.now(w_tz_JST)
dt_tokyo_now_str1 = dt_tokyo_now.strftime('%m/%d/%Y %H:%M')
dt_tokyo_now_YYYYmm = dt_tokyo_now.strftime('%Y%m')
print("[Execution time(JST)] "+str(dt_tokyo_now_str1))

# --------------------------------------------------------------------
# ログファイルパス(デフォルト)
# --------------------------------------------------------------------
log_file_path='get_currency_rate_' + str(dt_tokyo_now.year) + str(dt_tokyo_now.strftime('%m')) + '.log'
error429_file_name='./error429.log'


# --------------------------------------------------------------------
# パラメータチェック
# --------------------------------------------------------------------
args = sys.argv
if 2 >= len(args):
    print('Arguments are too short.')
    print('Usage:get_currency_rate.py BTCUSDT[Currency/USDT] x')
    print('Usage:get_currency_rate.py BTCUSDT[Base Currency/USDT] x QNTBTC[Trade Currency/Base Currency] y')
    print('      x and y : number of decimal places')
    print('ex1:get_currency_rate.py BTCUSDT 2')
    print('ex2:get_currency_rate.py BTCUSDT 2 QNTBTC 6')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'Arguments are too short', '\n']
    f.writelines(datalist)
    f.close()
    exit(1)

# リクエストパラメタ設定用、変数取得
arg1 = args[1]
arg2 = args[2]

if 5 >= len(arg1):
    print('Argument 1 length is too short.')
    print('Usage:get_currency_rate.py BTCUSDT[Currency/USDT] x')
    print('Usage:get_currency_rate.py BTCUSDT[Base Currency/USDT] x QNTBTC[Trade Currency/Base Currency] y')
    print('      x and y : number of decimal places')
    print('ex1:get_currency_rate.py BTCUSDT 2')
    print('ex2:get_currency_rate.py BTCUSDT 2 QNTBTC 6')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'Argument 1 length is too short. arg1=', arg1 , '\n']
    f.writelines(datalist)
    f.close()
    exit(1)

if not arg1[-4:] == 'USDT':
    print('The character in argument 1 must end with USDT.')
    print('Usage:get_currency_rate.py BTCUSDT[Currency/USDT] x')
    print('Usage:get_currency_rate.py BTCUSDT[Base Currency/USDT] x QNTBTC[Trade Currency/Base Currency] y')
    print('      x and y : number of decimal places')
    print('ex1:get_currency_rate.py BTCUSDT 2')
    print('ex2:get_currency_rate.py BTCUSDT 2 QNTBTC 6')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'The character in argument 1 must end with USDT. arg1=', arg1 , '\n']
    f.writelines(datalist)
    f.close()
    exit(1)


if 4 == len(args):
    print('Wrong number of arguments (2 or 4).')
    print('Usage:get_currency_rate.py BTCUSDT[Currency/USDT] x')
    print('Usage:get_currency_rate.py BTCUSDT[Base Currency/USDT] x QNTBTC[Trade Currency/Base Currency] y')
    print('      x and y : number of decimal places')
    print('ex1:get_currency_rate.py BTCUSDT 2')
    print('ex2:get_currency_rate.py BTCUSDT 2 QNTBTC 6')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'Wrong number of arguments (2 or 4)', '\n']
    f.writelines(datalist)
    f.close()
    exit(1)

# エラー429ファイル存在確認
if os.path.exists(error429_file_name):
    print('Error 429 file is exist. Error 429 file needs to be deleted.')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'Error 429 file is exist. Error 429 file needs to be deleted.', '\n']
    f.writelines(datalist)
    f.close()
    exit(1)

url = 'http://itbibo.php.xdomain.jp/wp-json/api/v1/trades'

w_tz_XXX = timezone(timedelta(hours=0), 'UTC')
w_datalist_header = ['date_JST,date_UTC,Trade_UTC1,Base Currency/USDT,API USDT Price,Trade_UTC2,Trade Currency/Base Currency,API Deal Price,Total quantity,Average quantity\n']

if 6 <= len(args):
    if args[5] == 'SGT':
        w_tz_XXX = timezone(timedelta(hours=+8), 'SGT')
        w_datalist_header = ['date_JST,date_SGT,Trade_SGT1,Base Currency/USDT,API USDT Price,Trade_SGT2,Trade Currency/Base Currency,API Deal Price,Total quantity,Average quantity\n']

dt_tz_now = datetime.now(w_tz_XXX)
dt_tz_now_str1 = dt_tz_now.strftime('%m/%d/%Y %H:%M')

print("[Execution time(" + str(w_tz_XXX) + ")] "+str(dt_tz_now_str1))

# リクエストパラメタ設定
params = {'symbol': arg1, 'limit': 1000 }
count=0
price1=float('0')
price_total1=float('0')
qty_total1=float('0')
dt_tokyo_str1=''
price_average1_halfup=''
decimal_format1='%.12f'
decimal_places1_str='0.000000000001'
qty_total1_halfup=''
qty_average1_halfup=''

r = requests.get(url, params=params)
print("[url] "+r.url)
print("[" + arg1 + " status_code1] "+str(r.status_code))
b_flag=0

decimal_places1=arg2
if decimal_places1 == '0':
    decimal_format1='%.0f'
    decimal_places1_str='0'
elif decimal_places1 == '1':
    decimal_format1='%.1f'
    decimal_places1_str='0.1'
elif decimal_places1 == '2':
    decimal_format1='%.2f'
    decimal_places1_str='0.01'
elif decimal_places1 == '3':
    decimal_format1='%.3f'
    decimal_places1_str='0.001'
elif decimal_places1 == '4':
    decimal_format1='%.4f'
    decimal_places1_str='0.0001'
elif decimal_places1 == '5':
    decimal_format1='%.5f'
    decimal_places1_str='0.00001'
elif decimal_places1 == '6':
    decimal_format1='%.6f'
    decimal_places1_str='0.000001'
elif decimal_places1 == '7':
    decimal_format1='%.7f'
    decimal_places1_str='0.0000001'
elif decimal_places1 == '8':
    decimal_format1='%.8f'
    decimal_places1_str='0.00000001'
elif decimal_places1 == '9':
    decimal_format1='%.9f'
    decimal_places1_str='0.000000001'
elif decimal_places1 == '10':
    decimal_format1='%.10f'
    decimal_places1_str='0.0000000001'
elif decimal_places1 == '11':
    decimal_format1='%.11f'
    decimal_places1_str='0.00000000001'
elif decimal_places1 == '12':
    decimal_format1='%.12f'
    decimal_places1_str='0.000000000001'
elif decimal_places1 == '13':
    decimal_format1='%.13f'
    decimal_places1_str='0.0000000000001'
elif decimal_places1 == '14':
    decimal_format1='%.14f'
    decimal_places1_str='0.00000000000001'

# リクエスト送信前待機(20秒:実行開始時分において、1分内でなるべく中間値を取得できるようにする場合、コメントを外す)
#time.sleep(20);

# --------------------------------------------------------------------
# 通貨レートファイル保存パス
# --------------------------------------------------------------------
currency_rate_path='/Users/Shared/App/Python/cryptocurrency-price/' + str(dt_tokyo_now.year) + '/' + str(dt_tokyo_now.strftime('%m')) + '/'
if os.name == 'nt':
    currency_rate_path='../cryptocurrency-price/' + str(dt_tokyo_now.year) + '/' + str(dt_tokyo_now.strftime('%m')) + '/'

# ディレクトリ(フォルダ)の存在確認
if not os.path.isdir(currency_rate_path):
    os.makedirs(currency_rate_path)

output_file_path=currency_rate_path+'currency_rate_' + arg1 + '_' + dt_tokyo_now_YYYYmm + '.csv'

# --------------------------------------------------------------------
# ログファイルパス(変更)
# --------------------------------------------------------------------
log_file_path=currency_rate_path+log_file_path


# リクエスト送信
rtn_json = r.json()

# レスポンス確認
if r.status_code == 200:

    if 5 >= len(str(rtn_json)):
        print("[Message] "+'Response string is too short. Response JSON String='+ str(rtn_json))
        f = open(log_file_path, 'a', encoding='UTF-8')
        datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' Response string is too short. Response JSON String=', str(rtn_json), '\n']
        f.writelines(datalist)
        f.close()
        exit(1)

    for index, item in enumerate(rtn_json):
        dt_tokyo = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=+9)))

        if len(dt_tokyo_str1) == 0:
            dt_tokyo_str1 = dt_tokyo.strftime('%Y/%m/%d %H:%M')
        else:
            if dt_tokyo_str1 != dt_tokyo.strftime('%Y/%m/%d %H:%M'):
                b_flag=1
                break

        #小数点以下を切り捨て整形
        if str(w_tz_XXX) == 'SGT':
            dt_world = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=+8)))
        else:
            dt_world = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=0)))

        #print(dt_world)
        dt_tz_str1 = dt_world.strftime('%m/%d/%Y %H:%M')
        #print("インデックス:" + str(index) + ", 値:" + dt_tz_str1 + ", 価格:" + item['price'] + ", 数量:" + item['qty'])
        price1=float(item['price'])
        price_total1+=(price1 * float(item['qty']))
        qty_total1+=float(item['qty'])

    if b_flag==1:
        count=index
    else:
        count=index+1

    print("[" + arg1 + "][data count1] "+str(count) + " [price_total1] "+str(price_total1) + " [decimal_places1_str] "+decimal_places1_str)

    if count==1:
        price_average1_tmp1=str(price1)
    else:
        price_average1_tmp1=str(price_total1/qty_total1)

    price_average1_tmp2=decimal_format1 % Decimal(price_average1_tmp1).quantize(Decimal(decimal_places1_str), rounding=ROUND_HALF_UP)

    price_average1=str(price_average1_tmp2)
    price_average1_halfup=price_average1

    qty_total1_halfup=str(float(Decimal(str(qty_total1)).quantize(Decimal('0.00001'), rounding=ROUND_HALF_UP)))
    qty_average1=qty_total1/count
    qty_average1_halfup=str(float(Decimal(str(qty_average1)).quantize(Decimal('0.00001'), rounding=ROUND_HALF_UP)))

    print("[" + arg1 + "][price_average1_halfup] "+str(price_average1_halfup) + " qty_total1_halfup] "+str(qty_total1_halfup) + " qty_average1_halfup] "+str(qty_average1_halfup))

    if 3 == len(args):
        if os.path.exists(output_file_path)==True:
            f = open(output_file_path, 'a', encoding='UTF-8')
            datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , dt_tz_str1 , ',' , arg1 , ',' , price_average1_halfup , ',' , dt_tz_str1, ',' , arg1 , ',' , price_average1_halfup , ',' , qty_total1_halfup, ',' , qty_average1_halfup, '\n']
            f.writelines(datalist)
            f.close()
        else:
            f = open(output_file_path, 'w', encoding='UTF-8')
            datalist = w_datalist_header
            f.writelines(datalist)
            datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , dt_tz_str1 , ',' , arg1 , ',' , price_average1_halfup , ',' , dt_tz_str1, ',' , arg1 , ',' , price_average1_halfup , ',' , qty_total1_halfup, ',' , qty_average1_halfup, '\n']
            f.writelines(datalist)
            f.close()
        exit(1)
else:
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' HTTP Response error. Status=' , str(r.status_code) ,' Response JSON String=', str(rtn_json), '\n']
    f.writelines(datalist)
    f.close()
    if str(r.status_code) =='429':
        f = open(error429_file_name, 'a', encoding='UTF-8')
        f.writelines(datalist)
        f.close()
    exit(1)

# リクエストパラメタ設定用、変数取得
arg3 = args[3]
arg4 = args[4]

# リクエストパラメタ設定
params = {'symbol': arg3, 'limit': 1000 }
count=0
pric2=float('0')
price_total2=float('0')
qty_total2=float('0')
dt_tokyo_str2=''
price_average2_halfup=''
decimal_format2='%.12f'
decimal_places2_str='0.000000000001'
qty_total2_halfup=''
qty_average2_halfup=''

r = requests.get(url, params=params)
print("[url] "+r.url)
print("[" + arg3 + " status_code2] "+str(r.status_code))
b_flag=0

decimal_places2=arg4
if decimal_places2 == '0':
    decimal_format2='%.0f'
    decimal_places2_str='0'
elif decimal_places2 == '1':
    decimal_format2='%.1f'
    decimal_places2_str='0.1'
elif decimal_places2 == '2':
    decimal_format2='%.2f'
    decimal_places2_str='0.01'
elif decimal_places2 == '3':
    decimal_format2='%.3f'
    decimal_places2_str='0.001'
elif decimal_places2 == '4':
    decimal_format2='%.4f'
    decimal_places2_str='0.0001'
elif decimal_places2 == '5':
    decimal_format2='%.5f'
    decimal_places2_str='0.00001'
elif decimal_places2 == '6':
    decimal_format2='%.6f'
    decimal_places2_str='0.000001'
elif decimal_places2 == '7':
    decimal_format2='%.7f'
    decimal_places2_str='0.0000001'
elif decimal_places2 == '8':
    decimal_format2='%.8f'
    decimal_places2_str='0.00000001'
elif decimal_places2 == '9':
    decimal_format2='%.9f'
    decimal_places2_str='0.000000001'
elif decimal_places2 == '10':
    decimal_format2='%.10f'
    decimal_places2_str='0.0000000001'
elif decimal_places2 == '11':
    decimal_format2='%.11f'
    decimal_places2_str='0.00000000001'
elif decimal_places2 == '12':
    decimal_format2='%.12f'
    decimal_places2_str='0.000000000001'
elif decimal_places2 == '13':
    decimal_format2='%.13f'
    decimal_places2_str='0.0000000000001'
elif decimal_places2 == '14':
    decimal_format2='%.14f'
    decimal_places2_str='0.00000000000001'

# エラー429ファイル存在確認
if os.path.exists(error429_file_name):
    print('Error 429 file is exist. Error 429 file needs to be deleted.')
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'Error 429 file is exist. Error 429 file needs to be deleted.', '\n']
    f.writelines(datalist)
    f.close()
    exit(1)

# リクエスト送信
rtn_json = r.json()

# レスポンス確認
if r.status_code == 200:

    if 5 >= len(str(rtn_json)):
        print("[Message] "+'Response string is too short. Response JSON String='+ str(rtn_json))
        f = open(log_file_path, 'a', encoding='UTF-8')
        datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' Response string is too short. Response JSON String=', str(rtn_json), '\n']
        f.writelines(datalist)
        f.close()
        exit(1)

    for index, item in enumerate(rtn_json):
        dt_tokyo = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=+9)))
        if len(dt_tokyo_str2) == 0:
            dt_tokyo_str2 = dt_tokyo.strftime('%Y/%m/%d %H:%M')
        else:
            if dt_tokyo_str2 != dt_tokyo.strftime('%Y/%m/%d %H:%M'):
                b_flag=1
                break

        #小数点以下を切り捨て整形
        if str(w_tz_XXX) == 'SGT':
            dt_world = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=+8)))
        else:
            dt_world = datetime.fromtimestamp(math.floor(item['time']/1000), timezone(timedelta(hours=0)))

        #print(dt_world)
        dt_tz_str2 = dt_world.strftime('%m/%d/%Y %H:%M')
        #print("インデックス:" + str(index) + ", 値:" + dt_tz_str2 + ", 価格:" + item['price'] + ", 数量:" + item['qty'])
        price2=float(item['price'])
        price_total2+=(price2 * float(item['qty']))
        qty_total2+=float(item['qty'])

    if b_flag==1:
        count=index
    else:
        count=index+1

    print("[" + arg3 + "][dt_tz_str2] "+str(dt_tz_str2))
    print("[" + arg3 + "][data count2] "+str(count)+ " [price_total2] "+str(price_total2) + " [qty_total2] "+str(qty_total2) + " [decimal_places2_str] "+decimal_places2_str)

    if count==1:
        price_average2_tmp1=str(price2)
    else:
        price_average2_tmp1=str(price_total2/qty_total2)

    price_average2_tmp2=decimal_format2 % Decimal(price_average2_tmp1).quantize(Decimal(decimal_places2_str), rounding=ROUND_HALF_UP)
    price_average2=str(price_average2_tmp2)
    price_average2_halfup=price_average2

    qty_total2_halfup=str(float(Decimal(str(qty_total2)).quantize(Decimal('0.00001'), rounding=ROUND_HALF_UP)))
    qty_average2=qty_total2/count
    qty_average2_halfup=str(float(Decimal(str(qty_average2)).quantize(Decimal('0.00001'), rounding=ROUND_HALF_UP)))

    print("[" + arg3 + "][price_average2_halfup] "+str(price_average2_halfup) + " [qty_total2_halfup] "+str(qty_total2_halfup) + " [qty_average2_halfup] "+str(qty_average2_halfup))

    if os.path.exists(output_file_path)==True:
        f = open(output_file_path, 'a', encoding='UTF-8')
        datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , dt_tz_str1 , ',' , arg1 , ',' , price_average1_halfup , ',' ,
                    dt_tz_str2, ',' , arg3 , ',' , price_average2_halfup , ',' , qty_total2_halfup, ',' , qty_average2_halfup, '\n']
        f.writelines(datalist)
        f.close()
    else:
        f = open(output_file_path, 'w', encoding='UTF-8')
        datalist = w_datalist_header
        f.writelines(datalist)
        datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , dt_tz_str1 , ',' , arg1 , ',' , price_average1_halfup , ',' ,
                    dt_tz_str2, ',' , arg3 , ',' , price_average2_halfup , ',' , qty_total2_halfup, ',' , qty_average2_halfup, '\n']
        f.writelines(datalist)
        f.close()
else:
    f = open(log_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' HTTP Response error. Status=' , str(r.status_code) ,' Response JSON String=', str(rtn_json), '\n']
    f.writelines(datalist)
    f.close()
    if str(r.status_code) =='429':
        f = open(error429_file_name, 'a', encoding='UTF-8')
        f.writelines(datalist)
        f.close()
exit(0)

プログラム実行

$ get_currency_rate.py BTCUSDT 2

出力結果

Windowsの場合

(実行ディレクトリ)..\cryptocurrency-price\yyyy\mm\currency_rate_BTCUSDT_yyyymm.csv

macOs/Linuxの場合

/Users/Shared/App/Python/cryptocurrency-price/yyyy/mm/currency_rate_BTCUSDT_yyyymm.csv

エラー発生時のログ

get_currency_rate_yyyymm.log

※yyyy は西暦4桁 、mmは年月2桁

CSV形式の出力結果をマージするプログラム

CSVマージ プログラム

pythonで作成しています。( python のインストール方法はこちら)

concat-cryptocurrency-price.py
# ======================================================================
# Project Name    : Crypto assets tax calculate
# File Name       : concat-cryptocurrency-price.py
# Encoding        : UTF-8
# Creation Date   : 2022-03-13
# Update Date     : 2022-09-04
# Site URL        : http://itbibo.wp.xdomain.jp/
# 
# Copyright © 2017-2022 IT系の備忘録
#
# This source code or any portion thereof must not be
# reproduced or used in any manner whatsoever.
# ======================================================================
import sys
import os
import pdb
import pandas as pd
import csv
from datetime import datetime, timedelta, timezone
args = sys.argv
if (3 >= len(args)):
    print('Arguments are too short.')
    print('Usage : concat-cryptocurrency-price.py [org csv file directory] [add csv filename] [add csv file directory] [timezone]')
    exit(1)
# 初期設定
w_tz_JST = timezone(timedelta(hours=+9), 'JST')
dt_tokyo_now = datetime.now(w_tz_JST)
concat_file_name_yyyy=str(dt_tokyo_now.year)
#print("[Execution time(JST)] "+str(dt_tokyo_now))
dt_tokyo_now_str1 = dt_tokyo_now.strftime('%m/%d/%Y %H:%M')
#print("[Execution time(JST)] "+str(dt_tokyo_now_str1))
#print("len(args) : "+str(len(args)))
#print("args[1] : "+str(args[1]))
#print("args[2] : "+str(args[2]))
#print("args[3] : "+str(args[3]))
# timezone
w_timezone='UTC'
# 通貨レート結合ファイル格納ディレクトリ
concat_file_dir=str(args[1])
# 通貨レート個別ファイル格納ディレクトリ
currency_rate_file_dir=str(args[3])
if os.name == 'nt':
    concat_file_dir=concat_file_dir+'/'
else:
    currency_rate_file_dir='/Users/Shared/App/Python/cryptocurrency-price/' + concat_file_name_yyyy + '/' + str(dt_tokyo_now.strftime('%m')) + '/'
if (5 <= len(args)):
    if (str(args[4]) == 'SGT'):
        print("args[4] : "+str(args[4]))
        w_timezone='SGT'
concat_file_path=concat_file_dir+'cryptocurrency-price-' + concat_file_name_yyyy + '.csv'
error_file_path=concat_file_dir+'error-' + concat_file_name_yyyy + '.log'
currency_rate_file_path=currency_rate_file_dir+str(args[2])
# 通貨レート個別ファイル存在確認
if not os.path.exists(currency_rate_file_path):
    print('File not found. path='+currency_rate_file_path)
    f = open(error_file_path, 'a', encoding='UTF-8')
    datalist = [str(dt_tokyo_now), ',' , 'File not found. path=', currency_rate_file_path, '\n']
    f.writelines(datalist)
    f.close()
    exit(1)
# 通貨レート結合ファイル存在確認
if not os.path.exists(concat_file_path):
    f = open(concat_file_path, 'w', encoding='UTF-8')
    if (w_timezone == 'SGT'):
        datalist = ['date_JST,date_SGT,Trade_SGT1,Base Currency/USDT,API USDT Price,Trade_SGT2,Trade Currency/Base Currency,API Deal Price,Total quantity,Average quantity\n']
    else:
        datalist = ['date_JST,date_UTC,Trade_UTC1,Base Currency/USDT,API USDT Price,Trade_UTC2,Trade Currency/Base Currency,API Deal Price,Total quantity,Average quantity\n']
    f.writelines(datalist)
    f.close()
# 通貨レート結合ファイル読込
concat_file_df = pd.read_csv(concat_file_path, dtype=str)
# 通貨レート個別ファイル読込
currency_rate_file_df = pd.read_csv(currency_rate_file_path, dtype=str)
concat_file_df = pd.concat([concat_file_df, currency_rate_file_df], axis=0)
# データを日付、通貨で並び替え
concat_file_df = concat_file_df.sort_values(by=['date_JST', 'Base Currency/USDT'])
# 重複行削除
concat_file_df = concat_file_df.drop_duplicates()
# ファイル出力
concat_file_df.to_csv(concat_file_path, index=False)
exit(0)

プログラム実行

形式: [プログラム名] [通貨レート結合ファイル格納ディレクトリ][通貨レート個別ファイル名] [通貨レート個別ファイル格納ディレクトリ]

$ concat-cryptocurrency-price.py ../input currency_rate_BTCUSDT_yyyymm.csv ../cryptocurrency-price/2022/05/

出力結果

Windowsの場合

(実行ディレクトリ)..\input\cryptocurrency-price-yyyy.csv

macOs/Linuxの場合

/Users/Shared/App/Python/cryptocurrency-price/cryptocurrency-price-yyyy.csv

※yyyy は西暦4桁 、mmは年月2桁

タイトルとURLをコピーしました