加密貨幣到價通知 : 爬蟲 + pandas + Line BOT

在開始寫程式前,我們需要先想好程式的流程該長得如何

還記得前幾周的爬蟲課程嗎?

import requests
import datetime
import pandas as pd
from linebot import LineBotApi
from linebot.models import TextSendMessage

def get_page():
    url = 'https://www.binance.com/exchange/public/product'
    try:
        res = requests.get(url)
        if res.status_code == 200:
            response = res.json()
            print('get_page ... Done')
            return response
    except Exception as e:
        print(e)
        return None

開始實作吧!(課後會更新代碼)

import requests
import datetime
import pandas as pd
from linebot import LineBotApi
from linebot.models import TextSendMessage

def get_page():
    url = 'https://www.binance.com/exchange/public/product'
    try:
        res = requests.get(url)
        if res.status_code == 200:
            response = res.json()
            print('get_page ... Done')
            return response
    except Exception as e:
        print(e)
        return None

def parse_page(response):
    block = response["data"]
    pd_block = pd.DataFrame(block)
    pd_result = pd_block[
        (pd_block['quoteAsset'] == 'USDT') & 
        ((pd_block['baseAsset'] == 'BTC') | (pd_block['baseAsset'] == 'ETH') | (pd_block['baseAsset'] == 'LTC'))]
    pd_result['delta'] = round((pd_result.close.astype(float) -pd_result.open.astype(float)) / pd_result.open.astype(float), 4)
    # pd_result['delta'] = (pd_result['close'].astype(float) -pd_result['open'].astype(float)) / pd_result['open'].astype(float)
    pd_result = pd_result[['baseAsset','quoteAsset','close','delta']]

    print('parse_page ... Done')
    return pd_result
    # print(pd_result)
    # print(pd_block['quoteAsset'].drop_duplicates())
    # print(pd_block.columns)

def export_excel(data):
    now_date = datetime.date.today()
    now_time = datetime.datetime.now()
    data['insert_date'] = now_date
    data['insert_time'] = now_time
    old_data = pd.read_excel(r'C:\Peter\python\shopee_hackthon\cryptocurrency.xlsx', index=False)
    insert_data = pd.concat([old_data, data], ignore_index=True)
    insert_data.to_excel(r'C:\Peter\python\shopee_hackthon\cryptocurrency.xlsx', index=False)

    print('export_excel ... Done')

def current_price(data):
    msg = '[cryptocurrency]\n' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '\n'
    for i in range(0,data.iloc[:,0].size,1):
        msg += '[' + str(data['baseAsset'].iloc[i]) + ']\n' + 'price = ' + str(data['close'].iloc[i]) + '\n' + 'delta = ' + str(data['delta'].iloc[i]) + '\n'
    print('current_price ... Done')
    push_linemsg(msg)

def alert_price(data):
    pd_alert = pd.read_excel(r'C:\Peter\python\shopee_hackthon\alert_setting.xlsx', index=False)

    msg = '[cryptocurrency_alert]\n' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '\n'
    for i in range(0,data.iloc[:,0].size,1):
        if float(data['close'].iloc[i]) > float(pd_alert[pd_alert['baseAsset']==data['baseAsset'].iloc[i]]['sell_price'].values[0]):
            msg += '[Sell]' + str(data['baseAsset'].iloc[i]) + '\n' + 'price = ' + str(data['close'].iloc[i]) + '\n' + 'delta = ' + str(data['delta'].iloc[i]) + '\n'
        elif float(data['close'].iloc[i]) < float(pd_alert[pd_alert['baseAsset']==data['baseAsset'].iloc[i]]['buy_price'].values[0]):
            msg += '[Buy]' + str(data['baseAsset'].iloc[i]) + '\n' + 'price = ' + str(data['close'].iloc[i]) + '\n' + 'delta = ' + str(data['delta'].iloc[i]) + '\n'
    print('alert_price ... Done')

    if msg != '':
        push_linemsg(msg)

def push_linemsg(msg):
    line_bot_api = LineBotApi('token')
    #push message to one user
    line_bot_api.push_message('user id', TextSendMessage(text=msg))
    print('push_linemsg ... Done')

# Main
response = get_page()

if response:
    data = parse_page(response)
else:
    print("error")

export_excel(data)
current_price(data)
alert_price(data)

延伸閱讀

results matching ""

    No results matching ""