Jump to content

Module:Gold Price

From Wikipedia, the free encyclopedia
local p = {}

local mwWikibase = mw.wikibase

-- Month names for display
local MONTHS = {
	"January", "February", "March", "April", "May", "June",
	"July", "August", "September", "October", "November", "December"
}

function p.main(frame)
	-- Troy ounces (argument 1)
	local ounces = tonumber(frame.args[1])
	if not ounces then
		return ""
	end

	-- Gold item (Q897)
	local entity = mwWikibase.getEntity("Q897")
	if not entity or not entity.claims or not entity.claims.P2284 then
		return ""
	end

	-- Use the first (most recent) price statement
	local claims = entity.claims.P2284
	local mostRecentClaim = claims[#claims]
	if not mostRecentClaim.mainsnak or not mostRecentClaim.mainsnak.datavalue then
		return ""
	end

	-- Extract price value
	local priceValue = mostRecentClaim.mainsnak.datavalue.value
	local price = math.floor(tonumber(priceValue.amount)+0.5)
	if not price then
		return ""
	end

	-- Extract timestamp (prefer qualifier P585)
	local timestamp
	if mostRecentClaim.qualifiers and mostRecentClaim.qualifiers.P585 then
		timestamp = mostRecentClaim.qualifiers.P585[1].datavalue.value.time
	elseif priceValue.time then
		timestamp = priceValue.time
	end

	-- Format date text
	local dateText = ""
	if timestamp then
		local year, month = timestamp:match("%+(%d+)%-(%d+)")
		if year and month then
			dateText = " (as of " .. MONTHS[tonumber(month)] .. ", " .. year .. ")"
		end
	end

	-- Calculate total value
	local total = ounces * price

	-- Format currency (USD)
	local formatted = "$" .. mw.language.getContentLanguage():formatNum(
		tonumber(string.format("%.2f", total))
	)

	return formatted .. dateText
end

return p