Pythonで仮想通貨の市場データをAPIスクレイピングする方法

Pythonを使って仮想通貨の市場データを取得する方法について紹介したいと思います。このスクリプトは無料で利用できるCoinGeckoのAPIを使って仮想通貨の価格、市場キャップ、取引量のデータを取得します。

目次

仮想通貨の市場データを取得するpythonスクリプト

まずは、以下のPythonスクリプトをご覧ください。

import argparse
import requests
import pandas as pd

BASE_URL = "https://api.coingecko.com/api/v3"

def get_crypto_list():
    url = f"{BASE_URL}/coins/list"
    response = requests.get(url)
    data = response.json()

    crypto_names = [crypto['id'] for crypto in data]
    return crypto_names

def is_valid_crypto(crypto_name, crypto_list):
    return crypto_name in crypto_list

def get_matching_cryptos(crypto_name, crypto_list):
    first_letter = crypto_name[0]
    matching_cryptos = [name for name in crypto_list if name.startswith(first_letter)]
    return matching_cryptos

def get_crypto_data(crypto_name):
    url = f"{BASE_URL}/coins/{crypto_name}/market_chart"
    parameters = {
        'vs_currency': 'jpy',
        'days': 'max'
    }
    response = requests.get(url, params=parameters)
    data = response.json()
    
    df_prices = pd.DataFrame(data['prices'], columns=['time', 'price'])
    df_market_caps = pd.DataFrame(data['market_caps'], columns=['time', 'market_cap'])
    df_total_volumes = pd.DataFrame(data['total_volumes'], columns=['time', 'total_volume'])
    
    df = pd.merge(df_prices, df_market_caps, on='time')
    df = pd.merge(df, df_total_volumes, on='time')

    df['time'] = pd.to_datetime(df['time'], unit='ms')
    
    return df

def main():
    parser = argparse.ArgumentParser(description='特定の仮想通貨の市場データを取得します。')
    parser.add_argument('crypto_name', type=str, help='仮想通貨の名前')
    args = parser.parse_args()

    crypto_list = get_crypto_list()

    if not is_valid_crypto(args.crypto_name, crypto_list):
        print(f"仮想通貨名 {args.crypto_name} は無効です。以下の有効な仮想通貨名を参考にしてください:")
        matching_cryptos = get_matching_cryptos(args.crypto_name, crypto_list)
        print(", ".join(matching_cryptos))
        return

    try:
        df = get_crypto_data(args.crypto_name)
        df.to_csv(f'{args.crypto_name}_prices.csv', index=False)
        print(f"データを {args.crypto_name}_prices.csv に保存しました")
    except Exception as e:
        print(f"エラーが発生しました: {str(e)}")

if __name__ == "__main__":
    main()

このスクリプトは、指定した仮想通貨の市場データを取得し、CSVファイルとして保存します。また、仮想通貨名が無効な場合には、エラーメッセージと共に有効な仮想通貨名のリストを表示します(入力値の1文字目で前方一致検索で絞ったリスト)。

以下に、各部分の詳細な説明をします。

  1. get_crypto_list関数: この関数はCoinGeckoのAPIから利用可能なすべての仮想通貨のリストを取得します。
  2. is_valid_crypto関数: この関数は指定した仮想通貨名が有効かどうかをチェックします。
  3. get_matching_cryptos関数: この関数は、指定した仮想通貨名の最初の文字に一致する仮想通貨のリストを取得します。
  4. get_crypto_data関数: この関数は、指定した仮想通貨の市場データを取得します。
  5. main関数: ここでは、コマンドライン引数として仮想通貨名を受け取り、上記の関数を適切な順序で呼び出しています。

このスクリプトを使用するには、Pythonがインストールされていて、インターネットに接続できる環境が必要です。また、requestspandasargparseというPythonのライブラリも必要なので、事前にインストールしておいてください。

スクリプトを実行すると、指定した仮想通貨の市場データがCSVファイルとして保存されます。このCSVファイルは、データ分析ツールやエクセルで開くことができます。

必要なライブラリインストール

pip install argparse requests pandas

スクリプト実行

パラメータが正しい場合

