Query editor
WITH daily_prices AS (with all_prices as (SELECTpp.hour,pp.condition_id,pp.token_id,case when pp.hour <= DATE_PARSE(SUBSTRING(pd.market_end_time FROM 1 FOR 19), '%Y-%m-%dT%H:%i:%s') then pricewhen pp.hour > DATE_PARSE(SUBSTRING(pd.market_end_time FROM 1 FOR 19), '%Y-%m-%dT%H:%i:%s') thenCASE when pd.token_outcome = 'Yes' and outcome = 'yes' then 1when pd.token_outcome = 'Yes' and outcome = 'no' then 0when pd.token_outcome = 'No' and outcome = 'yes' then 0when pd.token_outcome = 'No' and outcome = 'no' then 1 END ELSE price END as price_modFROM polymarket_polygon.market_prices_hourly ppleft join polymarket_polygon.market_details pd on pp.token_id = pd.token_id--WHERE ((pd.resolved_on_timestamp > p.hour) or (pd.resolved_on_timestamp is null)))SELECTlast_day_of_month(date_trunc('day', hour)) AS day,token_id,max_by(price_mod, hour) AS price_modFROM all_pricesGROUP BY 1, 2),token_balance_over_time AS (SELECTp.day,md.event_market_name as market,SUM(balance) AS balance_shares,SUM(balance * price_mod) AS balance_usdFROM polymarket_polygon.positions pINNER JOIN daily_prices mph ON mph.token_id = p.token_id AND mph.day = p.dayINNER JOIN polymarket_polygon.market_details md on p.token_id = md.token_idWHERE address != 0xa5ef39c3d3e10d0b270233af41cac69796b12966and ((md.resolved_on_timestamp >= p.day) or (md.resolved_on_timestamp is null))GROUP BY p.day, 2),market_rankings_today AS (SELECTmarket,balance_usd,ROW_NUMBER() OVER (ORDER BY balance_usd DESC) AS rankFROM (SELECTmarket,SUM(balance_usd) AS balance_usdFROM token_balance_over_timeWHERE day > now()- interval '2' dayGROUP BY market) ranked_markets),historical_market_balances AS (SELECTtb.day,market,SUM(balance_usd) AS balance_usd