def individual_bowling_game(pid):

        min_value = 0
        total_sets = 10
        trial_3 = 0
        pins = 10
        game_scores = []
        for game_set in range(total_sets):
            if game_set == total_sets - 1:
                trial_1, trial_2, trial_3 = Game.set_score(
                    min_value, total_sets, game_set, pins)
                score = trial_1 + trial_2 + trial_3
            else:
                trial_1, trial_2 = Game.set_score(min_value, total_sets,
                                                  game_set, pins)
                score = trial_1 + trial_2

            bonus = Strategies.run_strategy(trial_1, trial_2)

            set_total_score = score + bonus

            if game_set == (total_sets - 1) and (trial_1 == pins or
                                                 (trial_1 + trial_2) == pins):
                trial_scores = Game.three_trail_set(trial_1, trial_2, trial_3,
                                                    set_total_score)
            else:
                trial_scores = Game.two_trail_set(trial_1, trial_2,
                                                  set_total_score)

            game_scores.append(trial_scores)
        Player.players[pid]['game_scores'] = game_scores
        Player.calculate_final_score(pid)
    def run_moving_average_strategy(self):
        """
        This method will run the moving average strategy.

        It will call our other methods to:
            - get the candlestick data
            - process the candlestick data
            - compute the buy and sell signals
            - backtest the strategy
            - plot the candlestick chart

        Parameter:

        Return:
            - None
        """
        binance = BinanceOperations(
        )  # Create instance of binance operations class
        strategies = Strategies()  # Create instance of strategies class

        # Get candlestick data (with good dates to see signals, for test reasons)
        # start_time = 1590624000000  # 28th of May 2020
        # end_time = 1593302400000  # 28th of June 2020
        # candlestick_data = binance.get_candlestick_data(self.symbol, start_time=start_time, end_time=end_time)

        # Get candlestick data
        candlestick_data = binance.get_candlestick_data(self.symbol)

        # Process the candlestick data
        candlestick_df = self.process_data(candlestick_data)

        # Compute buy and sell signals:
        signals = strategies.moving_average_strategy(candlestick_df,
                                                     quantity=1)
        buy_signals = signals[0]
        sell_signals = signals[1]

        # Backtest the strategy
        self.backtest_strategy(buy_signals, sell_signals)

        # Plot the candlestick data as candlestick chart
        self.plot_data(candlestick_df, buy_signals, sell_signals)
Example #3
0
    def compute_strategy(self, state, id_team, id_player):

        s = Strategies(state, id_team, id_player)
        v = SuperState(state, id_team, id_player)
        a = Actions(state, id_team, id_player)

        if v.player.distance(v.ball) < PLAYER_RADIUS + BALL_RADIUS:
            shoot = v.playeradverse - v.player
            return SoccerAction(shoot=shoot.normalize() * 3)
        else:
            return a.deplacement(v.ball)
Example #4
0
 def compute_strategy(self, state, id_team, id_player):
   
     s = Strategies(state, id_team, id_player)
     v = SuperState(state, id_team, id_player)
     a = Actions(state, id_team, id_player)
     
     if v.player.distance(v.ball) < PLAYER_RADIUS + BALL_RADIUS:
         return a.tircoequippier
     else :
         if v.ballecampadverse == 0:
             if id_team == 1 :
                 return a.deplacement(Vector2D((GAME_WIDTH/2)-5, v.ball.y))
             else :
                 return a.deplacement(Vector2D((GAME_WIDTH/2)+5, v.ball.y))
         else :
             return a.deplacement(v.ball)
