示例#1
0
def constructSimulation(graph, num_cars, link_len_range, run_graphics,
                        debug_construct, debug_sim):
    """Builds and runs the simulation given the input parameters
       graph: - a correct symbolic representation that is being simulated
       num_cars: - number of cars to be in the simulation
       link_len_range: - the range of values that the length of the roads can take
       run_graphics: - boolean indicating whether or not the graphical overlay should be generated
       debug_construct: - boolean indicating whether construction is being debugged
       debug_sim: - boolean indicating whether simulator is being debugged"""
    num_junctions = len(graph.node_list)
    num_roads = len(graph.link_list)

    road_angles = [x.angle for x in graph.link_list]
    road_lengths = setLinkLengths(graph.link_list, link_len_range,
                                  debug_construct)

    car_goals = [random.randint(0, num_junctions) for x in range(num_roads)]

    junc_pairs = []
    pre, post = None, None
    for link in graph.link_list:
        pre = link.from_node
        post = link.to_node
        if link.angle > 90 and link.angle <= 270:
            junc_pairs.append((post.label, pre.label))
            link.angle -= 180
        else:
            junc_pairs.append((pre.label, post.label))
        print("{}-{}\t{}\t{}".format(link.from_node.label, link.to_node.label,
                                     junc_pairs[-1], link.length))

    if not debug_construct:
        simulator.runSimulation(num_junctions,num_roads,num_cars,road_angles,road_lengths,\
                               junc_pairs,car_goals,run_graphics,debug_sim)
示例#2
0
def main():
    welcome()
    coins = fetchCoins()
    currency, quantity = inputBuy()
    try:
        price = coins[currency]['price']
    except Exception as e:
        dramaticTyping("Invalid currency entered, please try again \n")
        inputBuy()
    runSimulation(coins[currency]['price'], quantity, currency)
    quitMenu()
示例#3
0
    def test_largePortfolio(self):
        i = 1000000
        result = runSimulation(30, i, i * 0.04,
                               ((ConstantWithdrawalAmountStrategy(i * .04),
                                 Assets(.5, .5), 1.0), ), 1926, 1997)

        self.assertAlmostEqual(result.getSuccessRate(), .95, delta=.005)
示例#4
0
    def test_constantPercentRegression(self):
        result = runSimulation(
            30, 1.0, .1,
            ((ConstantPercentWithdrawalStrategy(.1), Assets(.5, .5), 1.0), ),
            1926, 1997)

        self.assertLessEqual(result.getSuccessRate(), .95)
示例#5
0
    def test_ramp(self):
        i = 1000000
        result = runSimulation(30, i, i * 0.04,
                               ((ConstantWithdrawalAmountStrategy(i * .04),
                                 LinearRamp(Assets(.8, .2), Assets(.2, .8),
                                            (30 + 1) * 12), 1.0), ), 1926,
                               1997)

        self.assertAlmostEqual(result.getSuccessRate(), .98, delta=.005)
示例#6
0
def trinity(length,
            initialWithdrawal,
            initialPortfolio,
            ignoreInflation=False,
            maxYear=trinityMaxYear):
    return runSimulation(length, 1000000, initialWithdrawal,
                         ((ConstantWithdrawalAmountStrategy(initialWithdrawal),
                           initialPortfolio.allocation, 1.0), ), 1926, maxYear,
                         ignoreInflation)
示例#7
0
    def test_multipleStrategies(self):
        i = 1000000
        result = runSimulation(30, i, i * 0.04,
                               ((ConstantWithdrawalAmountStrategy(
                                   i * .04 * .6), Assets(.5, .5), .6),
                                (ConstantWithdrawalAmountStrategy(
                                    i * .04 * .4), Assets(.5, .5), .4)), 1926,
                               1997)

        self.assertAlmostEqual(result.getSuccessRate(), .95, delta=.005)
