仮想通貨×想い

仮想通貨、プログラミングのこと、最近気になることなど。。。

仮想通貨取引所 Zaif API サンプルプログラム:一定時間ごとに単純移動平均を表示(SMA:Simple Moving Average)(python編)

 pythonで、1分ごとに単純移動平均(SMA:Simple Moving Average)を表示するプログラムを作ってみました。無限ループのため、[CTRL]+[c] で終了してください。

#coding: utf-8
import requests
import json
from datetime import datetime
from time import sleep

def get_lastprice():
    response = requests.get("https://api.zaif.jp/api/1/last_price/xem_jpy")
    while response.status_code != 200:
        raise Exception('return status code is {}'.format(response.status_code))
        sleep(2)
        response = requests.get("https://api.zaif.jp/api/1/last_price/xem_jpy")        
    dic = json.loads(response.text)
    prc = dic["last_price"]
    return prc

nw = lp = jd = 0
twsx = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

while lp != 99:    # loop out at this day

    nw       = datetime.now()
    lp       = nw.day
    jd       = nw.second
    i = j = k = l = 0
    sum_nine = sum_twlv = sum_twsx = 0
    signal = fast = slow = 0

    if jd==0:
       
        twsx[25] = get_lastprice()        

        # cal. 9-moving average(signal)      
        for i in range(17,26):
            sum_nine += twsx[i]
        signal = sum_nine / 9
        
        # cal. 12-moving average(fast length)
        for j in range(14,26):
            sum_twlv += twsx[j]
        fast   = sum_twlv / 12
        
        # cal. 26-moving average(slow length)
        for k in range(0,26):
            sum_twsx += twsx[k]
            print("list[",k,"]=",twsx[k])    # view all list
        slow   = sum_twsx / 26
        
        print()
        print("NOW TIME     =",nw)
        print("signal(9ave.)=",signal)
        print("fast (12ave.)=",fast )
        print("slow (26ave.)=",slow )
       
        # shift value
        for l in range(0,25):
            twsx[l] = twsx[l+1]
       
        sleep(60-5)

 実行結果は次のとおりです(9分経過後)。

D:\python>python sma_1m.py
list[ 0 ]= 0
list[ 1 ]= 0
list[ 2 ]= 0
list[ 3 ]= 0
list[ 4 ]= 0
list[ 5 ]= 0
list[ 6 ]= 0
list[ 7 ]= 0
list[ 8 ]= 0
list[ 9 ]= 0
list[ 10 ]= 0
list[ 11 ]= 0
list[ 12 ]= 0
list[ 13 ]= 0
list[ 14 ]= 0
list[ 15 ]= 0
list[ 16 ]= 0
list[ 17 ]= 38.78
list[ 18 ]= 38.7
list[ 19 ]= 38.7
list[ 20 ]= 38.78
list[ 21 ]= 38.7
list[ 22 ]= 38.77
list[ 23 ]= 38.77
list[ 24 ]= 38.701
list[ 25 ]= 38.701

NOW TIME     = 2018-03-11 00:46:00.004421
signal(9ave.)= 38.73355555555557
fast (12ave.)= 29.050166666666673
slow (26ave.)= 13.407769230769235