"""Invented teaching fixtures; no forecast or investment recommendation."""
from fractions import Fraction as F
def npv(flows,rate):
 rate=F(str(rate));flows=[F(str(x)) for x in flows]
 if rate<=-1 or not flows:raise ValueError('Require flows and rate greater than -1')
 return sum((x/(1+rate)**i for i,x in enumerate(flows)),F(0))
def cash_bridge(opening,receipts,payments):
 if len(receipts)!=len(payments):raise ValueError('Period lengths differ')
 balance=F(str(opening));out=[]
 for receipt,payment in zip(receipts,payments):
  balance+=F(str(receipt))-F(str(payment));out.append(balance)
 return out
def runway(cash,reserve,burn):
 cash,reserve,burn=map(lambda x:F(str(x)),(cash,reserve,burn))
 if burn<=0 or reserve<0 or cash<reserve:raise ValueError('Require positive burn and cash at least reserve')
 return (cash-reserve)/burn
def ols(xs,ys):
 if len(xs)!=len(ys) or len(xs)<2:raise ValueError('Require paired observations')
 xs=list(map(F,xs));ys=list(map(F,ys));mx=sum(xs)/len(xs);my=sum(ys)/len(ys)
 sxx=sum((x-mx)**2 for x in xs)
 if not sxx:raise ValueError('Predictor must vary')
 slope=sum((x-mx)*(y-my) for x,y in zip(xs,ys))/sxx;intercept=my-slope*mx
 residuals=[y-intercept-slope*x for x,y in zip(xs,ys)]
 return slope,intercept,residuals,sum(e*e for e in residuals)
if __name__=='__main__':
 print('NPV:',float(npv([-100000,60000,60000],'.1')))
 print('Closing cash:',cash_bridge(200000,[100000,80000,120000],[150000,160000,140000]))
 print('Months above reserve:',runway(300000,100000,50000))
 print('OLS slope, intercept, residuals, SSE:',ols([1,2,3,4],[2,4,5,8]))