示例#8
0
    def test_multipleDifferentStrategies(self):
        i = 1000000
        result = runSimulation(
            30, i, 0.0,
            ((ConstantWithdrawalAmountStrategy(i * .04 * .5), Assets(.5,
                                                                     .5), .5),
             (ConstantPercentWithdrawalStrategy(.10), Assets(1.0, 0.0), .5)),
            1926, 2009)

        # it always works because you never run out with a percent withdrwawal strategy
        self.assertAlmostEqual(result.getSuccessRate(), 1.0, delta=.005)
示例#9
0
文件: test_vpw.py 项目: gasserma/dwr
    def test_basicWithdrawal(self):
        retirementLength = 30
        initialPortfolio = 1 * 1000 * 1000

        result = runSimulation(
            retirementLength, initialPortfolio, .05 * initialPortfolio * .5,
            ((Vpw(.04, retirementLength, .75), Assets(.5, .5), 1.0), ), 1926,
            2009)

        result.getSimResults()

        print(result)
示例#10
0
    def test_noOptions(self):
        retirementLength = 30

        result = runSimulation(
            retirementLength, 1 * 1000 * 1000, 20000,
            ((GuytonKlinger(40000, False, False, False, False,
                            retirementLength), Assets(.5, .5), 1.0), ), 1926,
            2009)

        result.getSimResults()

        print(result)
示例#11
0
    def update_data(self):
        """Called each time that any watched property changes.
           We grab the parameters from the form and run the
           simulation in a 'pure' function
        """
        N = 120

        # Get the current slider values
        p = self.prepay_probability.value
        d = self.default_probability.value

        self.source.data = runSimulation(N,p,d)
示例#12
0
文件: main_dwr.py 项目: gasserma/dwr
from assets import Assets
from simulator import runSimulation
from strategies.guyton_klinger import GuytonKlinger
"""
This is just a playground file. Useful for running the profiler, first attempt at running the code, etc.
"""
retirementLength = 30
initialPortfolio = 1 * 1000 * 1000

result = runSimulation(
    retirementLength, initialPortfolio, .05 * initialPortfolio * .5,
    ((GuytonKlinger(.05 * initialPortfolio, True, True, True, True,
                    retirementLength), Assets(.5, .5), 1.0), ), 1926, 2009)

result.getSimResults()

print(result)
示例#13
0
from simulator import runSimulation, runMany

N = 120
p = 0.01
d = 0.01

dic = runSimulation(N,p,d)

str1 = "using a prepay rate of " + str(p)
str2 = " and a default rate of " + str(d)

print str1 + str2

print dic['x']

print dic['y']

runMany(120)
示例#14
0
    def test_notConjuringMoney(self):
        assets = Assets(.5, .5)
        i = 1000000
        simLength = 30

        strategies = [
            ((GuytonKlinger(i * .04, True, True, True, True,
                            simLength), assets, 1.0), True),
            ((ConstantWithdrawalAmountStrategy(i * .04), assets, 1.0), True),
            ((ConstantPercentWithdrawalStrategy(.04), assets, 1.0), True),
            ((Vpw(.02, simLength, .04), assets, 1.0), True),
            ((HebelerAuto(55), assets, 1.0), True),
            ((LeprechaunGoldStrategy(.04), assets, 1.0), False),
            ((YearlyLeprechaunGoldStrategy(.04), assets, 1.0), False)
        ]

        class mblp:  # stands for "Make better lambdas python"
            prePortfolio = Portfolio(assets, i)
            growth = None

        def pre(observedPrePortfolioValue, observedGrowth, strategies):
            if len(strategies) != 1:
                raise RuntimeError

            mblp.growth = max(observedGrowth)
            if hasattr(strategies[0], 'yearGrowthAccumulator'):
                mblp.growth = max(mblp.growth,
                                  max(strategies[0].yearGrowthAccumulator),
                                  1.0)

            mblp.prePortfolio.value = observedPrePortfolioValue

        def post(observedPortfolioValue, observedWithdrawal):
            mblp.prePortfolio.value -= observedWithdrawal
            mblp.prePortfolio.value = mblp.prePortfolio.value * mblp.growth
            maxPossible = mblp.prePortfolio.value
            observed = observedPortfolioValue
            if mblp.expectSuccess:
                self.assertGreaterEqual(maxPossible + .00000001,
                                        observed,
                                        msg="Leprechauns detected.")
            else:
                if maxPossible + .00000001 < observed:
                    mblp.sawAFailure = True

        for s in strategies:
            mblp.prePortfolio = Portfolio(assets, i)
            mblp.growth = None
            mblp.sawAFailure = False
            mblp.expectSuccess = s[1]

            testhook = {"pre": pre, "post": post}

            runSimulation(simLength,
                          i,
                          i * 0.02, (s[0], ),
                          1926,
                          2009,
                          ignoreInfation=True,
                          testCallback=testhook)

            if not mblp.expectSuccess and not mblp.sawAFailure:
                self.fail("Goblins detected.")
