Skip to content

Instantly share code, notes, and snippets.

@foxcool
Created August 26, 2023 02:17
Show Gist options
  • Save foxcool/e467ce3dc6ecf8ce13a9d47cccc277c6 to your computer and use it in GitHub Desktop.
Save foxcool/e467ce3dc6ecf8ce13a9d47cccc277c6 to your computer and use it in GitHub Desktop.
Example of simple portfolio balance management with R
library(jsonlite)
# Get prices
url <- "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=dai,usd-coin,bitcoin,ethereum,polkadot,kusama,the-open-network,cosmos,tezos,1inch,moonbeam,ksm,aave,optimism,ethereum-name-service,gitcoin,maker,uniswap,acala-dollar-acala,binance-usd,hydradx,astar,tether"
data <- fromJSON(url)
token_data <- split(data, data$id)
# Define portfolio (collect token amounts from different sources in a list)
holdings <- list(
"bitcoin" = c(0.07),
"ethereum" = c(0.45, 0.095),
"dai" = c(2393, 1052),
"usd-coin" = c(89, 949),
"tether" = c(309),
"the-open-network" = c(1250),
"polkadot" = c(284, 236),
"maker" = c(0.79),
"optimism" = c(526),
"1inch" = c(2006),
"moonbeam" = c(3680),
"uniswap" = c(143.34),
"cosmos" = c(46.65),
"gitcoin" = c(274.39),
"ethereum-name-service" = c(24.81),
"kusama" = c(16.87),
"hydradx" = c(45535),
"aave" = c(3.23),
"tezos" = c(255.64),
"astar" = c(3905)
)
# Define target percentages
target_percentages <- c(
bitcoin = 15,
ethereum = 15,
dai = 10,
`usd-coin` = 10,
tether = 10,
`the-open-network` = 9,
polkadot = 9,
maker = 3,
optimism = 3,
`1inch` = 3,
moonbeam = 3,
uniswap = 2,
cosmos = 1,
gitcoin = 1,
`ethereum-name-service` = 1,
kusama = 1,
hydradx = 1,
aave = 1,
tezos = 1,
astar = 1
)
# Calculate the token quantities by token
token_quantities <- sapply(holdings, sum)
# Calculate the token sums
token_sums <- sapply(
names(token_quantities),
function(token) token_quantities[token] * token_data[[token]]$current_price,
USE.NAMES = FALSE
)
# Calculate the differences token sums with target sums
target_diffs <- token_sums - total_sum * target_percentages / 100
# Calculate the total sum
total_sum <- sum(unlist(token_sums))
# Calculate the percentages of each token in the portfolio
percentages <- token_sums / total_sum * 100
portfolio <- data.frame(
sum = token_sums,
quantity = unlist(token_quantities, use.names = FALSE),
percentage = percentages,
diff = target_diffs
)
print(total_sum)
print(portfolio)
# Create a pie chart
pie(token_sums, labels = names(token_quantities), main = "Token Portfolio")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment