Beispiel #1
0
 def test_main(self):
     mock_trading = mock.create_autospec(simulate.TradingSimulate)
     with mock.patch.object(tradeapi, 'REST', return_value=self.alpaca) as alpaca_init, \
             mock.patch.object(simulate, 'TradingSimulate', return_value=mock_trading) as trading_init, \
             mock.patch.object(
                 argparse.ArgumentParser, 'parse_args',
                 return_value=argparse.Namespace(start_date=None, end_date=None,
                                                 api_key='fake_api_key',
                                                 api_secret='fake_api_secret')):
         simulate.main()
     alpaca_init.assert_called_once_with('fake_api_key', 'fake_api_secret',
                                         utils.ALPACA_PAPER_API_BASE_URL, 'v2')
     trading_init.assert_called_once()
     mock_trading.run.assert_called_once()
Beispiel #2
0
 def _pushButtonclick(self):
     self.reset_data()
     a1, a2, a3 = simulate.main(self.RF,self.RFPLL,self.TF,self.TFPLL,self.IFPLL,self.BASE,self.SPAN,self.CLK)
     for i in range(len(a2)):
         if (len(a1[i]) != 0):
             message = str(a2[i]) + " " + str(len(a1[i]))
             self.threads.run_(message)
             str_name = a2[i]
             str_name = str_name.split('_')
             if len(str_name) == 2:
                 str_name = str_name[1]
                 for j in range(len(a1[i])):
                     message = str(j + 1) + " " + str(str_name) + " " + '*' + " " + str(a3[i][j]) + " " +  '=' + " " + str(a1[i][j])
                     self.threads.run_(message)
                 self.threads.terminate()
             elif len(str_name) == 3:
                 str_name1 = str_name[1]
                 str_name2 = str_name[2]
                 for j in range(len(a1[i])):
                     message = str(j + 1) + " " + str(str_name1) + " " + '*' + " " + str(a3[i][j][0]) + " " + '+' + " " + str(str_name2) + " " + '*' + " " + str(a3[i][j][1]) + " " +  '=' + " " + str(a1[i][j])
                     self.threads.run_(message)
                 self.threads.terminate()
             else:
                 continue
         else:
             continue
def Qfunc(theta):
    
    '''
    This is a function that calculates the distance between simulated moments 
    and the actual moments for the setup used for table 2
    '''
    
    import kgrid
    import zgrid
    import z_markov
    import simulate as sim
    import VFI
    
    # getting the grid space for capital
    kgrid, sizek = kgrid.main(params,w,a_k)

    # getting the grid space for shocks
    z_grid, pi = zgrid.main(sigma, mu, rho, sizez)

    # getting firm's optimal decision rule
    V, PF = VFI.main(theta, params, z_grid, kgrid, sizek, sizez, 
                                               pi, a_k, w, psi)
    
    # simulate the data 
    k_sim, I_sim, V_sim, pi_sim = sim.main(theta, params, kgrid, 
                                               pi, V, PF, N, T, z_grid)

   
    # define variables of interest
    I_K = (I_sim/k_sim).reshape((N*T, 1))
    Qav = (V_sim/k_sim).reshape((N*T, 1))
    PI_K = (pi_sim/k_sim).reshape((N*T, 1))
    
    # get the necessary statistics 
    I_Kr = I_K.reshape((1, N*T))
    sc = np.corrcoef(I_Kr[0][1:], I_Kr[0][:N*T-1])[0,1]
    sd = np.std(PI_K)
    qbar = V_sim.sum() / k_sim.sum()

    # run the q-regression
    Y = np.matrix(I_K)
    X = np.matrix(np.concatenate((np.ones((N*T, 1)), Qav, PI_K), axis = 1))
    a0, a1, a2 = np.linalg.inv(X.T * X) * X.T * Y 

    # construct the vectors
    mu_sim = np.array((a1[0, 0], a2[0, 0], sc, sd, qbar))
    mu_real = np.array((.03, .24, .4, .25, 3))
    
    # identity matrix
    Wmat = np.eye(len(mu_sim))

    # get the distance between simulated statistics and the actual statistics
    dist = np.matrix((mu_real - mu_sim)) * np.linalg.inv(Wmat) * np.matrix((mu_real - mu_sim)).T

    return dist