Example #5
0
    def compute_strategy(self, state, id_team, id_player):

        s = Strategies(state, id_team, id_player)
        v = SuperState(state, id_team, id_player)
        a = Actions(state, id_team, id_player)

        if v.player.distance(v.ball) < PLAYER_RADIUS + BALL_RADIUS:
            if id_team == 1:
                if v.player.x < GAME_WIDTH * 2 / 8:
                    shoot = Vector2D(GAME_WIDTH * 4 / 8, GAME_HEIGHT / 2)
                    return SoccerAction(shoot=shoot.normalize() * 3)
                else:
                    if v.playeradverse.y < GAME_HEIGHT / 2:
                        shoot = Vector2D(GAME_WIDTH * 7.5 / 8,
                                         GAME_HEIGHT * 3.5 / 4) - v.player
                        return SoccerAction(shoot=shoot.normalize() * 100)
                    else:
                        shoot = Vector2D(GAME_WIDTH * 7.5 / 8,
                                         GAME_HEIGHT * 0.5 / 4) - v.player
                        return SoccerAction(shoot=shoot.normalize() * 100)
            else:
                if v.player.x > GAME_WIDTH * 6 / 8:
                    shoot = Vector2D(GAME_WIDTH * 4 / 8, GAME_HEIGHT / 2)
                    return SoccerAction(shoot=shoot.normalize() * 3)
                else:
                    if v.playeradverse.y > GAME_HEIGHT / 2:
                        shoot = Vector2D(GAME_WIDTH * 0.5 / 8,
                                         GAME_HEIGHT * 0.5 / 4) - v.player
                        return SoccerAction(shoot=shoot.normalize() * 100)
                    else:
                        shoot = Vector2D(GAME_WIDTH * 0.5 / 8,
                                         GAME_HEIGHT * 3.5 / 4) - v.player
                        return SoccerAction(shoot=shoot.normalize() * 100)
        else:
            if v.ballecampadverse == 0:
                if id_team == 1:
                    return a.deplacement(
                        Vector2D(GAME_WIDTH * 2 / 8, GAME_HEIGHT / 2))
                else:
                    return a.deplacement(
                        Vector2D(GAME_WIDTH * 6 / 8, GAME_HEIGHT / 2))
            else:
                return a.deplacement(v.ball)
Example #6
0
def calculate_returns(day_skip = 4000):

    starting_amount = 100_000
    start = '1970-01-02'
    end = '2019-12-31'
    dividend_dates = [4,7,10,12]
    capital_dates = [4, 12]
    dividend_tax = 0.15        
    capital_tax = 0.15           
    capital_annual_yield = 0.001 
    annual_fund_fees = 0.00015   

    drop_pct_threshold = 0.2
    rise_pct_threshold = 0.6
    buy_pct = 0.4
    sell_pct = 0.1
    data  = download_data()

    #Get backtesting data object
    d = Data_Handler(data, starting_amount, start, end, dividend_dates, capital_dates, dividend_tax,
                     capital_tax, capital_annual_yield, annual_fund_fees)

    #Create backtesting data object.
    clean_data = Strategies(d, drop_pct_threshold, rise_pct_threshold, buy_pct, sell_pct)

    return_dict_fi = {}
    return_dict_shbl = {}
    
    starting_amount = clean_data.data.starting_amount
    
    for i in tqdm(range(0,len(clean_data.data.df), day_skip)):
    
        temp_d = deepcopy(clean_data)
        
        new_start_date = temp_d.data.df.Date.iloc[i]
        temp_d.data.df = temp_d.data.df[temp_d.data.df['Date'] >= new_start_date].reset_index()
        temp_d.data.max_price = temp_d.data.min_price = temp_d.data.df.iloc[0]['Price']

        temp_d.sell_high_buy_low_strat()
        temp_d.fully_invested_strat()
        
        ending_value_fi = temp_d.data.df.tail(1)['fi_Value'].iloc[0]
        ending_value_shbl = temp_d.data.df.tail(1)['shbl_Value'].iloc[0]

        ending_date = temp_d.data.df.tail(1)['Date'].iloc[0]
        
        year_diff = (ending_date - new_start_date) / datetime.timedelta(days=365)
        
        annualized_return_fi = (ending_value_fi / starting_amount) **(1/year_diff) - 1
        annualized_return_shbl = (ending_value_shbl / starting_amount) **(1/year_diff) - 1
        
        return_dict_fi[str(new_start_date)[:10]] = annualized_return_fi
        return_dict_shbl[str(new_start_date)[:10]] = annualized_return_shbl
    
    return_data = {'Fully_invested': return_dict_fi, 'Sell_high_buy_low': return_dict_shbl}
    return_data = pd.DataFrame.from_dict(return_data)
    fi_mean = round(np.mean(return_data.Fully_invested),3)
    shbl_mean = round(np.mean(return_data.Sell_high_buy_low),3)    
    sns.boxplot(data=return_data).set_title("Box plot based upon {} different starting dates"\
                                                .format(len(return_data)))
    
    plt.legend(loc = 'upper right', labels=['FI: mean ' + str(fi_mean), 'SHBL: mean ' \
                                                    + str(shbl_mean)], prop={'size': 9})
      
    return return_data