示例#15
0
def simulations():
    minYear = int(request.json.get("min_year", 1926))
    maxYear = int(request.json.get("max_year", 2009))
    failureThreshold = float(request.json.get("failure_threshold", 20 * 1000))
    initialPortfolioValue = float(
        request.json.get("initial_portfolio_value", 1 * 1000 * 1000))
    retirementLength = int(request.json.get("retirement_length", 30))

    strategies = []
    for s in request.json["strategies"]:
        args = s["args"]
        if type(s["asset_allocation"]) is dict:
            if s["asset_allocation"]["type"].lower() == "linear_ramp":
                allocation = LinearRamp(
                    Assets([float(f) for f in s["asset_allocation"]["start"]]),
                    Assets([float(f) for f in s["asset_allocation"]["end"]]),
                    (retirementLength + 1) * 12)
            else:
                raise NotImplemented("Unrecognized ramp: {0}".format(
                    s["asset_allocation"]["type"].lower()))
        else:
            allocation = Assets([float(f) for f in s["asset_allocation"]])
        weight = float(s.get("weight", 1.0))
        strategyType = s["type"]
        if strategyType.lower() == "guyton_klinger":
            strategy = GuytonKlinger(float(args.get("initial_amount")),
                                     bool(args.get("gk_pmr")),
                                     bool(args.get("gk_wr")),
                                     bool(args.get("gk_cpr")),
                                     bool(args.get("gk_pr")), retirementLength)
        elif strategyType.lower() == "const_amount":
            strategy = ConstantWithdrawalAmountStrategy(float(args["amount"]))
        elif strategyType.lower() == "const_percent":
            strategy = ConstantPercentWithdrawalStrategy(float(
                args["percent"]))
        elif strategyType.lower() == "hebeler_autopilot":
            strategy = HebelerAuto(int(args["age"]))
        elif strategyType.lower() == "vpw":
            strategy = Vpw(float(args["expected_return_percent"]),
                           int(retirementLength),
                           float(args["drawdown_percent"]))
        else:
            raise NotImplemented(
                "Unrecognized strategy: {0}".format(strategyType))

        strategies.append((strategy, allocation, weight))

    result = runSimulation(retirementLength, initialPortfolioValue,
                           failureThreshold, strategies, minYear, maxYear)

    results = result.getSimResults()
    initialWithdrawal = results[0]["withdrawals"][0]
    if strategyType.lower() == "const_percent":
        initialWithdrawal = initialPortfolioValue * float(args["percent"])
    if strategyType.lower() == "guyton_klinger":
        initialWithdrawal = float(args.get("initial_amount"))

    return flask.jsonify(initial_withdrawal_amt=initialWithdrawal,
                         simulation_start=minYear,
                         simulation_end=maxYear,
                         results=results,
                         stats=result.getStats(),
                         dist_stats=result.getDistStats(),
                         yearly_stats=result.getYearlyStats())