def get_sim(theta):
    
    '''
    This is a function that returns the simulated moments 
    to be used to obtain the standard errors
    '''
    
    import kgrid
    import zgrid
    import z_markov
    import simulate as sim
    import VFI
    
    # getting the grid space for capital
    kgrid, sizek = kgrid.main(params,w,a_k)

    # getting the grid space for shocks
    z_grid, pi = zgrid.main(sigma, mu, rho, sizez)

    # getting firm's optimal decision rule
    V, PF = VFI.main(theta, params, z_grid, kgrid, sizek, sizez, 
                                               pi, a_k, w, psi)
    
    # simulate the data 
    k_sim, I_sim, V_sim, pi_sim = sim.main(theta, params, kgrid, 
                                               pi, V, PF, N, T, z_grid)

   
    # define variables of interest
    I_K = (I_sim/k_sim).reshape((N*T, 1))
    Qav = (V_sim/k_sim).reshape((N*T, 1))
    PI_K = (pi_sim/k_sim).reshape((N*T, 1))
    
    # get the necessary statistics 
    I_Kr = I_K.reshape((1, N*T))
    sc = np.corrcoef(I_Kr[0][1:], I_Kr[0][:N*T-1])[0,1]
    sd = np.std(PI_K)
    qbar = V_sim.sum() / k_sim.sum()

    # run the q-regression
    Y = np.matrix(I_K)
    X = np.matrix(np.concatenate((np.ones((N*T, 1)), Qav, PI_K), axis = 1))
    a0, a1, a2 = np.linalg.inv(X.T * X) * X.T * Y 

    # construct the vectors
    mu_sim = np.array((a1[0, 0], a2[0, 0], sc, sd, qbar))
    
    return mu_sim
Beispiel #5
0
def main():

    global buttonPlay_rect, buttonQuit_rect, BASICFONT, DISPLAYWINDOW, bgColor, buttonPlay, buttonQuit

    pygame.init()

    FPSCLOCK = pygame.time.Clock()
    pygame.display.set_icon(pygame.image.load('assets/gameicon.png'))
    DISPLAYWINDOW = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Insanity')

    # Load the sound files
    """BEEP1 = pygame.mixer.Sound('beep1.ogg')
    BEEP2 = pygame.mixer.Sound('beep2.ogg')
    BEEP3 = pygame.mixer.Sound('beep3.ogg')
    BEEP4 = pygame.mixer.Sound('beep4.ogg')"""

    # Initialize some variables
    lastClickTime = 0 # timestamp of the player's last button push
    score = 0
    bgColor = pygame.image.load("assets/menubackground.jpg").convert()

    # Load images of the buttons
    init_button_img()
    init_img()

    # Create buttons for the menu
    buttonPlay = pygame.image.load("assets/menubutton_play.bmp").convert_alpha()
    buttonQuit = pygame.image.load("assets/menubutton_quit.bmp").convert_alpha()

    BASICFONT = pygame.font.Font('freesansbold.ttf', 16)

    isPlaying = False



    while True: # main game loop

        checkForQuit()
        if isPlaying == False:
            isPlaying = menu()

        lives = 3
        difficulty = 0
        result = 0
        gamesPlayed = []

        while isPlaying and lives > 0:
            resetGameFrame()
            checkForQuit()
            difficulty = random.randint(0,2)

            gameChoice = random.choice(('Arinoid','Tetris', 'Maze','Simulate','Inkspill'))
            if(gameChoice not in gamesPlayed):
                difficulty = 0

            print(gameChoice + ", difficulty : " + str(difficulty))
            if(gameChoice == "Simulate"):
                result = simulate.main(difficulty)
            elif(gameChoice == "Arinoid"):
                continue # Not implemented
            elif(gameChoice == "Tetris"):
                continue # Not implemented
            elif(gameChoice == "Maze"):
                result = bipo_main.main(difficulty)
            elif(gameChoice == "Inkspill"):
                result = inkspill.main(difficulty)

            gamesPlayed.append(gameChoice)

			# 'result' is either 0 (if the game has been won) or -1 (if the game has been lost)
            lives = lives + result
            score = score + result +1

            if lives > 0:
                displayScore(score,lives)
                pygame.time.wait(2000)

        isPlaying = gameOver(score)


        pygame.display.update()
        FPSCLOCK.tick(FPS)
