-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetCryptoPortfolio.py
More file actions
142 lines (119 loc) · 4.93 KB
/
GetCryptoPortfolio.py
File metadata and controls
142 lines (119 loc) · 4.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# +
import requests
import pandas as pd
import time
import json
def GetCryptoPortfolio(year, cryptoCurrencies, inFiatCurrency):
"""
This function returns the value of the crypto currency
on the first day of the year. This can help in reporting crypto portfolio in Norway.
Thanks to Coingecko for an amazing free API.
Parameters:
year (string):The year in YYYY format.
cryptoCurrencies (dictionary):Keys are name of the cryptocurrency and values
are positions for each cryptocurrency.
inFiatCurrency (string):The fiat currency in which the value needs to be returned
input examples "usd", "nok", "sek" etc.
Returns:
df(dataframe):The dataframe containing the portfolio value.
"""
date = "01-01-"+year
apiData = {"Date" : [],
"Cryptocurrency": [],
"Position":[],
"Price in {0}".format(inFiatCurrency.upper()): []} # Creating a dictionary
for i in cryptoCurrencies.keys():
"""
This loop sends API calls and retrieves the values and updated the apiData dictionary
"""
url ="https://api.coingecko.com/api/v3/coins/{0}/history?date={1}".format(i.lower(), date)
x = requests.get(url)
response = x.json()
priceinCurrency = round(response["market_data"]["current_price"][inFiatCurrency.lower()],2)
apiData["Date"].append(date)
apiData["Cryptocurrency"].append(i)
apiData["Position"].append(cryptoCurrencies[i])
apiData["Price in {0}".format(inFiatCurrency.upper())].append(priceinCurrency)
time.sleep(5) #avoiding multiple requests to the api in a short time scale
df = pd.DataFrame(apiData)
df["CryptoValue in {}".format(inFiatCurrency.upper())] = round((df["Price in {0}".format(inFiatCurrency.upper())] * df["Position"]), 2)
df.to_csv(r"output/CryptoPortfolio.csv", index=False) # Save as a CSV
return df # Return the resulting dataframe
# +
# Testing : GetCryptoPortfolio
#year = "2021"
#cryptos = {"Bitcoin": 2,"Ethereum": 4}
#fiat = "nok"
#df = GetCryptoPortfolio(year, cryptos, fiat)
#df
# -
def CreatePortfolioPieChart(fiatCurrency):
"""
This function generates a pie chart of the portfolio in the input fiat currency.
Parameters:
inFiatCurrency (string):The fiat currency in which the value needs to be returned
input examples "usd", "nok", "sek" etc.
Returns:
none
"""
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("output/CryptoPortfolio.csv")
plt.figure()
plt.rcParams["figure.figsize"] = (10,3)
plt.rcParams['font.size'] = 8
values = df.iloc[:, 4].to_list()
labels = df.iloc[:, 1].to_list()
explode = (0.08,) * df.iloc[:, 4].count()
colors = ['#008DB8', '#00AAAA', '#00C69C', '#00E28E', '#00FF80', '#191970', '#001CF0', '#0038E2', '#0055D4', '#0071C6', ]
colors = colors[0:df.iloc[:, 4].count()]
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return fiatCurrency.upper() +' {v:d}'.format(v=val)
return my_autopct
fig1, ax1= plt.subplots()
ax1.pie(values, colors=colors, explode=explode,
autopct=make_autopct(values),
shadow=False, startangle=30)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title("Crypto Portfolio as of {0}".format(df.iat[0,0]))
plt.legend(labels=labels, loc="best")
plt.tight_layout()
plt.savefig('output/CryptoPortfolioPieChart.png', dpi=200)
# +
# Testing : CreatePortfolioPieChart
#CreatePortfolioPieChart("nok")
# -
def CreatePortfolioTreeMapChart(fiatCurrency):
"""
This function generates a TreeMap chart of the portfolio in the input fiat currency.
Parameters:
inFiatCurrency (string):The fiat currency in which the value needs to be returned
input examples "usd", "nok", "sek" etc.
Returns:
none
"""
import matplotlib.pyplot as plt
import pandas as pd
import squarify
df = pd.read_csv("output/CryptoPortfolio.csv")
plt.figure()
plt.rcParams["figure.figsize"] = (10,3)
plt.rcParams['font.size'] = 8
labels =[]
colors = ['#008DB8', '#00AAAA', '#00C69C', '#00E28E', '#00FF80', '#191970', '#001CF0', '#0038E2', '#0055D4', '#0071C6', ]
colors = colors[0:df.iloc[:, 4].count()]
for index, row in df.iterrows():
labels.append(row["Cryptocurrency"] + "\n"+fiatCurrency.upper()+" "+str(row["CryptoValue in {}".format(fiatCurrency.upper())]))
values = df.iloc[:, 4].to_list()
squarify.plot(sizes=values, label=labels, color=colors, alpha=0.6)
plt.title("Crypto Portfolio as of {0}".format(df.iat[0,0]))
plt.axis('off')
plt.tight_layout()
plt.savefig('output/CryptoPortfolioTreeMapChart.png', dpi=200)
# +
# Testing : CreatePortfolioTreeMapChart
#CreatePortfolioTreeMapChart("nok")
# -