# source: https://medium.com/huddlofficial/how-to-buy-bitcoin-at-deep-discounts-599492ba5556
import requests
from datetime import datetime as dt
import statistics
from tabulate import tabulate as tb
apikey = 'YOUR_API_KEY'
url = 'https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&allData=true'
#url = 'https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=2000'
headers = {'authorization': apikey}
r = requests.get(url, headers=headers).json()
df = {'datetime': [], 'Open': []}
for i in range(len(r['Data']['Data'])):
df['datetime'].append(dt.fromtimestamp(r['Data']['Data'][i]['time']).strftime('%Y-%m-%d'))
df['Open'].append(float(r['Data']['Data'][i]['open']))
btc_price_list = []
invested = 0
hodlings = .0
table = [['Date', 'Investment', 'BTC price', 'Bought', 'Hodlings', 'Value', 'Invested', 'Profit $', 'Profit %', 'DCAD']]
for i in range(len(df['datetime'])):
if df['datetime'][i][-2:] == '01': # monthly.
# if df['datetime'][i][-5:] == '01-01': # annually.
investment = 100
btc_price = float('{:.2f}'.format(df['Open'][i]))
btc_price_list.append(btc_price)
bought = float('{:.8f}'.format(investment / btc_price))
hodlings = float('{:.8f}'.format(hodlings + bought))
value = float('{:.2f}'.format(hodlings * btc_price))
invested += investment
profita = float('{:.2f}'.format(value - invested))
profitp = float('{:.2f}'.format((value - invested) / invested * 100))
arithmetic_mean = statistics.mean(btc_price_list)
harmonic_mean = statistics.harmonic_mean(btc_price_list)
dcad = float('{:.2f}'.format((arithmetic_mean - harmonic_mean) / arithmetic_mean * 100))
table.append([
df['datetime'][i], investment, btc_price, bought, hodlings, value, invested, profita, profitp, dcad
])
table.append(table[0])
print (tb(table, headers='firstrow', tablefmt='grid', showindex='always'))