Example #7
0
        elif (opt == 8):
            print('You made the best choice and didn\'t play\n')
            exit()

        # Roulette Settings
        roulette.configurePlayer()

        # Strategy Name selection from a Strategies' Names array
        allStrategies = [
            "exit", "number", "color", "sofovich", "martingale", "dalembert",
            "fibonacci", "sante", "noplay"
        ]
        stratName = allStrategies[opt]

        # Configuring strategy parameters
        strat = Strategies(roulette, stratName)
        print()

        # Arrays for multiple Game Results (Recommended: 5 to 10)
        results = 6
        resultsLimited = []
        resultsUnlimited = []

        # Simulating the Strategy
        for i in range(results):
            if (opt == 1): graphsLim, graphsUnlim = strat.betToNumber()
            elif (opt == 2):
                graphsLim, graphsUnlim = strat.betToColor()
            elif (opt == 3):
                graphsLim, graphsUnlim = strat.betAsSofovich()
            elif (opt == 4):
Example #8
0
    async def perform_strategy(self, iteration, strategy_num):
        self.mainAgent.clean_strike_force(
        )  # Clear dead units from strike force
        self.mainAgent.is_army_cached = False  # Must re obtain army data
        if self.mainAgent.predicted_enemy_position_num == -1:
            # Initializing things that are needed after game data is loaded

            # Prevent game from crashing
            hatchery = self.mainAgent.bases
            if hatchery == None or hatchery.amount == 0:
                return
            else:
                hatchery = self.mainAgent.bases.ready.random

            # Assume first position
            self.mainAgent.predicted_enemy_position = 0
            self.mainAgent.num_enemy_positions = len(
                self.mainAgent.enemy_start_locations)
            self.mainAgent.start_location = self.mainAgent.bases.ready.random.position  # Should only be 1 hatchery at this time
            self.mainAgent.map_width = self.mainAgent.game_info.map_size[0]
            self.mainAgent.map_height = self.mainAgent.game_info.map_size[1]

            # Get a point in the corner of the map
            p = lambda: None  # https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python
            p.x = self.mainAgent.game_info.map_center.x * 1.9
            p.y = self.mainAgent.game_info.map_center.y * 1.9
            self.mainAgent.map_corner = Point2.from_proto(p)

        # Make sure given strategy num is valid
        if Strategies.has_value(strategy_num):
            # Valid strategy num, convert int into enum value
            strategy = Strategies(strategy_num)

            # Mark strategy as changed or not
            if strategy != self.mainAgent.prev_strategy:
                self.mainAgent.log("New strategy is " + str(strategy))
                self.mainAgent.did_strategy_change = True
                self.mainAgent.strike_force = None
            else:
                self.mainAgent.did_strategy_change = False

            self.mainAgent.prev_strategy = strategy  # Prepare for next iteration
        else:
            self.log_error(f"Unknown strategy number {strategy_num}")
            return

        # Call the proper strategy function

        # Prevent game from crashing
        hatchery = self.mainAgent.bases
        if hatchery == None or hatchery.amount == 0:
            return
        else:
            hatchery = self.mainAgent.bases.ready.random

        # Attack
        if strategy == Strategies.HEAVY_ATTACK:
            await self.heavy_attack(iteration)
        elif strategy == Strategies.MEDIUM_ATTACK:
            await self.medium_attack(iteration)
        elif strategy == Strategies.LIGHT_ATTACK:
            await self.light_attack(iteration)

        # Scouting
        elif strategy == Strategies.HEAVY_SCOUTING:
            await self.heavy_scouting(iteration)
        elif strategy == Strategies.MEDIUM_SCOUTING:
            await self.medium_scouting(iteration)
        elif strategy == Strategies.LIGHT_SCOUTING:
            await self.light_scouting(iteration)

        # Defense
        elif strategy == Strategies.HEAVY_DEFENSE:
            await self.heavy_defense(iteration)
        elif strategy == Strategies.MEDIUM_DEFENSE:
            await self.medium_defense(iteration)
        elif strategy == Strategies.LIGHT_DEFENSE:
            await self.light_defense(iteration)

        # Harass
        elif strategy == Strategies.HEAVY_HARASS:
            await self.heavy_harass(iteration)
        elif strategy == Strategies.MEDIUM_HARASS:
            await self.medium_harass(iteration)
        elif strategy == Strategies.LIGHT_HARASS:
            await self.light_harass(iteration)

        # Unknown
        else:
            self.log("Unknown strategy was given: " + str(strategy))