> py .\get_crypto_market_data.py bitcoin
データを bitcoin_prices.csv に保存しました

パラメータに誤りがある場合

> py .\get_crypto_market_data.py bitcoinxxxxx
仮想通貨名 bitcoinxxxxx は無効です。以下の有効な仮想通貨名を参考にしてください:
b20, baanx, baasid, babacoin, babb, baby-alvey, babyama, baby-aptos, baby-arbitrum, baby-bali, baby-bitcoin, babybnbtiger, babyboo, babydoge2-0, babydogearmy, baby-doge-cash, baby-doge-ceo, babydoge-ceo, baby-doge-coin, babydoge-coin-eth, baby-doge-inu, babydot, babyfloki, baby-floki, baby-floki-coin, baby-floki-inu, baby-g, babykitty, baby-lambo-inu, babylon-finance, babylons, baby-lovely-inu, baby-moon-floki, babypepe, baby-pepe, babypepeentire, babyrabbit, baby-richard-heart, baby-saitama, baby-samo-coin, baby-shark, baby-shark-tank, baby-shiba-coin, baby-shiba-inu, babyswap, babywhale, baby-woj, babyxrp, bacondao, badger-dao, badger-sett-badger, bad-idea-ai, bafi-finance-token, bagholder, bai-stablecoin, baked-token, bakerytoken, bakerytools, baklava, balanced-dollars, balance-network, balancer, balancer-80-bal-20-weth, balancer-aave-boosted-wmatic, balancer-boosted-aave-dai, balancer-boosted-aave-usdc, balancer-boosted-aave-usdt, balancer-boosted-aave-weth, balancer-maticx-boosted-aave-wmatic, balance-tokens, bali-token, bali-united-fc-fan-token, ball-coin, balloonsville-air, ballswap, ball-token, balpha, balto-token, bambi, bamboo-coin, bamboo-defi, bamboo-token-c90b31ff-8355-41d6-a495-2b16418524c2, banana, bananace, bananaclubtoken, banana-coin, bananatok, banana-token, banano, bancor, bancor-governance-token, band-protocol, bandzai-token, bankbrc, bankera, bankercoin, bankers-dream, bankless-bed-index, bankless-dao, bankroll-extended-token, bankroll-vault, banksocial, bantu, bao-finance, bao-finance-v2, baousd, baptlabs, bark, barking, barnbridge, barter, bart-simpson-coin, based-ai, based-finance, basedpepe, based-shares, base-protocol, basic, basic-attention-token, basilisk, basis-cash, basis-gold-share-heco, basis-markets, basis-share, basketball-legends, basketcoin, baskonia-fan-token, bastion-protocol, bata, bathtub-protocol, battlefly, battle-for-giostone, battleforten, battle-hero, battle-infinity, battle-of-guardians-share, battle-pets, battle-saga, battleverse, battle-world, bayc-vault-nftx, baymax-finance, bazaars, bb-gaming, bbs-network, bcpay-fintech, b-cube-ai, bdollar, beacon, beam, beamswap, bean, bean-2, bean-cash, bear-inu, bear-scrub-money, beatgen-nft, beauty-bakery-linked-operation-transaction-technology, becoswap-token, bedlingtonterriertoken, bedrock, beechat, beeco, beefy-escrowed-fantom, beefy-finance, beenode, beep-coin, beer, beer-money, beethoven-x, beetroot, befasterholdertoken, befitter, befitter-health, beholder, bela, beldex, belifex, bella-protocol, bellcoin, belt, beluga-fi, beluga-protocol, bemchain, be-meta-famous, bemil-coin, ben-2, benddao, benft-solutions, benqi, benqi-liquid-staked-avax, ben-s-finale, benzene, bep20-leo, bepay, bepro-network, beradex, bergerdoge, bermuda, berry, berry-data, berryswap, berylbit, beryltriochain, beskar, bet2bank, beta-finance, beta-token, betero, betswap-gg, betswirl, betted, betterfan, betterment-digital, beyondcoin, beyond-finance, beyond-protocol, bezoge-earth, bfg-token, bficoin, bfx-finance, bhbd, bhive, bhnetwork, bho-network, biaocoin, bibi, biblecoin, biblepay, bibox-token, bib-token, biconomy, biconomy-exchange-token, bidao, bidao-smart-chain, bidipass, bidshop, bidz-coin, bifi, bifrost, bifrost-native-coin, bigcap, big-crypto-game, big-data-protocol, big-defi-energy, big-digital-shares, big-eyes, biggerminds, big-panda, bigshortbets, big-turn, bikerush, bilira, billiard-crypto, billionaires-pixel-club, billionhappiness, billy-token, bim, binamon, binance-bitcoin, binancecoin, binance-coin-wormhole, binance-eth, binanceidr, binance-peg-avalanche, binance-peg-bitcoin-cash, binance-peg-cardano, binance-peg-dogecoin, binance-peg-eos, binance-peg-filecoin, binance-peg-firo, binance-peg-iotex, binance-peg-litecoin, binance-peg-ontology, binance-peg-polkadot, binance-peg-xrp, binance-usd, binance-wrapped-btc, binance-wrapped-dot, binarydao, binaryx, binaryx-2, bincentive, binemon, bingo, binspirit, binstarter, bintex-futures, biokript, biometric-financial, biopassport, bios, birake, birb-2, bird-money, birdtoken, biskit-protocol, bismuth, biso, bistroo, biswap, bit2me, bitazza, bitball, bitbar, bitbase-token, bitbook-token, bitboost, bitcanna, bitcash, bitcastle, bitcci-cash, bitcicoin, bitci-racing-token, bitcoin, bitcoin-2, bitcoin-2-0, bitcoin-asia, bitcoin-avalanche-bridged-btc-b, bitcoinbam, bitcoin-bep2, bitcoin-br, bitcoin-cash, bitcoin-cash-sv, bitcoin-confidential, bitcoin-diamond, bitcoin-e-wallet, bitcoin-fast, bitcoin-free-cash, bitcoin-god, bitcoin-gold, bitcoin-green, bitcoin-hd, bitcoin-legend, bitcoinmono, bitcoin-pay, bitcoinpepe, bitcoin-plus, bitcoinpos, bitcoin-private, bitcoin-pro, bitcoin-red, bitcoin-scrypt, bitcoin-subsidium, bitcoin-trc20, bitcointry-token, bitcoinv, bitcoin-vault, bitcoinvb, bitcoinx, bitcoinz, bitcoiva, bitconey, bitcore, bitdao, bite, bitenium-token, bitflowers, bitforex, bit-game-verse-token, bitget-token, bithachi, bithash-token, bit-hotel, bitica-coin, bitindi-chain, bitkub-coin, bitlocus, bitmark, bitmart-token, bitmeme, bitmex-token, bitmon, bito-coin, bitone, bitorbit, bitoreum, bitpaid-token, bitpanda-ecosystem-token, bitrise-token, bitrue-token, bitscrow, bitshares, bitshiba, bitsniper, bitsong, bitspawn, bitstake, bitsten-token, bit-store-coin, bitstubs, bitsum, bittensor, bittoken, bittorrent, bittorrent-old, bittube, bittwatt, bitvalley, bitvote, bitwhite, bitxor, bitzen, bitzipp, biu-coin, blackcoin, blackdragon-token, black-eyed-dragon, blackhat-coin, blackhole-protocol, blackpearl-chain, black-phoenix, blackpool-token, black-rabbit-ai, blacksmith-token, black-stallion, blade, blank, blast-frontiers, blaze-network, blazestake-staked-sol, bless-global-credit, blind-boxes, blin-metaverse, blithe, blitz-labs, blitzpredict, blizzard-network, blizz-finance, blocery, block-ape-scissors, blockasset, blockaura, blockbank, blockbase, blockblend, blockblend-2, blockcdn, blockchain-bets, blockchain-brawlers, blockchain-certified-data-token, blockchain-cuties-universe-governance, blockchain-euro-project, blockchaingames, blockchain-monster-hunt, blockchainpoland, blockchainspace, blockcreate, block-e, blockescrow, blockgpt, blockless, blockmax, blocknet, blockombat, blockport, blockportal, blockremit, blockrock, blocks, blockscape, blocksmith-labs-forge, blocksport, blocksquare, blockstack, blockstar, blockster, blocksworkz, blockton, blockv, blockverse, blockx, bloc-money, blocsport-one, blocto-token, blokpad, bloktopia, bloody-bunny, bloom, blossom, blox, bloxmove-erc20, blox-token, blu, blueart, blue-baikal, bluebenx-2, bluebit, bluefin, bluejay, bluemove, bluesale, blueshift, bluesparrow, bluesparrow-token, bluewizard, blur, blurt, bluzelle, bmax, bmchain-token, bnb-bank, bnb-diamond, bnbpot, bnbtiger, bnext-b3x, bnktothefuture, bnpl-pay, bnsd-finance, bns-token, bob, boba-brewery, boba-network, bobcoin, bob-coin, bobo, bobo-coin, bobs_repair, bob-token, bocachica, bocoin, boda-token, bodrumspor-fan-token, body-ai, bogdanoff, bogey, bogged-finance, boid, boji, boku, bolide, bolivarcoin, bollycoin, bologna-fc-fan-token, bolt, boltbot, bolt-token-023ba86e-eb38-41a1-8d32-8b48ecfcb2c7, bomb, bombcrypto-coin, bomber-coin, bomb-money, bonded-cronos, bondly, bone-2, bonerium-boneswap, bone-shibaswap, boneswap, bone-token, bonfida, bonfire, bongweedcoin, bonk, bontecoin, boo, boo-finance, boo-mirrorworld, boop, boosted-lusd, booster, bora, borderless-money, borealis, bored, bored-apemove, bored-ape-social-club, bored-candy-city, bored-pepe-vip-club, boringdao, boringdao-[old], boring-protocol, bosagora, boson-protocol, boss, bossswap, bostrom, botopiafinance, bot-planet, botto, bottos, botxcoin, bountie-hunter, bounty0x, bountykinds-yu, bountymarketcap, bovineverse-bvt, bowl-shibarium, bowscoin, boxa, bpegd, b-protocol, bracelet, brain-sync, braintrust, brandpad-finance, brave-power-crystal, brazil-fan-token, brcp-token, brd, bread, breederdao, brewlabs, brick, brick-token, bridged-trueusd, bridge-mutual, bridge-network, bridge-oracle, bright-token, bright-union, brise-paradise, britto, brmv-token, brn-metaverse, broccoli, brokkr, brokoli, broovs-projects, brother-music-platform, brr-protocol, bruce-pepe, bruv, brz, bscex, bsclaunch, bscpad, bscstarter, bsc-station, bsdium, bsv, btaf-token, btc-2x-flexible-leverage-index, btcmoon, btc-proxy, btc-standard-hashrate-token, btf, btour-chain, btrips, bts-chain, btse-token, btu-protocol, bubblefong, bubu, buckhath-coin, buddy-dao, buff-coin, buff-doge-coin, buffedshiba, buffswap, build, buildup, bullbear-ai, bull-btc-club, bull-coin, bullet-2, bullets, bull-game, bullieverse, bullion, bull-market, bullperks, bull-token, bumblebot, bumble-c, bumoon, bumper, bundles, bunicorn, bunnypark, bunnypark-game, bunny-token-polygon, bunscake, burency, burger-swap, burn, burp, burrow, bursaspor-fan-token, busd-plenty-bridge, busdx, business-universe, busy-dao, butter, butterfly-protocol-2, buying, buymainstreet, buymore, bware-infra, b-watch-box, bxh, byepix, byld, bysl, byteball, bytecoin, byteex, bytenext, bytom, bytz, bzetcoin, bzx-protocol

以上、Pythonを使って仮想通貨の市場データを取得する方法についての紹介でした。このスクリプトが仮想通貨のデータ分析や機械学習のプロジェクトに役立つことを願っています。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

文系の大学を卒業後、未経験でWebエンジニアとしての道を歩む。
プログラミングスクールで基礎を学び、Webエンジニアとして就職。
今ではプロジェクト経験15年以上のベテランエンジニアに。
 
今までの経験を活かし、プログラミング関連の情報や生活に役立つ情報を配信していきます。

コメント

コメント一覧 (1件)

コメントする

目次