"""C08 构造教学模型。标准库、确定性输出;所有最优性范围见各条输入。 执行后写入脚本相邻 JSON。未调用行情、求解器或外部资料。 """ from itertools import product from math import sqrt from pathlib import Path import json def dot(a, b): return sum(x*y for x, y in zip(a, b)) def quad(w, s): return sum(w[i]*s[i][j]*w[j] for i in range(len(w)) for j in range(len(w))) def cov(a, b): if len(a) < 2 or len(a) != len(b): raise ValueError('协方差需要至少两个对齐观测') ma, mb = sum(a)/len(a), sum(b)/len(b) return sum((x-ma)*(y-mb) for x, y in zip(a, b))/(len(a)-1) def simplex(n, units): for k in product(range(units+1), repeat=n): if sum(k) == units: yield [v/units for v in k] def c078(): inp = {'assets':['A','B','C','D'], 'box':[0,70], 'step':10, 'constraints':[['总资金',[1,1,1,1],'=',100],['行业甲',[1,1,0,0],'>=',60],['行业乙',[0,0,1,1],'>=',50]], 'relaxed_industry_b_min':40, 'unit':'净资产百分点'} grid = list(product(range(inp['box'][0],inp['box'][1]+1,inp['step']), repeat=4)) def check(w, mask, bmin=None): vals=[] for index,(_,coefficients,op,bound) in enumerate(inp['constraints']): if index==2 and bmin is not None: bound=bmin value=dot(w,coefficients) vals.append(value==bound if op=='=' else value>=bound) return all(vals[index] for index in range(3) if mask&(1<=minimum] for c in inp['one_side_caps']],'feasible_count_without_turnover':len(feasible)}} def c083(): inp={'mu':[.01,.03,.05,.07],'current':[.2,.5,.8],'curvature':.08,'buy_cost':.01,'sell_cost':.006,'bounds':[0,1], 'threshold_mu':[.033,.034,.04,.05,.051],'threshold_current':.5,'unit':'单期净资产比例;解析连续解'} def solve(mu,h): k,cb,cs=inp['curvature'],inp['buy_cost'],inp['sell_cost']; lo=k*h-cs; hi=k*h+cb x=h if lo<=mu<=hi else ((mu+cs)/k if mu=target]; checks.append([target,bounds[0][-1],max(starts) if starts else None,max(0,target-bounds[0][-1])]) return {'input':inp,'output':{'daily_path':days,'start_day_upper_bounds':bounds,'deadline_tests':checks,'final_inventory':inv,'final_cash':cash, 'conservation':dot(inv,inp['prices'])+cash,'initial_nav':dot(inp['inventory'],inp['prices'])+inp['cash']}} def build(): funcs=[c078,c079,c080,c081,c082,c083,c084,c085,c086,c087,c088] return {f'DJ4-{78+i:03d}':f() for i,f in enumerate(funcs)} if __name__ == '__main__': result=build() Path(__file__).with_suffix('.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8',newline='\n')