Esempio n. 1
0
    def __init__(self, symbol, dates, start_val, verbose=False):
        # Initialize Genetic Algorithm
        self.POP_SIZE = 100
        self.DNA_SIZE = 8
        self.MAX_GENERATIONS = 500
        # Mutation probability = 1/mutation_chance
        self.mutation_chance = 100
        self.mutation_factor = 0.1
        self.population_replacement = 0.7
        self.best_population_replacement = 0.5

        self.verbose = verbose

        self.start_val = start_val
        self.symbol = symbol
        self.dates = dates
        self.fitness_dict = {}
        # Get data
        self.prices_df = util.get_data([symbol],
                                       pd.date_range(dates[0], dates[1]),
                                       addSPY=False).dropna()

        # Get Candlestick data
        self.df_aux = util.get_all_data(symbol, dates)
        self.ohlc = ind.get_ohlc(self.df_aux)
        self.patterns_signal, self.trends, self.points_signal, self.sma_signal, self.rsi_signal, self.macd_signal, self.bb_signal = self.get_signals(
            self.prices_df, self.ohlc)
    def testPolicy(self,
                   symbol,
                   dates=['2011-1-1', '2011-12-31'],
                   start_val=100000,
                   ga_train=False):
        #Test a trading policy for a stock wthin a date range and output a trades dataframe.

        # Get data
        prices_df = util.get_data([symbol],
                                  pd.date_range(dates[0], dates[1]),
                                  addSPY=False).dropna()

        # Get Candlestick data
        df_aux = util.get_all_data(symbol, dates)
        ohlc = ind.get_ohlc(df_aux)

        #Generate order signals
        order_signals = self.trade_strategy(prices_df, ohlc, ga_train)

        # Remove 0 signals
        order_signals = order_signals[order_signals != 0.0]

        # Create trades dataframe
        trades = []
        # Double-Down and Double-Up is Active
        position = 0
        for date in order_signals.index:
            if order_signals.loc[date].values == 1:
                # Buy Order
                if position == 0:
                    trades.append((date, symbol, "BUY", 1000))
                    position = 1
                elif position == -1:
                    # Double-Up
                    trades.append((date, symbol, "BUY", 2000))
                    position = 1
            elif order_signals.loc[date].values == -1:
                # Sell Order
                if position == 0:
                    trades.append((date, symbol, "SELL", 1000))
                    position = -1
                elif position == 1:
                    # Double-Down
                    trades.append((date, symbol, "SELL", 2000))
                    position = -1
            if date == order_signals.index[-1]:
                # Last day, close open positions
                last_trade = trades[-1]
                trades[-1] = (last_trade[0], last_trade[1], last_trade[2],
                              last_trade[3] - 1000)
                position = 0

        self.df_trades = pd.DataFrame(
            trades, columns=['Date', 'Symbol', 'Order', 'Shares'])
        self.df_trades.set_index('Date', inplace=True)

        #pdb.set_trace()

        return self.df_trades
Esempio n. 3
0
                    # Search for Morning Star patterns
                    found, signal = is_morning_star_doji(ohlc[i-1], row, ohlc[i+1])
                    if found:
                        found_signals.append([mdates.num2date(ohlc[i+1][date]), signal])
                if "Abandoned Baby" in patterns:
                    # Search for Abandoned baby patterns
                    found, signal = is_abandoned_baby(ohlc[i-1], row, ohlc[i+1])
                    if found:
                        found_signals.append([mdates.num2date(ohlc[i+1][date]), signal])
                        
            # Search for 2 candle patterns
            if "Harami Cross" in patterns:
                # Search for Harumi Cross patterns
                found, signal = is_harami_cross(row, ohlc[i+1])
                if found:
                    #pdb.set_trace()
                    found_signals.append([mdates.num2date(ohlc[i+1][date]), signal])
    return found_signals
                
if __name__ == "__main__":
    symbols = ['SPY','AAPL', 'GOOG', 'IBM', 'XOM']
    obs_dates = ['2011-03-01','2011-04-01']
    symbol = "GOOG"
    df_aapl = util.get_all_data(symbol, obs_dates)
    ohlc = ind.get_ohlc(df_aapl)
    for i, row in enumerate(ohlc[:-1]):
        if is_harami_cross(row, ohlc[i+1])[0]:
            print ("Found Harami Cross!")
            print (mdates.num2date(row[0]), row[1:])
            print (mdates.num2date(ohlc[i+1][0]), ohlc[i+1][1:])
    #pdb.set_trace()
Esempio n. 4
0
    split_date = df.index[pos]

    # Use GeneticAlgorithm to optimize signal weights
    params = False
    gen_alg = ga.GeneticAlgorithm(symbol=symbol,
                                  dates=[dates[0], split_date],
                                  start_val=start_val,
                                  verbose=True)
    params, sharpe_ratio = gen_alg.start_ga()

    #pdb.set_trace()

    ft = FakeTicker(symbol, df, testing_pctg)
    #print (ft.get_training_data().shape)
    prices_df = ft.get_training_data()['Adj Close']
    ohlc = ind.get_ohlc(ft.get_training_data())

    trades = []
    ctr = 0
    while not ft.is_end_ticker():
        start = time.time()
        # Get tick data
        ticker_data = ft.get_ticker_data()

        # Add new ticker to training data
        new_index = prices_df.index.insert(len(prices_df), ticker_data.name)
        prices_df = np.append(prices_df.values.flatten(),
                              ticker_data['Adj Close'])
        prices_df = pd.DataFrame(prices_df, index=new_index, columns=[symbol])

        # Add new OHLC to ohlc array