"""C12 构造家庭支出案例。仅标准库;从输入计算表格,不复现官方统计调查。 保存为 .py 后直接执行;输出到自身相邻 .json。金额单位元,比例最终展示 时四舍五入两位,内部用 Decimal。未知量保留 None,不把缺失视作零。 """ from datetime import date from decimal import Decimal, ROUND_HALF_UP from pathlib import Path import json def d(x): return Decimal(str(x)) def show(x): if x is None: return '未知' return str(d(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)) def pct(a, b): return None if b == 0 else d(a) / d(b) * 100 def table(headers, rows): return {'headers': headers, 'rows': rows} def price_bridge(items): rows = [] totals = [Decimal(0)] * 8 for name, p0, q0, p1, q1 in items: p0,q0,p1,q1 = map(d, (p0,q0,p1,q1)) vals = [p0*q0, p1*q0, p1*q1, (p1-p0)*q0, p1*(q1-q0), p0*(q1-q0), (p1-p0)*q1, (p1-p0)*(q1-q0)] totals = [a+b for a,b in zip(totals, vals)] rows.append([name] + [show(v) for v in vals]) rows.append(['合计']+[show(v) for v in totals]) return table(['商品','旧价旧量','现价旧量','现价现量','先价格效应','后数量效应','先数量效应','后价格效应','交互项'],rows) def case122(): items = [['米/千克',6,10,7,12],['鸡蛋/盒',12,4,13,3],['青菜/千克',5,8,6,10]] alt = [[n,p,q,p1,q] for n,p,q,p1,q1 in items] return {'inputs': {'items':items, 'contrast':'现期数量全部改为基期数量'}, 'tables':{'inputs':table(['商品/计量单位','旧单价','旧数量','现单价','现数量'],items), 'bridge':price_bridge(items), 'contrast':price_bridge(alt)}} def crosswalk(records, targets): originals = list(dict.fromkeys(x[1] for x in records)) rows=[] for old in originals: amounts=[sum(r[3] for r in records if r[1]==old and r[2]==new) for new in targets] rows.append([old]+amounts+[sum(amounts)]) sums=[sum(r[i+1] for r in rows) for i in range(len(targets)+1)] rows.append(['合计']+sums) return table(['原分类']+targets+['合计'],rows) def case123(): records=[['A','日用','食品',400],['B','日用','家清',180],['C','日用','文具',120], ['D','日用','未识别',300],['E','交通','交通',200],['F','居住','居住',800]] targets=['食品','家清','文具','交通','居住','未识别'] current={'食品':500,'家清':220,'文具':140,'交通':220,'居住':820} alt=[r[:] for r in records] alt[3][2]='食品' oldknown={k:sum(r[3] for r in records if r[2]==k) for k in current} comparisons=[[k,oldknown[k],v,v-oldknown[k], '存在未识别影响' if k in targets[:3] else '完全可比'] for k,v in current.items()] return {'inputs':{'records':records,'current':current,'contrast':'补得D单据,证实300元全部食品'}, 'tables':{'inputs':table(['凭证','原分类','证据可映射目标','金额'],records), 'matrix':crosswalk(records,targets), 'comparison':table(['新类别','旧已识别','现期','与已识别额差','状态'],comparisons), 'contrast':crosswalk(alt,targets)}} def person_days(periods, reference): rows=[] for p in periods: days=sum(x[1]*x[2] for x in p['segments']) per=d(p['shared'])/days rows.append([p['period'],days,p['shared'],p['fixed'],p['shared']+p['fixed'],show(per),show(per*reference+p['fixed'])]) return table(['期间','实际人日','共同消费','固定住房','总支出','元/人日','标准化至60人日加固定费'],rows) def case124(): periods=[{'period':'基期30天','segments':[[1,2,30]],'shared':1800,'fixed':3000}, {'period':'现期30天','segments':[[1,2,30],[2,1,15]],'shared':2400,'fixed':3000}] alt=[periods[0],{'period':'现期新增者住满30天','segments':[[1,2,30],[2,1,30]],'shared':2400,'fixed':3000}] inputs=[[p['period'],str(p['segments']),p['shared'],p['fixed']] for p in periods] return {'inputs':{'periods':periods,'reference_person_days':60,'contrast':alt[1]}, 'tables':{'inputs':table(['期间','分段[标记,人数,天数]','共同消费/元','固定住房/元'],inputs), 'comparison':person_days(periods,60),'contrast':person_days(alt,60)}} def basket(items): b=sum(d(p)*d(q) for n,p,q,p1,q1 in items) old=new=actual=Decimal(0);rows=[] for n,p,q,p1,q1 in items: x,y,z=d(p)*d(q),d(p1)*d(q),d(p1)*d(q1) old+=x;new+=y;actual+=z rows.append([n,show(x),show(y),show(pct(x,b)),show(pct(d(p1)-d(p),p)),show(pct(y-x,b))]) rows.append(['合计',show(old),show(new),show(100),'不求平均',show(pct(new-old,old))]) summary=[['基期篮子成本',show(old)],['同篮子现价成本',show(new)],['固定篮子价格涨幅/%',show(pct(new-old,old))], ['替换为现期数量后的实际成本',show(actual)],['实际成本增幅/%',show(pct(actual-old,old))]] return table(['商品','基期成本','固定数量现价成本','基期权重/%','单价涨幅/%','价格贡献/百分点'],rows),table(['指标','结果'],summary) def case125(): items=[['米/千克',5,20,6,15],['牛奶/盒',10,30,11,20],['公交/次',2,50,2,40]] fixed,summary=basket(items) return {'inputs':{'items':items,'contrast':'实际数量换成15、20、40,仅计算实际成本;固定篮子仍20、30、50'}, 'tables':{'inputs':table(['商品/单位','基期价','基期量','现期价','实际现期量'],items),'basket':fixed,'contrast':summary}} def category_growth(items): base=sum(x[1] for x in items);current=sum(x[2] for x in items);rows=[] for n,a,b in items: rows.append([n,a,b,b-a,show(pct(a,base)),show(pct(b-a,a)) if a else '不定义',show(pct(b-a,base))]) rows.append(['合计',base,current,current-base,show(100),show(pct(current-base,base)),show(pct(current-base,base))]) return table(['类别','基期额','现期额','差额','基期权重/%','类别增幅/%','总增幅贡献/百分点'],rows) def case126(): items=[['住房',6000,6300],['餐食',2000,2200],['交通',1000,900],['新课程',0,600]] alt=[[n,a,0 if a==0 else b] for n,a,b in items] rates=[pct(b-a,a) for n,a,b in items if a] return {'inputs':{'items':items,'contrast':'新课程现期额改为0,其他不变'}, 'tables':{'growth':category_growth(items),'contrast':category_growth(alt), 'wrong':table(['算法','结果/%'],[['直接平均三个有定义类别增幅',show(sum(rates)/len(rates))], ['用全部金额计算总增幅',show(pct(sum(x[2]-x[1] for x in items),sum(x[1] for x in items))) ]])}} def meal_mix(items): q0=sum(x[2] for x in items);q1=sum(x[4] for x in items) cost0=sum(d(x[1])*x[2] for x in items);cost1=sum(d(x[3])*x[4] for x in items) fixed=sum(d(x[3])*x[2] for x in items)/q0 rows=[[n,p0,q_0,show(pct(q_0,q0)),p1,q_1,show(pct(q_1,q1)),p0*q_0,p1*q_1] for n,p0,q_0,p1,q_1 in items] summary=[['基期总均价',show(cost0/q0)],['现期总均价',show(cost1/q1)],['按基期结构的现价均价',show(fixed)], ['价格效应/元每餐',show(fixed-cost0/q0)],['结构效应/元每餐',show(cost1/q1-fixed)],['总均价增幅/%',show(pct(cost1/q1-cost0/q0,cost0/q0))]] return table(['餐型','旧价','旧餐数','旧占比/%','现价','现餐数','现占比/%','旧费用','现费用'],rows),table(['指标','结果'],summary) def case127(): a=[['家中餐',10,80,10,50],['外食餐',40,20,40,50]] b=[['家中餐',10,80,12,50],['外食餐',40,20,44,50]] ar,ass=meal_mix(a);br,bss=meal_mix(b) return {'inputs':{'scene_a':a,'scene_b':b},'tables':{'scene_a':ar,'summary_a':ass,'scene_b':br,'summary_b':bss}} def household_average(houses): total=sum(h[1] for h in houses);people=sum(h[2] for h in houses) rows=[[n,c,p,show(d(c)/p),show(pct(p,people)),show(d(c)/people)] for n,c,p in houses] simple=sum(d(c)/p for n,c,p in houses)/len(houses) summary=[['家庭数',len(houses)],['总支出',total],['总人数',people],['各户人均简单平均',show(simple)], ['汇总人均',show(d(total)/people)],['两种平均差额',show(simple-d(total)/people)]] return table(['家庭','支出/元','人数','户内人均/元','人口权重/%','汇总人均贡献/元'],rows),table(['指标','结果'],summary) def case128(): a=[['甲',3000,1],['乙',6000,3],['丙',6000,4]] b=[['甲',6000,2],['乙',4000,2],['丙',3000,2]] ar,ass=household_average(a);br,bss=household_average(b) return {'inputs':{'houses':a,'contrast_equal_people':b},'tables':{'houses':ar,'summary':ass,'contrast':br,'contrast_summary':bss}} def coverage(records, missing_bounds): matrix=[];common0=common1=known0=known1=0 for month,a0,b0,a1,b1 in records: observed0=sum(x for x in [a0,b0] if x is not None);observed1=sum(x for x in [a1,b1] if x is not None) known0+=observed0;known1+=observed1 joint=all(x is not None for x in [a0,b0,a1,b1]) if joint:common0+=observed0;common1+=observed1 matrix.append([month,a0 if a0 is not None else '缺失',b0 if b0 is not None else '缺失',a1 if a1 is not None else '缺失',b1 if b1 is not None else '缺失','是' if joint else '否']) low=known1+sum(x[1] for x in missing_bounds);high=known1+sum(x[2] for x in missing_bounds) summary=[['基期已知全年',known0],['现期已观察合计/全年下界',known1],['共同完整月份基期',common0],['共同完整月份现期',common1], ['共同子集增幅/%',show(pct(common1-common0,common0))],['假设缺失范围后全年下端',low],['假设缺失范围后全年上端',high], ['假设全年增幅下端/%',show(pct(low-known0,known0))],['假设全年增幅上端/%',show(pct(high-known0,known0))]] return table(['月份','基期A/元','基期B/元','现期A/元','现期B/元','两账户共同完整'],matrix),table(['指标','结果'],summary) def case129(): records=[[m,800,200,880 if m<=9 else None,220 if m<=9 else None] for m in range(1,13)] bounds=[[m,900,1400] for m in range(10,13)] alt=[[m,0,2000] for m in range(10,13)] matrix,summary=coverage(records,bounds);_,contrast=coverage(records,alt) return {'inputs':{'records':records,'missing_combined_monthly_bounds':bounds,'contrast_bounds':alt,'bound_assumption':'所有遗漏支出非负,无遗漏退款;上下端仅构造情景'}, 'tables':{'coverage':matrix,'bounds':table(['缺失月份','两账户合计假设下端','假设上端'],bounds),'summary':summary,'contrast':contrast}} def perimeter(records, base): seen=set();rows=[];raw=common=new=excluded=0 for rid,account,amount,kind,econ in records: raw+=amount if kind=='内部转账': status='排除内部转账';excluded+=amount elif econ in seen: status='排除重复观测';excluded+=amount else: seen.add(econ) if account in base:common+=amount;status='共同账户外部消费' else:new+=amount;status='新增范围外部消费' rows.append([rid,account,amount,kind,econ,status]) return table(['流水','账户','流出/元','性质','经济事件号','计入状态'],rows),{'raw':raw,'excluded':excluded,'common':common,'new':new,'total':common+new} def case130(): base_accounts=['银行卡'];old=5000 records=[['R1','银行卡',5400,'外部消费','E1'],['R2','银行卡',1000,'内部转账','T1'], ['R3','新钱包',900,'外部消费','E2'],['R4','新钱包',200,'外部消费','E3'], ['R5','银行卡',200,'外部消费','E3'],['R6','现金',300,'外部消费','E4']] tx,s=perimeter(records,base_accounts) # 共同归属按输入顺序首次记录;R4钱包先于R5,故E3归新增范围。 bridge=[['基期旧账范围',old],['共同账户外部消费变化',s['common']-old],['新增范围外部消费',s['new']],['现期全范围外部消费',s['total']],['原始流出',s['raw']],['排除转账与重复',s['excluded']]] contrast=[] for history in [None,1000]: expanded_old=None if history is None else old+history growth=None if expanded_old is None else pct(s['total']-expanded_old,expanded_old) contrast.append(['未知' if history is None else history,'未知' if expanded_old is None else expanded_old,'不计算' if growth is None else show(growth)]) return {'inputs':{'old_common_external':old,'base_accounts':base_accounts,'records':records,'assignment_rule':'同一事件归首次记录账户;明确R4钱包为主记录,R5银行卡为重复镜像','old_new_scope_external':None,'contrast_verified_history':1000}, 'tables':{'transactions':tx,'bridge':table(['范围桥步骤','金额/元'],bridge),'contrast':table(['新增范围可核验历史额','补齐后的基期总额','全范围增幅/%'],contrast)}} def event_window(events, records, width): rows=[];summary=[] for year,event in events.items(): window=outside=jan=annual=0 for when,amount in records[year]: day=date.fromisoformat(when);delta=(day-date.fromisoformat(event)).days included=-width<=delta<=width annual+=amount;jan+=amount if day.month==1 else 0 if included:window+=amount else:outside+=amount rows.append([year,when,delta,amount,'窗内' if included else '窗外']) summary.append([year,event,2*width+1,jan,window,outside,annual,window+outside]) return table(['构造年','日期','距构造事件/天','费用/元','归属'],rows),table(['年份','构造事件日','窗口日数','一月合计','窗口合计','窗口外','全年全部输入','回代'],summary) def case131(): events={'2030':'2030-01-30','2031':'2031-02-15'} records={'2030':[['2030-01-10',200],['2030-01-25',500],['2030-01-30',1000],['2030-02-04',400],['2030-12-01',300]], '2031':[['2031-01-10',220],['2031-02-10',550],['2031-02-15',1100],['2031-02-20',440],['2031-12-01',330]]} detail,summary=event_window(events,records,7);_,contrast=event_window(events,records,3) return {'inputs':{'events':events,'records':records,'half_window_days':7,'contrast_half_window_days':3,'scope':'两年日期均构造,不表示历史春节;每年全年账本仅含所列五笔'}, 'tables':{'dates':detail,'summary':summary,'contrast':contrast}} def dual_view(periods, prices): cashrows=[];quantityrows=[];expanded=[] for period,cash,meals,rides in periods: meal_est=0 if meals == 0 else (None if prices['meal'] is None else meals*prices['meal']) ride_est=0 if rides == 0 else (None if prices['ride'] is None else rides*prices['ride']) cashrows.append([period,cash]) quantityrows.append([period,meals,rides]) partial=cash+sum(v for v in [meal_est,ride_est] if v is not None) complete=meal_est is not None and ride_est is not None expanded.append([period,cash,show(meal_est),show(ride_est),partial,'完整' if complete else '仅部分估价,不称完整总额']) return table(['期间','现金餐食与通勤/元'],cashrows),table(['期间','单位供餐/份','单位班车/次'],quantityrows),table(['期间','现金/元','餐食估价/元','班车估价/元','已估部分加现金/元','状态'],expanded) def case132(): periods=[['基期',1200,0,0],['现期',800,20,10]] prices={'meal':15,'ride':None};alt={'meal':15,'ride':5} cash,qty,expanded=dual_view(periods,prices);_,_,contrast=dual_view(periods,alt) return {'inputs':{'periods':periods,'illustrative_prices':prices,'contrast_illustrative_prices':alt,'estimation_assumption':'单价仅管理情景,不为福利或税务标准;餐食与班车已实际消费、未计入现金费用'}, 'tables':{'cash':cash,'quantity':qty,'expanded':expanded,'contrast':contrast}} def main(): cases={f'DJ4-{n}':globals()[f'case{n}']() for n in range(122,133)} output=json.dumps(cases,ensure_ascii=False,indent=2,allow_nan=False)+'\n' Path(__file__).with_suffix('.json').write_text(output,encoding='utf-8',newline='\n') if __name__=='__main__': main()