Skip to content

Weighted average investment percent change #1476

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 31 additions & 11 deletions packages/app/features/home/InvestmentsBalanceCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { useMemo } from 'react'
import { IconCoin, IconError } from 'app/components/icons'
import { useCoins } from 'app/provider/coins'
import { investmentCoins as investmentCoinsList } from 'app/data/coins'
import { formatUnits } from 'viem'
import { HomeBodyCard } from './screen'

export const InvestmentsBalanceCard = (props: CardProps) => {
Expand Down Expand Up @@ -141,22 +142,41 @@ function OverlappingCoinIcons({
}

function InvestmentsAggregate() {
const tokenIds = useCoins()
.investmentCoins.filter((c) => c?.balance && c.balance > 0n)
.map((c) => c.coingeckoTokenId)
const coins = useCoins().investmentCoins.filter((c) => c?.balance && c.balance > 0n)

const tokenIds = coins.map((c) => c.coingeckoTokenId)
const { data: marketData, isLoading, isError } = useMultipleTokensMarketData(tokenIds)

const { totalValue, assetValues } = useMemo(() => {
if (!marketData?.length) return { totalValue: 0, assetValues: [] }

// Calculate values for each asset and total
const assetValues = coins.map((coin) => {
const marketInfo = marketData.find((m) => m.id === coin.coingeckoTokenId)
if (!marketInfo || !coin.balance) return { value: 0, percentChange: 0 }

const parsedBalance = formatUnits(coin.balance, coin.decimals)
return {
value: Number(parsedBalance) * (marketInfo.current_price ?? 0),
percentChange: marketInfo.price_change_percentage_24h ?? 0,
}
})

const totalValue = assetValues.reduce((sum, asset) => sum + asset.value, 0)

return { totalValue, assetValues }
}, [marketData, coins])

const aggregatePercentage = useMemo(() => {
if (!marketData?.length) return 0
if (totalValue <= 0) return 0

// Simple average of percentage changes
const aggregatePercentage =
marketData.reduce((total, coin) => {
return total + (coin?.price_change_percentage_24h ?? 0)
}, 0) / marketData.length
const weightedPercentage = assetValues.reduce((sum, asset) => {
const weight = asset.value / totalValue
return sum + asset.percentChange * weight
}, 0)

return Number(aggregatePercentage.toFixed(2))
}, [marketData])
return Math.round(weightedPercentage * 100) / 100
}, [totalValue, assetValues])

if (tokenIds.length === 0)
return (
Expand Down
Loading