예제 #1
0
#this python script has the gnuplot script for plotting already integrated. Please change the all-cap variables
#according to your needs

import time
import os
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()

BitcoinPrice=cg.get_coin_market_chart_by_id(id='bitcoin',vs_currency='eur',days=30)
datafile=open('PATH_TO_WHERE_THE_DATA_SHALL_STORED_AS_/data.txt', 'w')
for i in xrange(len(BitcoinPrices['prices'])):
    datafile.write(time.strftime('%Y.%m.%d %H:%M:%S', time.localtime((BitcoinPrices['prices'][i][0])/1000))+' '+str(BitcoinPrices['prices'][i][1])+'\n')
datafile.close()

datafile=open('PATH_TO_WHERE_YOUR_PLOT_SCRIPT_IS_TO_BE_STORED_AS/script.gnu','w')

#you may want to put the whole script in a single line in your IDE
datafile.write(
"set terminal 'pdf'\n 
set output 'PATH_TO_WHERE_THE_PLOT_SHALL_STORED_AS_/plot.pdf'\n 
set title 'historic BTC Price'\n 
set xlabel 'time'\n 
set ylabel 'Price/EUR'\n 
set xdata time\n 
set timefmt '%Y.%m.%d %H:%M:%S'\n 
set format x '"'%m.%d'"'\n 
set xtics'"'STARTDATE_YYYY.MM.DD'"',432000,'"'ENDDATE_YYYY.MM.DD'"'\n 
plot 'PATH_TO_WHERE_THE_DATA_SHALL_STORED_AS_/data.txt' u 1:3 w l notitle")
datafile.close()

os.system('gnuplot PATH_TO_WHERE_YOUR_PLOT_SCRIPT_IS_TO_BE_STORED_AS/script.gnu')
예제 #2
0
            }
new_mapping = {}

dates = []
date_dummy = datetime.datetime(2013,4,27)
today = str(datetime.datetime.today().date())
while date_dummy < datetime.datetime(int(today[:4]), int(today[5:7]), int(today[8:10])):
    date_dummy = date_dummy + datetime.timedelta(days=1)
    dates.append(date_dummy)
dates_df = pandas.DataFrame({'date': dates})
dfs = [dates_df]
days = 'max'

#looping through all coins
for i in range (0,len(mapping['name'])):
    data = cg.get_coin_market_chart_by_id(mapping['name'][i], vs_currency='usd', days= days)
    coin_data = {}
    coin_dates = []
    coin_prices = []
    coin_vols = []
    coin_caps = []
    for time, val in data['prices']:
        dt = datetime.datetime.fromtimestamp(int(time)/1000)
        coin_dates.append(dt)
        coin_prices.append(val)
    for time, val in data['total_volumes']:
        coin_vols.append(val)
    for time, val in data['market_caps']:
        coin_caps.append(val)
    coin_data = {'date': coin_dates, 'prices': coin_prices, 'total_volume': coin_vols, 'market_cap': coin_caps}
예제 #3
0
 this_coin = pd.DataFrame(columns=['date_unix',
                       'date_string',
                       'id',
                       'symbol',
                       'name',
                       'price_usd',
                       'market_cap',
                       'volume']
                         )
 coinData = None
 time.sleep(0.6)
 while coinData is None:
     try:
         coinData = cg.get_coin_market_chart_by_id(id=symbol['id'],
                                                   vs_currency='usd',
                                                   days=30000,
                                                   interval='daily'
                                                   )
     except Exception as e:
         print(e)
         time.sleep(10)
         print("Resuming...")
 
 n_days = len(coinData['prices'])
 if n_days < 31:
     coin = {'date_unix': 0,
             'date_string': '1970-01-01',
             'id': symbol['id'],
             'symbol': symbol['symbol'],
             'name': symbol['name'],
             'price_usd': 0,
def get_fund_ROI(address, file_name):
    sent = requests.get(
        'https://api.bloxy.info/widget/address_value_daily?address=' +
        address +
        '&currency=ETH&key=ACCunOMWYpmCp&format=table&price_currency=USD'
    ).json()
    df1 = pd.DataFrame(sent)
    df1.rename(columns={0: 'Date-USD', 11: 'ROI'}, inplace=True)
    df1['ROI-USD'] = df1.ROI.cumsum()

    sent = requests.get(
        'https://api.bloxy.info/widget/address_value_daily?address=' +
        address +
        '&currency=ETH&key=ACCunOMWYpmCp&format=table&price_currency=ETH'
    ).json()
    df2 = pd.DataFrame(sent)
    df2.rename(columns={0: 'Date', 11: 'ROI'}, inplace=True)
    df2['ROI-ETH'] = df2.ROI.cumsum()

    df = pd.concat([df1, df2], axis=1,
                   sort=False)[['Date', 'ROI-USD', 'ROI-ETH']]
    df = df.set_index('Date')
    df.index = pd.to_datetime(df.index)

    cmc = yf.Ticker("^CMC200")

    hist = cmc.history(period="max")[['Open']]
    hist['Open'] = (np.where(hist['Open'] < 100, hist['Open'] * 10,
                             hist['Open']))

    df = pd.concat([df, hist], axis=1, sort=False)
    df = df.interpolate(axis=0).dropna(subset=['ROI-USD'])

    start_cmc200 = df.head(1)['Open'][0]
    df['CMC200-USD'] = (((df['Open'] - start_cmc200) / start_cmc200) * 100)
    df = df[['ROI-USD', 'ROI-ETH', 'CMC200-USD']]

    cg = CoinGeckoAPI()

    data = cg.get_coin_market_chart_by_id('bitcoin', 'eth', 500)

    dates = [
        datetime.fromtimestamp(data['prices'][i][0] /
                               1000).strftime('%Y-%m-%d')
        for i in range(len(data['prices']))
    ]
    price = [data['prices'][i][1] for i in range(len(data['prices']))]

    df_data = {'BTC-ETH': price, 'Date': dates}
    df_btc = pd.DataFrame(df_data)
    df_btc = df_btc.set_index('Date')
    df_btc.index = pd.to_datetime(df_btc.index)

    df = pd.concat([df, df_btc], axis=1, sort=False)
    df = df.dropna(subset=['ROI-USD'])

    start_btc = df.head(1)['BTC-ETH'][0]
    df['BTC-ETH'] = (((df['BTC-ETH'] - start_btc) / start_btc) * 100)

    df.drop(df.tail(1).index, inplace=True)

    df.to_csv(file_name, index=True)
def Malta(file_name):

    # Get the NAV, and sharePrice of the fund on each priceUpdate
    jsonData = '{"query": "{fundCalculationsHistories(where: {fund: \\"0x26491fc7da30b35d818de45982fb1de4f65ed8f5\\"}) { nav, timestamp, totalSupply, source}}"}'
    data = requests.post(
        'https://api.thegraph.com/subgraphs/name/melonproject/melon',
        data=jsonData).json()['data']

    roi = []
    nav = []
    timestamp = []

    for i in range(len(data['fundCalculationsHistories'])):
        if (data['fundCalculationsHistories'][i]['source'] == 'priceUpdate'):
            roi.append(
                int(data['fundCalculationsHistories'][i]['nav']) /
                int(data['fundCalculationsHistories'][i]['totalSupply']))
            nav.append(int(data['fundCalculationsHistories'][i]['nav']) / 1e18)
            timestamp.append(
                (int(data['fundCalculationsHistories'][i]['timestamp'])))

    while (len(data['fundCalculationsHistories']) == 100):
        jsonData = '{"query": "{fundCalculationsHistories(where: {fund: \\"0x26491fc7da30b35d818de45982fb1de4f65ed8f5\\", timestamp_gt:\\"' + str(
            timestamp[-1] +
            1) + '\\"}) { nav, timestamp, totalSupply, source}}"}'
        data = requests.post(
            'https://api.thegraph.com/subgraphs/name/melonproject/melon',
            data=jsonData).json()['data']

        for i in range(len(data['fundCalculationsHistories'])):
            if (data['fundCalculationsHistories'][i]['source'] == 'priceUpdate'
                ):
                roi.append(
                    int(data['fundCalculationsHistories'][i]['nav']) /
                    int(data['fundCalculationsHistories'][i]['totalSupply']))
                nav.append(
                    int(data['fundCalculationsHistories'][i]['nav']) / 1e18)
                timestamp.append(
                    (int(data['fundCalculationsHistories'][i]['timestamp'])))

    df1 = pd.DataFrame({'NAV': nav, 'ROI-ETH': roi}, index=timestamp)

    # Get the price of USDC on each price update
    jsonData = '{"query": "{assetPriceHistories(where: {asset: \\"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\\", , timestamp_gt: \\"' + str(
        timestamp[0] - 1) + '\\"}) {price, timestamp}}"}'
    data = requests.post(
        'https://api.thegraph.com/subgraphs/name/melonproject/melon',
        data=jsonData).json()['data']

    price = []
    timestamp = []

    for i in range(len(data['assetPriceHistories'])):
        price.append(int(data['assetPriceHistories'][i]['price']) / 1e18)
        timestamp.append((int(data['assetPriceHistories'][i]['timestamp'])))

    while (len(data['assetPriceHistories']) == 100):
        jsonData = '{"query": "{assetPriceHistories(where: {asset: \\"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\\", , timestamp_gt: \\"' + str(
            timestamp[-1] + 1) + '\\"}) {price, timestamp}}"}'
        data = requests.post(
            'https://api.thegraph.com/subgraphs/name/melonproject/melon',
            data=jsonData).json()['data']

        for i in range(len(data['assetPriceHistories'])):
            price.append(int(data['assetPriceHistories'][i]['price']) / 1e18)
            timestamp.append(
                (int(data['assetPriceHistories'][i]['timestamp'])))

    df2 = pd.DataFrame(price, index=timestamp, columns=['USD-ETH'])

    df = pd.concat([df1, df2], axis=1, sort=False)

    df['ROI-USD'] = ((df['ROI-ETH'] / df['USD-ETH']) /
                     (1 / df.iloc[0]['USD-ETH']) - 1) * 100
    df['ROI-ETH'] = (df['ROI-ETH'] - 1) * 100
    df.index = pd.to_datetime(df.index, unit='s').strftime('%Y-%m-%d')
    df = df[~df.index.duplicated(keep='first')]
    df.index.name = 'Date'

    df.to_csv(file_name[:-4] + '_raw.csv', index=True)

    cmc = yf.Ticker("^CMC200")

    hist = cmc.history(period="max")[['Open']]
    hist['Open'] = (np.where(hist['Open'] < 100, hist['Open'] * 10,
                             hist['Open']))
    hist.index = pd.to_datetime(hist.index).strftime('%Y-%m-%d')

    df = pd.concat([df, hist], axis=1, sort=True)
    df = df.interpolate(axis=0).dropna(subset=['ROI-USD'])

    df.index = pd.to_datetime(df.index).strftime('%Y-%m-%d')

    start_cmc200 = df.head(1)['Open'][0]
    df['CMC200-USD'] = (((df['Open'] - start_cmc200) / start_cmc200) * 100)
    df = df[['ROI-USD', 'ROI-ETH', 'CMC200-USD']]

    cg = CoinGeckoAPI()

    data = cg.get_coin_market_chart_by_id('bitcoin', 'eth', 500)

    dates = [
        datetime.fromtimestamp(data['prices'][i][0] /
                               1000).strftime('%Y-%m-%d')
        for i in range(len(data['prices']))
    ]
    price = [data['prices'][i][1] for i in range(len(data['prices']))]

    df_btc = pd.DataFrame({'BTC-ETH': price}, index=dates)
    df_btc.index = pd.to_datetime(df_btc.index).strftime('%Y-%m-%d')

    df_btc.drop(df_btc.tail(1).index, inplace=True)

    df = pd.concat([df, df_btc], axis=1, sort=True)
    df = df.dropna(subset=['ROI-USD'])

    start_btc = df.head(1)['BTC-ETH'][0]
    df['BTC-ETH'] = (((df['BTC-ETH'] - start_btc) / start_btc) * 100)

    df.drop(df.tail(1).index, inplace=True)

    df.to_csv(file_name, index=True)
#!/usr/bin/env python
# coding: utf-8

# In[1]:CODE TO OBTAIN CANDLE STICK PLOT TO GET PRICE FLUCTUATION ON BITCOIN FOR PAST 30 DAYS

get_ipython().system('pip install pycoingecko')  #INSTALL pycoingecko
from pycoingecko import CoinGeckoAPI  #Import CoinGecko API

cg = CoinGeckoAPI()

bitcoin_data = cg.get_coin_market_chart_by_id(id='bitcoin',
                                              vs_currency='usd',
                                              days=30)

bitcoin_price_data = bitcoin_data['prices']

import pandas as pd

data = pd.DataFrame(bitcoin_price_data, columns=['TimeStamp', 'Price'])

print(data)

data['Date'] = pd.to_datetime(data['TimeStamp'], unit='ms')

print(data)

candlestick_data = data.groupby(data.Date.dt.date).agg(
    {'Price': ['min', 'max', 'first', 'last']})

candlestick_data