Beispiel #6
0
            print("Case {} not found".format(i))

        # Running
        print("Starting case {}".format(case))

        # Completing data
        if 'initial_condition' not in case:
            case['initial_condition'] = ""
        filename = case["input"]
        directory = os.path.dirname(filename)
        if case['initial_condition'] == -1:
            initial_condition_file = os.path.join(directory, "preparation.output.json")
            if os.path.isfile(initial_condition_file):
                case['initial_condition'] = initial_condition_file

        # Simulating
        try:
            simulate.main(
                input=case['input'],
                format='json',
                initial_condition=case['initial_condition'],
                output='',
                name=''
            )
        except:
            print("Not converged")

        print("End")

        # end
Beispiel #7
0
    old_groups[group_id] = {"id": group["id"], "name": group["name"]}
new_config["groups"] = old_groups
print("Group ID written to config")

if not "simulation_id" in old_groups[group_id]:
    print("Creating the simulation group")
    data = {"name": group["name"] + " Simulation"}
    headers = {"Content-Type": "application/json"}
    res = util.post_rest('groups', data=data, headers=headers)
    if res is None:
        print("Creating simulation groupme failed")
    else:
        old_groups[group_id]["simulation_id"] = res["id"]

util.write_config(new_config)

if not os.path.exists("groups"):
    os.mkdir("groups")
if not os.path.exists("groups/" + group_id):
    os.mkdir("groups/" + group_id)
    os.mkdir("groups/" + group_id + '/members')

print("Loading group information for first run")
load_messages.main(group_id, "reset")
print("Done loading group information")

print("Setup Complete")
run = input("Would you like to run the simulation? (y/n): ")
if run == 'y':
    simulate.main(group_id)
Beispiel #8
0
from simulate import main

cases = [
    # {'name': "colesoncove_pre",
    #  'input': "notebooks/colesoncove_pre.json",
    #  'output': "notebooks/colesoncove_pre.out.json",
    #  "reporting_interval": 1,
    #  "time_horizon": 1,
    #  "relative_tolerance": 1e-3,
    #  "MaxStep": 1,
    #  "MaxNumSteps": 1000000,
    #  },
    {'name': "colesoncove",
     'input': "notebooks/colesoncove.json",
     'output': "notebooks/colesoncove.out.json",
     'initial_condition': "notebooks/colesoncove_pre.out.json",
     "reporting_interval": 1,
     "time_horizon": 1,
     "relative_tolerance": 1e-3,
     "MaxStep": 1,
     "MaxNumSteps": 1000000,
     },
]



if __name__ == "__main__":
    for case in cases:
        main( **case )
Beispiel #9
0
        console.setLevel(logging.CRITICAL)

    # Set a format which is simpler for console use
    formatter = logging.Formatter('%(message)s')
    # Tell the handler to use this format
    console.setFormatter(formatter)
    # Add the handler to the root logger
    logging.getLogger('').addHandler(console)

    # Create a logger
    log = logging.getLogger(__name__)

    #
    # RUN SELECTED COMMAND
    #
    if cliArgs.command == "simulate":
        # Run simulate.py
        simulate.main(cliArgs)

    elif cliArgs.command == "list":
        # Run list.py
        list.main()

    elif cliArgs.command == "convert":
        # Run convert.py
        convert.main(cliArgs)

    elif cliArgs.command == "extract":
        # Run extract.py
        extract.main(cliArgs)
Beispiel #10
0
        "Ca": Cai,
    })

    with open("mc/{}_{}_pumped.json".format(filename, suffix), 'w') as outfile:
        json.dump(data_mc, outfile, indent=4)

    output_filename = "mc/{}_{}_pumped_{}.out.json".format(
        filename, suffix, id)

    simulate.main(
        name=filename,
        input="mc/{}_{}_pumped.json".format(filename, suffix),
        output=output_filename,
        initial_condition="notebooks/{}_{}_fixedW.out.json".format(
            filename, "cs"),
        init="notebooks/{}_{}_fixedW.out.json.init".format(filename, "cs"),
        reporting_interval=25 * 24 * 3600,
        time_horizon=1000 * 24 * 3600,
        relative_tolerance=1e-3,
        MaxStep=10 * 24 * 3600,
        MaxNumSteps=100,
    )
    os.remove(output_filename + ".init")
    with open(output_filename) as f:
        json_data = f.read()

    output = json.loads(json_data)
    output2 = output.copy()

    for key in output.keys():
        if key in ("condenser.Rf", "condenser.Alc", "condenser.Ca",