def __init__(self, start_date, end_date, initial_position, market, params, h5file=None):
     Strategy.__init__(self, start_date, end_date, initial_position, market, params, h5file)
     for symbol in initial_position.keys():
         if symbol == "$":
             continue
         self.addIndicator(symbol, "value", SimpleValue())
         self.addSpecificIndicator(symbol, "peak", PeakTrough())
         date = getPrevTradingDay(market, start_date, symbol)
         #date = getNextTradingDay(start_date, symbol)
         self.peakDate = date
         self.troughDate = date
         ticker = market[symbol]
         if ticker[date] == None:
             self.max_value = 0
             self.min_value = 1000
         else:
             self.max_value = ticker[date].adjhigh
             self.min_value = ticker[date].adjlow
         self.updateSpecificIndicator(symbol, 'peak', start_date, (self.max_value, 1))
     self.updateIndicators(start_date)
     self.win_point = params['win']
     self.loss_point = params['loss']
     self.low_to_high = 0
     self.high_to_low = 0
     self.upTrend = 0
     self.downTrend = 0
Exemple #2
0
def CreateString(n, k):
    initialValue = 'A' * n
    char_list = list(initialValue)
    h = Strategy(k)
    candidates = SortedListWithKey(key=h.evaluate_node)
    candidates.add(char_list)

    altura = 0
    while altura < k+1:
        try:
            candidate = candidates.pop(0)
            punctuation = h.evaluate_node(candidate)
            if punctuation == 0:
                return ''.join(candidate)

            l = expand(candidate)
            for expanded in l:
                punctuation = h.evaluate_node(expanded)
                if punctuation >= 0:
                    candidates.add(expanded)

            altura += 1
        except IndexError:
            return ''
    return ''
 def __init__(self, start_date, end_date, initial_position, market, params, h5file=None):
     Strategy.__init__(self, start_date, end_date, initial_position, market, params, h5file)
     during = params['during']
     self.history = [1000.0 for x in xrange(during+1)]
     for symbol in initial_position.keys():
         if symbol == "$":
             continue
         self.addIndicator(symbol, "value", SimpleValue())
         try:
             short = params['short']
         except KeyError:
             short = Trending.DEF_SHORT_DAYS
         self.addIndicator(symbol, "short", EMA(short)) 
         try:
             long_ = params['long']
         except KeyError:
             long_ = Trending.DEF_LONG_DAYS
         self.addIndicator(symbol, "long", EMA(long_))
     try:
         backfill = params['backfill']
     except KeyError:
         backfill = long_
     d = start_date - (backfill * ONE_DAY)
     self.updateIndicators(d, start_date)
     self.win_point = params['win']
     self.loss_point = params['loss']
Exemple #4
0
def test_precompute():
    ticks = load_ticks('dc', 'pp', 2015, range(9,10), use_cache=True)
    
    s = Strategy(ticks, 3.75, show_freq=None)
    ind = PivotProfile(s, 5*60*2, int(1 * 3.75 * 60 * 60 * 2))
    t0 = time.time()
    ind.precompute()
    t1 = time.time()
    print 't_precompute =', t1 - t0, 'sec'
    
    s.add_indicator(ind)
    t0 = time.time()
    s.run()
    t1 = time.time()
    print 't =', t1 - t0, 'sec'
    
    s2 = Strategy(ticks, 3.75, show_freq=None)
    ind2 = PivotProfile(s2, 5*60*2, int(1 * 3.75 * 60 * 60 * 2))
    s2.add_indicator(ind2)
    t0 = time.time()
    s2.run()
    t1 = time.time()
    print 't =', t1 - t0, 'sec'
    
    sal = ind.saliency[0][ind.saliency[3]:-ind.saliency[3]]
    sal2 = ind2.saliency[0][ind2.saliency[3]:-ind2.saliency[3]]
    print np.abs(sal - sal2).mean(), np.abs(sal - sal2).max(), np.abs(sal).mean()
 def __init__(self, start_date, end_date, initial_position, market, params, h5file=None):
     Strategy.__init__(self, start_date, end_date, initial_position, market, params, h5file)
     self.diff = {}
     for symbol in initial_position.keys():
         if symbol == "$":
             continue
         self.diff[symbol] = [0.0]
         self.addIndicator(symbol, "value", SimpleValue())
         try:
             period = params['period']
         except KeyError:
             period = averageSystem.DEF_PERIOD
         self.addIndicator(symbol, "MA", SMA(period))
         try:
             short = params['short']
         except KeyError:
             short = Trending.DEF_SHORT_DAYS
         self.addIndicator(symbol, "short", EMA(short)) 
         try:
             long_ = params['long']
         except KeyError:
             long_ = Trending.DEF_LONG_DAYS
         self.addIndicator(symbol, "long", EMA(long_))
     try:
         backfill = params['backfill']
     except KeyError:
         backfill = period
     d = start_date - (backfill * ONE_DAY)
     self.updateIndicators(d, start_date)
     self.win_point = params['win']
     self.loss_point = params['loss']
     self.pre = 0
    def __init__(self, start_date, end_date, initial_position, market, params, h5file=None):
        Strategy.__init__(self, start_date, end_date, initial_position, market, params, h5file)
        self.diff = {}
        for symbol in initial_position.keys():
            if symbol == "$":
                continue
	    self.diff[symbol] = [0.0]
            self.addIndicator(symbol, "value", SimpleValue()) 
            try:
                short = params['short']
            except KeyError:
                short = Trending.DEF_SHORT_DAYS
            self.addIndicator(symbol, "short", EMA(short)) 
            try:
                long_ = params['long']
            except KeyError:
                long_ = Trending.DEF_LONG_DAYS
            self.addIndicator(symbol, "long", EMA(long_))
            '''
            try:
                rsi = params['rsi']
            except KeyError:
                rsi = Trending.DEF_RSI_PERIOD
            self.addIndicator(symbol, "rsi", RSI(rsi))
            '''

        # Backfill the indicators 
        try:
            backfill = params['backfill']
        except KeyError:
            backfill = long_

        d = start_date - (backfill * ONE_DAY)
        self.updateIndicators(d, start_date)
	def __init__(self, settings, watchlist, trademanager):
		Strategy.__init__(self, watchlist, trademanager)
		self.minprice = settings.getfloat("Strategy", "minprice")
		self.minvolume = settings.getfloat("Strategy", "minvolume")
		self.fastma = settings.getint("Strategy", "fastma")
		self.slowma = settings.getint("Strategy", "slowma")
		self.atrStop = self._getfloatsetting(settings, "Strategy", "atrStop")
		self.percentStop = self._getfloatsetting(settings, "Strategy", "percentStop")
	def __init__(self, settings, watchlist, tradeManager):
		Strategy.__init__(self, watchlist, tradeManager)
		
		self.minprice = settings.getfloat("Strategy", "minprice")
		self.minvolume = settings.getint("Strategy", "minvolume")
		self.mingap = settings.getfloat("Strategy", "mingap")
		self.dailysmatrendfilter = self._getintsetting(settings,"Strategy", "dailysmatrendfilter")
		self.target = self._getfloatsetting(settings, "Strategy", "target")
		self.minhour = settings.getint("Strategy", "minhour")
		self.maxhour = settings.getint("Strategy", "maxhour")
		self.donchianstop = settings.getint("Strategy", "donchianstop")
class TestStrategy(unittest.TestCase):
    def setUp(self):
        self.problem = Problem()
        self.strategy = Strategy()

    def test_execute(self):
        try:
            self.strategy.execute(self.problem)
        except UndefinedError:
            pass
        else:
            self.fail('Did not see UndefinedError')
	def __init__(self, settings, watchlist, tradeManager):
		Strategy.__init__(self, watchlist, tradeManager)
		self.minprice = settings.getfloat("Strategy", "minprice")
		self.timescale = settings.getint("Strategy", "timescale")
		self.period = settings.getint("Strategy", "period")
		self.bandwidth = settings.getfloat("Strategy", "bandwidth")
		self.bandStop = self._getfloatsetting(settings, "Strategy", "bandStop")
		self.percentStop = self._getfloatsetting(settings, "Strategy","percentStop")
		self.sma = self._getintsetting(settings, "Strategy", "smafilter")
		self.exitAtOtherBand = self._getboolsetting(settings, "Strategy", "exitAtOtherBand")
		self.doLong = self._getboolsetting(settings, "Strategy", "doLong")
		self.doShort = self._getboolsetting(settings, "Strategy", "doShort")
Exemple #11
0
def test_macd():
    ticks = load_ticks('dc', 'pp', 2015, range(9,10), use_cache=True)
    s = Strategy('pp09_macd', ticks, 3.75)
    
    inds = [MACD(s, 1*60*2, 5*60*2, standardized=False, escape_opening=1),
            MACD(s, 2*60*2, 10*60*2, standardized=False, escape_opening=1),
            MACD(s, 10*60*2, 60*60*2, standardized=False, escape_opening=0)
            ]
    
    for ind in inds:
        s.add_indicator(ind)
    
    s.run()
Exemple #12
0
class Trader(object):
  '''
  '''
  last_id = -1  
  @classmethod
  def new_id(cls):
    cls.last_id = cls.last_id + 1
    return cls.last_id
  
  def __init__(self, datafeed, broker, opening_bal, instrument, strategy, start_date, end_date):
    '''
    '''    
    self.id = Trader.new_id()
    
    self.instrument = instrument    
    self.start_date = start_date
    self.end_date = end_date        
    self.datafeed = datafeed

    self.opening_bal = opening_bal
    
    self.broker = broker    
    self.orderQ = None
    self.receiptQ = None
    self.term_req_Q = None
    self.term_notice_Q = None    
    self.broker.register_trader(self)
    
    self.order_receipts = []
    self.load_strategy()    

  def load_strategy(self):
    '''
    called by simulator
    '''
    self.strategy = Strategy(self, self.instrument, self.start_date, self.end_date)  
  def submit_order(self, order):
    '''
    submit order to broker for execution
    place on orderQ
    '''    
    order.trader_id = self.id
    self.orderQ.put(order)
  def execute_strategy(self, date):
    '''
    called by simulator
    '''
    self.strategy.execute(date)
Exemple #13
0
	def processOfferQuery(self, aQueryInConstruction):
		sStrategy = aQueryInConstruction.sStrategy
		try:
			aStrategy = next(sc for sc in Strategy.__subclasses__() if sc.strategyName() == aQueryInConstruction.sStrategy)
			aQueryInConstruction.strategy = aStrategy()
		except Exception:
			raise IllegalStrategy(aQueryInConstruction.sStrategy)
		return aQueryInConstruction
Exemple #14
0
def test_output(year=2015, month_range=range(1, 13), name=''):
    for exchange, commodity, tick_size, hours_per_day in futures:
        ticks = load_ticks(exchange, commodity, year, month_range)   
        name = base_dir+commodity+str(year%100)+str(month_range[0]).zfill(2)+'-'+str(year%100)+str(month_range[-1]).zfill(2)+'_pivot'+name
        s = Strategy(name, ticks, tick_size, hours_per_day, save_freq=10)#, show_freq=10)
    #    ind_xs = SRProfile(s, 0.5*60*2, int(30*60*2))
        ind_s = PivotProfile(s, 5*60*2, int(1 * hours_per_day * 60 * 60 * 2 * 1.5))
        ind_m = PivotProfile(s, 30*60*2, int(5 * hours_per_day * 60 * 60 * 2 * 1.5))
        for ind in [
                    ind_m,
                    ind_s, 
    #                ind_xs,
                    ]:
            ind.precompute()
            s.add_indicator(ind)
        s.run()
    return s
Exemple #15
0
def mill(traj, z_start=0, z_stop=None, z_step = 1, FF=3000, FZ=200, options=None):
    'вырезаем траекторию'
    from strategy import Strategy
    from tool import Tool
    cut = Strategy()
    t = Tool()
    t.F = FF
    t.FZ = FZ
    #берем опции
    xx = get_option(options, 'x', 0)
    yy = get_option(options, 'y', 0)
    sc = get_option(options, 'scale', 1)
    ang = get_option(options, 'angle', 0)

    if z_stop == None: #просто один слой там, где скажут
        cut.mill(traj, tool=t, x=xx, y=yy, scale=sc, angle=ang, options=options)
        return

    opt = options.copy()
    z = z_start
    while z >= z_stop:
        opt['z'] = z
        cut.mill(traj, tool=t, x=xx, y=yy, scale=sc, angle=ang, options=opt)        
        z -= z_step

    if z + z_step > z_stop: #дорезаем остатки
        opt['z'] = z_stop
        cut.mill(traj, tool=t, x=xx, y=yy, scale=sc, angle=ang, options=opt)        
Exemple #16
0
 def strategies(self):
   cherrypy.response.headers["Content-Type"] =  "text/plain"
   subclasses = Strategy.__subclasses__()
   subclassNameList = [] 
   	
   for aSubclass in subclasses:
       subclassNameList.append(aSubclass.strategyName())
   	
   return json.dumps(subclassNameList, ensure_ascii=False)
Exemple #17
0
def test_output(year=2016, month_range=range(1, 6), exp_name=''):
    for exchange, commodity, tick_size, hours_per_day in futures:
        ticks = load_ticks(exchange, commodity, year, month_range)   
        name = base_dir+commodity+str(year%100)+str(month_range[0]).zfill(2)+'-'+str(year%100)+str(month_range[-1]).zfill(2)+'_common'+exp_name
        s = Strategy(name, ticks, tick_size, hours_per_day, save_freq=10)#, show_freq=10)
        inds = [
#            MACD(s, 10, 1*60*2, escape_opening=0),
#            MACD(s, 10, 5*60*2, escape_opening=0),
#            MACD(s, 1*60*2, 10*60*2, escape_opening=0),
#            MACD(s, 5*60*2, 30*60*2, escape_opening=0),
#            MACD(s, 5*60*2, 60*60*2, escape_opening=0),
#            MACD(s, 5*60*2, 120*60*2, escape_opening=0),
#            MACD(s, 5*60*2, 240*60*2, escape_opening=0),
#            MA(s, 5*2),
#            MA(s, 1*60*2),
#            MA(s, 5*60*2),
#            MA(s, 10*60*2),
#            MA(s, 30*60*2),
#            MA(s, 60*60*2),
#            MA(s, 120*60*2),
#            MA(s, 240*60*2),
            PastXtrm(s, 5*60*2),
            PastXtrm(s, 10*60*2),
            PastXtrm(s, 30*60*2),
            PastXtrm(s, 60*60*2),
            PastXtrm(s, 120*60*2),
            PastXtrm(s, 240*60*2),
            FutureXtrm(s, 5*60*2),
            FutureXtrm(s, 10*60*2),
            FutureXtrm(s, 30*60*2),
            FutureXtrm(s, 60*60*2),
            FutureXtrm(s, 120*60*2),
            FutureXtrm(s, 240*60*2),
            TimeInfo(s)
            ]
        for ind in inds:
            s.add_indicator(ind)
        print 'Running', name
        with Timer() as t:
            s.run()
        print 'Run took %f sec.' % t.interval
    return s
 def make_move(self, x=None, y=None):
     Player.make_move(self, x, y)
     # Calculate move
     liberties = Game.liberties(self.player, self.state)
     #def apply_strat(strategy, mult=1, heur=None):
     #    return strategy.apply(self.player, self.state, liberties, mult, heuristic=heur)
     heur = None
     for strat, mult in self.strats:
         heur = strat.apply(self.player, self.state, liberties, mult, heur)
     x, y = Strategy.run(heur)
     self.game.move(x, y)
Exemple #19
0
class Agent:
    POPULATION_SIZE = 15
    SIGMA = 0.5
    LEARNING_RATE = 0.3

    def __init__(self, model, timeseries, skip, initial_money, real_trend,
                 minmax):
        self.model = model
        self.timeseries = timeseries
        self.skip = skip
        self.real_trend = real_trend
        self.initial_money = initial_money
        self.es = Strategy(
            self.model.get_weights(),
            self.get_reward,
            self.POPULATION_SIZE,
            self.SIGMA,
            self.LEARNING_RATE,
        )
        self.minmax = minmax
        self._initiate()

    def _initiate(self):
        # i assume first index is the close value
        self.trend = self.timeseries[0]
        self._mean = np.mean(self.trend)
        self._std = np.std(self.trend)
        self._inventory = []
        self._capital = self.initial_money
        self._queue = []
        self._scaled_capital = self.minmax.transform([[self._capital, 2]])[0,
                                                                           0]

    def reset_capital(self, capital):
        if capital:
            self._capital = capital
        self._scaled_capital = self.minmax.transform([[self._capital, 2]])[0,
                                                                           0]
        self._queue = []
        self._inventory = []

    def change_data(self, timeseries, skip, initial_money, real_trend, minmax):
        self.timeseries = timeseries
        self.skip = skip
        self.initial_money = initial_money
        self.real_trend = real_trend
        self.minmax = minmax
        self._initiate()

    def act(self, sequence):
        decision = self.model.predict(np.array(sequence))

        return np.argmax(decision[0])

    def act_softmax(self, sequence):
        decision = self.model.predict(np.array(sequence))

        return np.argmax(decision[0]), softmax(decision)[0]

    def get_state(self, t, inventory, capital, timeseries):
        state = get_state(timeseries, t)
        len_inventory = len(inventory)
        if len_inventory:
            mean_inventory = np.mean(inventory)
        else:
            mean_inventory = 0
        z_inventory = (mean_inventory - self._mean) / self._std
        z_capital = (capital - self._mean) / self._std
        concat_parameters = np.concatenate(
            [state, [[len_inventory, z_inventory, z_capital]]], axis=1)
        return concat_parameters

    def get_reward(self, weights):
        initial_money = self._scaled_capital
        starting_money = initial_money
        invests = []
        self.model.weights = weights
        inventory = []
        state = self.get_state(0, inventory, starting_money, self.timeseries)

        for t in range(0, len(self.trend) - 1, self.skip):
            action = self.act(state)
            if action == 1 and starting_money >= self.trend[t]:
                inventory.append(self.trend[t])
                starting_money -= self.trend[t]

            elif action == 2 and len(inventory):
                bought_price = inventory.pop(0)
                starting_money += self.trend[t]
                invest = ((self.trend[t] - bought_price) / bought_price) * 100
                invests.append(invest)

            state = self.get_state(t + 1, inventory, starting_money,
                                   self.timeseries)
        invests = np.mean(invests)
        if np.isnan(invests):
            invests = 0
        score = (starting_money - initial_money) / initial_money * 100
        return invests * 0.7 + score * 0.3

    def fit(self, iterations, checkpoint):
        self.es.train(iterations, print_every=checkpoint)

    def buy(self):

        initial_money = self._scaled_capital
        starting_money = initial_money
        inventory = bitmex_back.get_position('XBTUSD')
        state = self.get_state(0, inventory, starting_money, self.timeseries)
        fees = 0
        states_sell = 0
        states_buy = 0

        for t in range(0, len(self.trend) - 1, self.skip):
            action, prob = self.act_softmax(state)
            print(t, prob)

            if action == 1 and starting_money >= self.trend[t] and t < (
                    len(self.trend) - 1 - window_size):
                bitmex_back.place_order(price=self.real_trend[t],
                                        type="Market",
                                        qty=1,
                                        stopPx=self.real_trend[t] * 1.03)
                updated_balance = [i['walletBalance']
                                   for i in balances[-1]][-1]
                timestamp = [i['timestamp'] for i in balances[-1]][-1]
                fee_for_trade = [i['fee'] for i in balances[-1]][-1]
                fees += fee_for_trade
                states_buy += 1
                print('day %d: buy 1 unit at price %f, total balance %f' %
                      (timestamp, self.real_trend[t], updated_balance))

            elif action == 2 and len(inventory):
                bitmex_back.place_order(price=self.real_trend[t],
                                        type="Market",
                                        qty=-1,
                                        stopPx=self.real_trend[t] * 0.97)
                updated_balance = [i['walletBalance']
                                   for i in balances[-1]][-1]
                investment_updated = [i['unrealizedPnL'] for i in balances[-1]]
                investment = investment_updated[0]
                timestamp = [i['timestamp'] for i in balances[-1]][-1]
                fee_for_trade = [i['fee'] for i in balances[-1]][-1]
                fees += fee_for_trade
                states_sell += 1

                print(
                    'day %d, sell 1 unit at price %f, investment %f %%, total balance %f,'
                    % (timestamp, self.real_trend[t], investment,
                       updated_balance))
            state = self.get_state(t + 1, inventory, starting_money,
                                   self.timeseries)
        unrealized_gains = [i['unrealizedPnL'] for i in balances[-1]][-1]
        realized_gains = [i['realizedPnL'] for i in balances[-1]][-1]

        total_gains = unrealized_gains + realized_gains - fees
        return states_buy, states_sell, total_gains, fees
Exemple #20
0
 def __init__(self, search_order="DLRU"):
     search_order = search_order[::-1]
     Strategy.__init__(self, search_order=search_order)
Exemple #21
0
from strategy import Strategy, BLACK, WHITE
from OthelloStrategy5_padusuma import OthelloStrategy
ai = Strategy()
ai2 = OthelloStrategy()

from Othello_Core import *
core = OthelloCore()

import random
import time
#############################################################
# client.py
# a simple othello client
# plays 2 strategies against each other and keeps score
# imports strategies from "strategies.py" as ai
# rest of functionality is stored in core.py
#
# SRINIDHI KRISHNAN
############################################################

B_STRATEGY = ai.human_strategy()
W_STRATEGY = ai.minimax_strategy(6)
ROUNDS = 10
SILENT = False

# see core.py for constants: MAX, MIN, TIE


def play(strategy_b, strategy_w, first=BLACK, silent=True):
    """
    Plays strategy_b vs. strategy_w, beginning with first
 def __init__(self):
     '''
     Constructor
     '''
     Strategy.__init__(self)
Exemple #23
0
 def __init__(self, strategy=Strategy()):
     self._strategy = strategy
Exemple #24
0
    def test_stream_price(self):
        s = Strategy(start_amount=1000, sl=0.02, tpmulti=2)
        p1 = Price([datetime(2015, 12, 31, 12, 00), 10])
        s.stream_price(p1)

        self.assertEqual(len(s.trades), 1)
        # Remaining amount comes by subtracting first transaction total amount.
        self.assertEqual(s.status['remaining_amount'], 900)
        self.assertEqual(s.status['open_trades_count'], 1)

        trx1 = s.trades[0]
        self.assertEqual(trx1.get('entry_amount'), 100)
        self.assertEqual(trx1.get('stop_loss_price'), 8)
        self.assertEqual(trx1.get('take_profit_price'), 14)

        # Balance count should be equal to transactions count.
        self.assertEqual(len(s.balances), len(s.trades))
        self.assertTrue(isinstance(s.balances[0][0], datetime))

        ##
        # Add second price tick.
        ##
        p2 = Price([datetime(2015, 12, 31, 12, 30), 12])
        s.stream_price(p2)

        # Remaining amount comes by subtracting first transaction total amount.
        self.assertEqual(s.status['remaining_amount'], 780)
        self.assertEqual(s.status['open_trades_count'], 2)

        # Last record of balance should be updated.
        self.assertEqual(s.current_price.get('value'), 12)
        self.assertEqual(len(s.balances), len(s.trades))
        self.assertEqual(s.balances[-1][1], 1020)

        ##
        # Add third price
        ##
        p3 = Price([datetime(2015, 12, 31, 13, 00), 14])
        s.stream_price(p3)

        # Remaining amount comes by subtracting first transaction total amount.
        self.assertEqual(s.status['remaining_amount'], 780)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 1)

        # Last record of balance should be updated.
        self.assertEqual(s.current_price.get('value'), 14)
        self.assertEqual(len(s.balances), len(s.trades))
        self.assertEqual(s.balances[-1][1], 1060)

        
        ##
        # Add fourth price
        ##
        p4 = Price([datetime(2015, 12, 31, 13, 30), 16])
        s.stream_price(p4)

        self.assertEqual(s.status['remaining_amount'], 780)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 2)
        self.assertEqual(s.current_price.get('value'), 16)
        self.assertEqual(len(s.balances), len(s.trades))
        self.assertEqual(s.balances[-1][1], 1100)

        # Add 10 more prices with the same price. No more than 10
        # positions should be opened, because of insufficient money.
        pdate = datetime(2015, 12, 31, 13, 30)
        for i in range(10):
            min_30 = timedelta(minutes=30)
            pdate = pdate + min_30
            p = Price([pdate, 16])
            s.stream_price(p)

        self.assertEqual(s.status['remaining_amount'], 140)
        self.assertEqual(s.status['open_trades_count'], 6)
        self.assertEqual(s.status['closed_trades_count'], 2)
        self.assertEqual(s.current_price.get('value'), 16)
        self.assertEqual(len(s.balances), 14)
        self.assertEqual(s.balances[-1][1], 1100)

        # Create decreasing more prices with constantly decreasing prices 
        # calculate the result of trading.
        p15 = Price([pdate + timedelta(minutes=30), 15])
        s.stream_price(p15)
        self.assertEqual(s.status['remaining_amount'], 140)
        self.assertEqual(s.status['open_trades_count'], 6)
        self.assertEqual(s.status['closed_trades_count'], 2)
        self.assertEqual(len(s.balances), 15)
        self.assertEqual(s.balances[-1][1], 1040)

        p16 = Price([pdate + timedelta(minutes=30), 14])
        s.stream_price(p16)
        self.assertEqual(s.status['remaining_amount'], 700)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 7)
        self.assertEqual(len(s.balances), 16)
        self.assertEqual(s.balances[-1][1], 980)

        p17 = Price([pdate + timedelta(minutes=30), 13])
        s.stream_price(p17)
        self.assertEqual(s.status['remaining_amount'], 570)
        self.assertEqual(s.status['open_trades_count'], 3)
        self.assertEqual(s.status['closed_trades_count'], 7)
        self.assertEqual(len(s.balances), 17)
        self.assertEqual(s.balances[-1][1], 960)


        p18 = Price([pdate + timedelta(minutes=30), 12])
        s.stream_price(p18)
        self.assertEqual(s.status['remaining_amount'], 690)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 9)
        self.assertEqual(len(s.balances), 18)
        self.assertEqual(s.balances[-1][1], 930)

        p19 = Price([pdate + timedelta(minutes=30), 11])
        s.stream_price(p19)
        self.assertEqual(s.status['remaining_amount'], 690)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 10)
        self.assertEqual(len(s.balances), 19)
        self.assertEqual(s.balances[-1][1], 910)

        p20 = Price([pdate + timedelta(minutes=30), 10])
        s.stream_price(p20)
        self.assertEqual(s.status['remaining_amount'], 690)
        self.assertEqual(s.status['open_trades_count'], 2)
        self.assertEqual(s.status['closed_trades_count'], 11)
        self.assertEqual(len(s.balances), 20)
        self.assertEqual(s.balances[-1][1], 890)

        # Test stats calculation.
        self.assertEqual(s.stats['trades_count'], 13)
        self.assertEqual(s.stats['positive_count'], 2)
        self.assertEqual(s.stats['negative_count'], 9)
        self.assertEqual(s.stats['balance_highest'], 1100)
        self.assertEqual(s.stats['balance_lowest'], 890)
        self.assertEqual(s.stats['positive_max_in_row'], 2)
        self.assertEqual(s.stats['negative_max_in_row'], 9)
Exemple #25
0
 def __traverse_files(self):
     count = 0
     for root, directories, files in walk(self.__source_directory):
         for filename in files:
             file_dir = join(root, filename)
             __strat = Strategy(file_dir, self.__destination_directory)
Exemple #26
0
        #output = backTest.resample("1Min")
        #exit()

        #GROUP RESAMPLE TO PICKLE
        #groupResample(2015, 1, 6, "1H", "EUR_USD")
        #exit()

        # READ PICKLE INTO DATAFRAME (prices)
        #backtest =  Backtest("historical/EUR_USD_Week3.csv_1Min-OHLC.pkl",backtestSettings,leverage,closeDictionary,backtestSettings['positions'])
        backtest = Backtest("historical/EUR_USD_2015_1_through_12.pkl",
                            backtestSettings, leverage, backtestPositions)
        #backtest =  Backtest("historical/EUR_USD_2015_1_through_12.pkl",backtestSettings,leverage,closeDictionary,backtestSettings['positions'])
        prices = backtest.readPickle()

        # INSTANTIATE STRATEGY
        strategy = Strategy(backtestPositions, priceQueue, backtestSettings,
                            strategySettings)

        # LOOP THROUGH PRICES
        i = 0  # for displaying trades in a scatterplot
        for index, row in prices:

            # SKIP ERRORS IN PICKLE
            if np.isnan(row['Buy']) or np.isnan(row['Sell']):
                continue

            # 0.A: ADD CURRENT PRICE TO QUEUE
            priceQueue = strategy.doQueue(
                priceQueue, strategySettings["queuePeriod"],
                row)  # add current price to queue, along with stats
            longQueue = strategy.doQueue(
                longQueue, strategySettings["longQueuePeriod"],
Exemple #27
0
            next_group.append(Individual(st=Strategy(sim_code=new_bro)))
            next_group.append(Individual(st=Strategy(sim_code=new_sis)))
    print()
    return next_group


# 生成初始群体
group = []
for group_index in range(group_size):
    # 生成随机代码
    gene_list = []
    for gene_index in range(gene_size):
        gene_list.append(str(random.randint(0, 6)))
    sim_code = "".join(gene_list)
    group.append(Individual(st=Strategy(sim_code=sim_code)))

for evo_num in range(evo_time):
    print("evolution----------", evo_num)
    group = genetic_algorithm(group)

for ele in group:
    gl = []
    for i in range(10000):
        b_map = Map(max_x=10, max_y=10, bean_rate=0.5, wall_rate=0).inner_map
        for j in range(action_time):
            ele.movement(bean_map=b_map)
        gl.append(ele.goal)
        ele.goal = 0
    ans = sum(gl) // len(gl)
    ele.goal = ans
Exemple #28
0
def genetic_algorithm(bef_group):
    # 执行任务并计算适应度
    for individual in bef_group:
        goal_list = []
        for exec_num in range(exec_time):
            goal_list.append(cal_adaptability(individual, action_time))
            individual.goal = 0
        adaptability = sum(goal_list) // len(goal_list)
        individual.goal = adaptability
        # print("one's goal:", individual.goal)
    bef_group.sort(key=lambda x: x.goal, reverse=True)

    sample = list(map(lambda x: x.goal, bef_group))
    print(sample)
    print("均值:",
          sum(sample) // len(sample), "最大值:", max(sample), "最小值", min(sample))
    print("顶端策略:", end="")
    bef_group[0].st.print_sim_table()

    # 进化
    selector = []
    next_group = []
    for group_i in range(group_size):
        for curr_num in range(max([group_size - group_i - p_size, 1])):
            selector.append(group_i)

    # print(selector)

    while len(next_group) < group_size:
        father = random.randint(0, len(selector) - 1)
        mother = random.randint(0, len(selector) - 1)
        father = selector[father]
        mother = selector[mother]
        if father == mother:
            continue
        else:
            cut_p = random.randint(1, gene_size - 1)
            f_x = bef_group[father].get_sub_x(cut_p)
            f_y = bef_group[father].get_sub_y(cut_p)
            m_x = bef_group[mother].get_sub_x(cut_p)
            m_y = bef_group[mother].get_sub_y(cut_p)
            new_bro = f_x + m_y
            new_sis = m_x + f_y
            # 变异
            new_bro_list = list(new_bro)
            for gene_i in range(gene_size):
                if random.random() < mutation_prob:

                    print("!", end="")

                    random_num = random.randint(0, 6)
                    while random_num == new_bro_list[gene_i]:
                        random_num = random.randint(0, 6)
                    new_bro_list[gene_i] = str(random_num)
            new_bro = "".join(new_bro_list)

            new_sis_list = list(new_sis)
            for gene_i in range(gene_size):
                if random.random() < mutation_prob:

                    print("!", end="")

                    random_num = random.randint(0, 6)
                    while random_num == new_sis_list[gene_i]:
                        random_num = random.randint(0, 6)
                    new_sis_list[gene_i] = str(random_num)
            new_sis = "".join(new_sis_list)

            next_group.append(Individual(st=Strategy(sim_code=new_bro)))
            next_group.append(Individual(st=Strategy(sim_code=new_sis)))
    print()
    return next_group
Exemple #29
0
    kwargs = {
        'start': start_date,
        'end': end_date,
        'initialize': initialize,
        'handle_data': handle_data,
        'analyze': analyze,
        'before_trading_start': before_trading_start,
        'after_trading_end': after_trading_end,
        'bundle': 'quandl',
        'capital_base': config.get('capital_base'),
        'algo_name': config.get('name'),
        'algo_id': config.get('id'),
        'benchmark_symbol': config.get('benchmark_symbol')
    }

    if args.live_mode == 'True':
        if os.path.exists('test.state'):
            os.remove('test.state')
        print("Running in live mode.")
        kwargs['tws_uri'] = 'localhost:7497:1232'
        kwargs['live_trading'] = True
    else:
        kwargs['live_trading'] = False

    strategy = Strategy(kwargs)
    strategy.run_algorithm()

    if args.live_mode != 'True':
        input("Press any key to exit")
Exemple #30
0
    
    log = Logger()
    
    live_data = True
    do_trade = False
    
    data = DataLoader(ticker, start_time, live_data, do_trade)

    model = Model(data)
    model.fit()
    
    algorithm = Malgus(data, days, log, model)
    
    action = algorithm.determineInitialAction()
    
    strategy = Strategy(data, action, model)
    
    within_duration = True
    
    while (within_duration):
        
        print ("start action:", action.descr)
        
        action.performAction()
        
        next_action = strategy.chooseNextAction()
        
        action = next_action
        
        within_duration = algorithm.checkStop()
        
Exemple #31
0
                pass
            pass
            round_cnt += 1
            pass
        pass

    # Show player status
    def show_game_status(self):
        self.players[0].get_info()
        self.players[1].get_info()
        pass


# invictus_Gaming = Game()
# invictus_Gaming.start()
invictus_Gaming = Strategy()
invictus_Gaming.cfr_process()

# # Test if equal
# from card import Card
#
# player3 = Player(3, 50)
# player4 = Player(4, 50)
# card1 = []
# card2 = []
# community = []
# card1.append(Card("heart", 3))
# card1.append(Card("heart", 2))
# card2.append(Card("club", 3))
# card2.append(Card("club", 2))
# player3.set_cards(card1)
Exemple #32
0
 def on_place_fail(self, reason):
     Strategy.on_place_fail(self, reason)
Exemple #33
0
def main():
    data = GetData('poloniex', newdata=False)
    tickers = ['OMG/BTC']  #tickers = data.tickers()
    periods = ['30m']  #periods = ['5m','15m','30m','1h']
    maximum_parameters = []
    proportion_test = 0.1
    graph_results = True
    #data.fetch('BTC/USDT') # use if list length error

    for tick in tickers:
        if tick[-3:] == 'BTC':
            data.fetch(tick)
            temp_results = []

            for period in periods:
                '''formats the bitcoin and current coin data to the right period'''
                tick_data = data.periodFormatter(tick, period)
                startDate = tick_data.index[0]
                btc_data = data.periodFormatter('BTC/USDT', period, startDate)
                prices = [close for close in tick_data['Close']]
                '''formats the raw data to the proportion of data chosen'''
                startDate = tick_data.index[int(
                    (1 - proportion_test) * len(prices))]
                endDate = tick_data.index[-1]
                btc_prices = btc_data.loc[startDate:endDate]['Close']
                tick_prices = tick_data.loc[startDate:endDate]['Close']

                for MAlong in [10, 15, 30]:
                    for x in [2, 3, 4]:
                        MAshort = int(MAlong / x)
                        if len(tick_prices) == len(btc_prices):

                            strategy = Strategy(len(tick_prices))

                            for count, price in enumerate(tick_prices.values):
                                strategy.tick(price, btc_prices.values[count])
                                strategy.movingaverage(MAlong, MAshort, count)

                            profit, balance = strategy.returnParam()
                            temp_results.append([
                                tick, period, tick_prices, strategy, profit,
                                balance, MAlong, MAshort
                            ])
                        else:
                            print('length error')
                            break

            optimumParam = None
            for result in temp_results:
                if optimumParam == None:
                    optimumParam = result
                    optimum = result
                elif result[5] > optimumParam[5]:
                    optimumParam = result
                else:
                    pass

            print(optimumParam[0], optimumParam[1], optimumParam[4],
                  optimumParam[5], optimumParam[6], optimumParam[7])
            maximum_parameters.append(optimumParam)

        for param in maximum_parameters:
            plot = Graphics(param[2], param[3].MAlong, param[3].MAshort,
                            param[3].buylist, param[3].selllist,
                            param[3].balanceList)
            plot.MA_plot()
 def strategy(emotion_multiplier):
     return Strategy(
         lambda id: BasicEmotionPrisoner(id, emotion_multiplier),
         BasicEmotionPrisoner.prisoner_type)
Exemple #35
0
 def setUp(self):
     self.board = Board()
     self.strategy = Strategy(self.board, 'X')
Exemple #36
0
#print data.head()

"""
Main Entry point
"""
if __name__ == '__main__':
    
    dt = DataConstructor()
    dt.BuildData('002215')
    
    data = dt.GetData()
    
    CloseOrder = []

    st = Strategy(data,CloseOrder)

    plotter = Plotter(data)
    st.run1()

    plotter.plot1(st.getoo())
    #data = pd.read_csv('000001.csv')
    """   
    #init the margin column  
    #data['margin']=np.zeros(len(data))
 
    #create indicator
    ind = Indicator(data)
    ind.genIndicator()

    #create the strategy
Exemple #37
0
        # 是否交易的日期
        if not calendar.trade_day():
            none_trade_day()
            continue
        elif not calendar.trade_time():  #交易日非交易时间段
            none_trade_time()
            continue
        else:  #进入交易时间  calendar.trade_day() & calendar.trade_time()
            trade_time()
            #time.sleep(.5)


if __name__ == "__main__":
    #winsound.PlaySound('./wav/good afternoon CN.wav',winsound.SND_ASYNC)
    #time.sleep(3)
    args = sys.argv
    if len(args) == 5:
        strategy = Strategy(args[1], args[2], args[3], args[4])
    else:
        strategy = Strategy("QUERY_2_DAYS_HARD", 20, 5, 10)
    time.sleep(.5)
    trader = DFCF_Trader()
    calendar = TradeCalendar()
    quotation = PriceQuotation()
    try:
        run()
    except KeyboardInterrupt:
        #关闭打开的线程
        trader.kill = 1
        quotation.kill = 1
        print '\n\nCtrl-C Entered'
Exemple #38
0
class DukascopyEngine:
    def connect(self, instruments, period, strategyClass, strategyParams=None, getStat=False):
        self.name = 'Dukascopy'
        self.instruments = instruments
        self.period = period
        self.getStat = getStat
        self.strategy = strategyClass(self)
        self.strategyParams = strategyParams
        self.strategyClass = strategyClass

        self.slippage = 0

        self.start()

    def __init__(self):
        """for use getHistory without runing strategy"""
        self.strategy = Strategy(self)


    def start(self):
        context = zmq.Context()
        socket = context.socket(zmq.SUB)
        socket.connect('tcp://127.0.0.1:43001')

        for instrument in self.instruments:
            socket.setsockopt(zmq.SUBSCRIBE, instrument)

        self.strategy.onStart()

        ###main bars loop#######################################
        while True:
            filter = socket.recv()
            bar = socket.recv()
            bar = bar.split(' ')

            if self.period != (bar[0] + " " + bar[1]):
                continue

            bar[2] = datetime.utcfromtimestamp(float(bar[2]) / 1e3)
            bar = np.array(bar)
            bar = bar[2:]
            bar[1:11] = bar[1:11].astype(np.float32, copy=False)
            bar[1:11] = np.around(bar[1:11].astype(np.double),5)
            self.strategy.onBar(bar)
        ###main bars loop#######################################

        self.strategy.onStop()

    def sendOrder(self, order, bar=None):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")

        type = ""
        if order.market == True:
            if order.orderType == 1:
                type = "BUY"
            else:
                type = "SELL"
        else:
            if order.orderType == 1:
                type = "BUYLIMIT"
            else:
                type = "SELLLIMIT"

        order = ['sendOrder', self.strategyClass.name, order.instrument, type, str(order.lot), str(order.price),
                 str(self.slippage), str(order.stop), str(order.target), str(order.timeStopTime)]
        command = '--'.join(order)
        socket.send(command)
        message = socket.recv()
        return message

    def closeOrder(self, order, bar=None):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")

        type = ""
        if order.market == True:
            if order.orderType == 1:
                type = "BUY"
            else:
                type = "SELL"
        else:
            if order.orderType == 1:
                type = "BUYLIMIT"
            else:
                type = "SELLLIMIT"

        order = ['closeOrder', self.strategy.name, order.instrument, type, str(order.lot), str(order.price),
                 str(self.slippage), str(order.stop), str(order.target), str(order.timeStopTime)]
        command = '--'.join(order)
        socket.send(command)
        message = socket.recv()
        return message

    def closePosition(self, position, bar=None):
        self.closeOrder(position.order, bar)

    def getOrders(self):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")
        orders = []
        for instrument in self.instruments:
            command = ['getOrders', self.strategy.name, instrument]
            command = '--'.join(command)
            socket.send(command)
            message = socket.recv()
            if message != '':
                orderStrings = message.split('-+-')
                for orderString in orderStrings:
                    orderString = orderString.split('--')
                    market = True
                    orderType = 1
                    if orderString[2] == "SELL":
                        orderType = -1
                    if orderString[2] == "BUYLIMIT":
                        market = False
                    if orderString[2] == "SELLLIMIT":
                        orderType = -1
                        market = False
                    orders.append(
                        Order(instrument=orderString[1], orderType=orderType, market=market, lot=orderString[3],
                              price=orderString[4], stop=orderString[5],
                              target=orderString[6], timeStopTime=orderString[7], openTime=orderString[8]))
        return orders

    def getPositions(self):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")

        positions = []
        for instrument in self.instruments:
            command = ['getPositions', self.strategy.name, instrument]
            command = '--'.join(command)
            socket.send(command)
            message = socket.recv()
            if message != '':
                positionStrings = message.split('-+-')
                for positionString in positionStrings:
                    positionString = positionString.split('--')
                    market = True
                    orderType = 1
                    if positionString[2] == "SELL":
                        orderType = -1
                    if positionString[2] == "BUYLIMIT":
                        market = False
                    if positionString[2] == "SELLLIMIT":
                        orderType = -1
                        market = False

                    timeStopTime = datetime.utcfromtimestamp(float(positionString[7]) / 1e3)
                    orderOpenTime = datetime.utcfromtimestamp(float(positionString[8]) / 1e3)
                    positionOpenTime = datetime.utcfromtimestamp(float(positionString[9]) / 1e3)

                    positions.append(Position(
                        Order(instrument=positionString[1], orderType=orderType, market=market, lot=positionString[3],
                              price=positionString[4], stop=positionString[5],
                              target=positionString[6], timeStopTime=timeStopTime, openTime=orderOpenTime),
                        openTime=positionOpenTime))
        return positions

    def getHistoryBars(self, instrument, barsBefore, shift, barsAfter=0, period='ONE_MIN', trimInstrument = False, filterWeekends = True):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")
        command = ['getHistory', self.strategy.name, instrument, period, str(barsBefore), str(shift),
                   str(barsAfter), str(filterWeekends)]  # command, strategyName, intrument, period, barsBefore, shift, barsAfter
        command = '--'.join(command)
        socket.send(command)
        message = socket.recv()

        bars = []


        if message != '':
            barsStrings = message.split('-+-')
            for barStrings in barsStrings:
                bar = barStrings.split('--')

                bar[1] = datetime.utcfromtimestamp(float(bar[1]) / 1e3)
                bar = bar[1:]
                bar = np.array(bar)
                bar[1:11] = bar[1:11].astype(np.float32, copy=False)
                bar[1:11] = np.around(bar[1:11].astype(np.double),5)
                if trimInstrument == True:
                    bar = bar[:11]
                bars.append(bar)
            bars = np.array(bars)

        return bars

    def getHistoryFromDateUntilNow(self, instrument, period, dateFrom, trimInstrument = False):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")
        command = ['getHistoryFromDateUntilNow', self.strategy.name, instrument, period, str(dateFrom)]  # command, strategyName, intrument, period, barsBefore, shift, barsAfter
        command = '--'.join(command)
        socket.send(command)
        message = socket.recv()
        print message

        bars = []


        if message != '':
            barsStrings = message.split('-+-')
            for barStrings in barsStrings:
                bar = barStrings.split('--')

                bar[1] = datetime.utcfromtimestamp(float(bar[1]) / 1e3)
                bar = bar[1:]
                bar = np.array(bar)
                bar[1:11] = bar[1:11].astype(np.float32, copy=False)
                bar[1:11] = np.around(bar[1:11].astype(np.double),5)
                if trimInstrument == True:
                    bar = bar[:11]
                bars.append(bar)
            bars = np.array(bars)

        return bars

    def getHistoryFromDateToDate(self, instrument, period, dateFrom, dateTo, trimInstrument = False):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect("tcp://127.0.0.1:43002")
        command = ['getHistoryFromDateToDate', self.strategy.name, instrument, period, str(dateFrom), str(dateTo)]  # command, strategyName, intrument, period, barsBefore, shift, barsAfter
        command = '--'.join(command)
        socket.send(command)
        message = socket.recv()

        bars = []


        if message != '':
            if message.find('JFException') != -1:
                return message
            barsStrings = message.split('-+-')
            for barStrings in barsStrings:
                bar = barStrings.split('--')
                bar[1] = datetime.utcfromtimestamp(float(bar[1]) / 1e3)
                bar = bar[1:]
                bar = np.array(bar)
                bar[1:11] = bar[1:11].astype(np.float32, copy=False)
                bar[1:11] = np.around(bar[1:11].astype(np.double),5)
                if trimInstrument == True:
                    bar = bar[:11]
                bars.append(bar)
            bars = np.array(bars)

        return bars
Exemple #39
0
    def __init__(self, bars, balance_start, bankruptcy_at, multiplier, transaction_costs, slippage, timeperiod):

        Strategy.__init__(self, bars, balance_start, bankruptcy_at, multiplier, transaction_costs, slippage)

        pdta.SETTINGS.join = False
        self.indicator = pdta.MA(self.bars_pd, timeperiod)
Exemple #40
0
        transitions_player1.extend(transitions_player_1)
        transitions_player2.extend(transitions_player_2)

    return transitions_player1, transitions_player2


def constant_function(x):
    def fn():
        return x

    return fn


if __name__ == "__main__":
    cnn = CNN()
    stg = Strategy(cnn)
    megaman = Agent(stg)  # player 1
    megaman.get_exploration_factor = constant_function(EXPLORATION)
    megaman.train()

    performance = []
    print("Training ... ")
    for t in itertools.count():
        megaman.train()
        # p1, p2 = play_many([megaman, "negamax"], num_games=GAMES_PER_EPISODE)
        p1, p2 = play_many(["negamax", megaman], num_games=GAMES_PER_EPISODE)
        transitions = Transition(*zip(*p2))
        num_wins = transitions.reward.count(1)
        win_ratio = num_wins / GAMES_PER_EPISODE
        print(f"WR: {win_ratio:>6.2%}")
        performance.append(win_ratio)
Exemple #41
0
if os.path.isfile(DATASET_JSON):
    with open(DATASET_JSON) as dataset_json:
        items = json.load(dataset_json)["0"]
else:
    items = numpy.zeros(DATASET_SIZE, dtype=int)
    items[:int(len(items) * SELECTIVITY)] = 1
    numpy.random.shuffle(items)
    numpy.random.shuffle(items)
    dataset = dict()
    dataset[0] = list(items)
    with open(DATASET_JSON, "w") as dataset_json:
        json.dump(dataset, dataset_json)
enumerated = dict()
for (index, item) in enumerate(items):
    enumerated[index] = item
test = dict()
for i in range(TEST_PHASES):
    its = numpy.zeros(TEST_PHASE_SIZE, dtype=int)
    its[:TEST_PHASE_SIZE / 2] = 1
    numpy.random.shuffle(its)
    test[i] = its
crowd = Crowd(NUM_USERS, ERROR_RATE_YES, ERROR_RATE_NO, test)
avg_er_yes = crowd.avg_er_yes
avg_er_no = crowd.avg_er_no
strategy = Strategy(M, M)
unc_opt_cost = UncOptCost()

unc_opt_cost.unc_opt_cost(enumerated, K, SELECTIVITY, avg_er_yes, strategy,
                          crowd)
 def __init__(self, n=DEFAULT_N):
     '''
     Constructor
     '''
     Strategy.__init__(self)
     self._n = n  
Exemple #43
0
 def __init__(self):
     Strategy.__init__(self)
     self.target_vps_count = int(plebnet_settings.get_instance().strategy_vps_count())
Exemple #44
0
def run_strategy(name, path):
    strategy = Strategy(name, path)
    strategy.run()
Exemple #45
0
 def __init__(self):
     """for use getHistory without runing strategy"""
     self.strategy = Strategy(self)
Exemple #46
0
 def __init__(self,config):
   Strategy.__init__(self,config)
   self.placer = Placer(config)
   self.picker = Picker(config)
        s_result['pct_simple_profit'] = self.abs_profit / self.max_open 
        s_result['pct_compound_profit'] = self.pct_compound_profit
        s_result['annual_pct_simple_profit'] = (1+s_result['pct_simple_profit'])**self.years-1
        s_result['annual_pct_compound_profit'] = (1+s_result['pct_compound_profit'])**self.years-1
        s_result['volatility'] = np.std(self.profit_trades) * (1/self.years)**(1/2) # Annual volatility
        s_result['sharpe'] = s_result['annual_pct_simple_profit'] / s_result['volatility']
        print s_result['sharpe']
        return s_result
    
    def save_result(self):
        writer = pd.ExcelWriter("test_simulation.xlsx")
        df_result.to_excel(writer,"simulation")

#===============================================================================
# FUNCTIONS
#===============================================================================



#===============================================================================
# MAIN
#===============================================================================
if __name__=='__main__':
    strategy = Strategy()
    strategy.post_open_conditions(ndowns = 4)
    strategy.post_close_conditions(nups = 1)
    sim = Simulation("SPY", from_date='20050101', to_date='20120612')
    sim.get_prices_yahoo()
    sim.apply_strategy(strategy)
    s_result = sim.get_result()
    print s_result 
Exemple #48
0
# Timedelta -> Str
def time_format(t):
    return str(datetime.timedelta(seconds=int(t)))


# Event -> Strategy
lo = lambda event: Strategy([
    rules.LayTheOutsider(liability=100,
                         initial_price_from=3.75,
                         price_from=4,
                         price_to=13,
                         time_from=-10,
                         time_to=70),
    rules.Green([
        Condition(
            op.eq, S.back_price(S.home),
            S.maximum(S.back_price(S.away), S.back_price(S.home),
                      S.back_price(S.the_draw))),
        Condition(
            op.eq, S.back_price(S.away),
            S.minimum(S.back_price(S.away), S.back_price(S.home),
                      S.back_price(S.the_draw)))
    ])
], event)

one_x = lambda event: Strategy([
    rules.OneX(liability=100,
               margin=.07,
               away_initial_price_from=3.5,
               time_from=-10,
               time_to=70,
Exemple #49
0
        if self.portfolio_value is None:
            self._calculate_portfolio_value()
        return self.portfolio_value

    def _calculate_portfolio_value(self):
        data = (self.portfolio.allocations.
                loc[:,
                    self.portfolio.allocations.columns != Portfolio.CASH].mul(
                        self.stock_data.adj_close,
                        fill_value=None).ffill().sum(axis="columns").add(
                            self.portfolio.allocations[Portfolio.CASH],
                            fill_value=None).ffill())

        self.portfolio_value = pd.DataFrame(data=data,
                                            columns=[self.CLOSING_VALUE])


if __name__ == "__main__":
    symbols = ["SPY", "AMZN"]
    start = "2016-11-01"
    end = "2017-11-01"
    dates = pd.date_range(start=start, end=end)
    stock_data = StockData(symbols, dates=dates)

    strategy = Strategy()
    portfolio = Portfolio(symbols=symbols, stock_data=stock_data, dates=dates)
    portfolio.optimize(strategy=strategy, stock_data=stock_data)

    portfolio_analyzer = PortfolioAnalyzer(portfolio=portfolio,
                                           stock_data=stock_data)
Exemple #50
0
 def setUp(self):
     self.problem = Problem()
     self.strategy = Strategy()
Exemple #51
0
 def load_strategy(self):
   '''
   called by simulator
   '''
   self.strategy = Strategy(self, self.instrument, self.start_date, self.end_date)  
Exemple #52
0
 def on_place(self, oid, side, price, size, otype):
     Strategy.on_place(self, oid, side, price, size, otype)
Exemple #53
0
from tradingBot import TradingBot
from portfolio import Portfolio
from database import Database
from priceReceiver import Receiver
from tradeUpdates import TradeUpdates

config = configparser.ConfigParser()
config.read('config.ini')

account_id = 'ua'
db_url = os.environ['DATABASE_URL']
db_conn = Database.create_connection(db_url)

move_av = Strategy(
  db_conn, 'moving_average', 
  'limit', window_len = 5, 
  lookback_len = 7, buy_threshold = 0.01, 
  profit_margin = 0.005, stop_threshold = 0.005)
account = Portfolio(account_id)

tradeReceiver = TradeUpdates(
  "wss://paper-api.alpaca.markets/stream", 
  db_url, account_id)

dataReceiver = Receiver(
  "wss://data.alpaca.markets/stream", db_url)

traderBot = TradingBot(move_av, account, period = 60)

tradeReceiver.start()
dataReceiver.start()
Exemple #54
0
    # NDOWNS-NUPS
    #===========================================================================
#     strategy = Strategy(type='ndowns-nups')
#     strategy.post_open_conditions(ndowns = 4)
#     strategy.post_close_conditions(nups = 1)
#     sim = Simulation("SPY", from_date='20000101', to_date='20140612')
#     sim.apply_strategy(strategy)
#     s_result = sim.get_result()
#     print 'ndowns-nups: '
#     print s_result 
    
    
    #===========================================================================
    # PCTDOWN-NUPS - INTERDAY WITH YAHOO PRICES
    #===========================================================================
    strategy = Strategy(type='pctdown-nups', pctdown=5.0, nups=1)
    sim = Simulation("SPY", from_date='20000101', to_date='20140612')
    sim.get_prices_yahoo()
    sim.apply_strategy(strategy)
    s_result = sim.get_result()
    sim.save_result()
    print 'pctdown-nups: '
    print s_result
    
    #===========================================================================
    # PCTDOWN-NUPS - INTRADAY WITH IB PRICES
    #===========================================================================
    strategy = Strategy(type='pctdown-nups', pctdown=5.0, nups=1)
    sim = Simulation("AAPL", from_date='20000101', to_date='20140612')
    sim.get_prices_IB()
    sim.apply_strategy(strategy)
Exemple #55
0
 def __init__(self, color):
     Strategy.__init__(self, color)
Exemple #56
0
# -*- coding: utf-8 -*-
from strategy import Strategy
import settings
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("Sample")


def mylogic(ticker, ohlcv, position, balance, strategy):
    pass


strategy = Strategy(mylogic)
strategy.settings.timeframe = '1m'
strategy.settings.interval = 10
strategy.settings.partial_ohlcv = True
strategy.testnet.use = True
strategy.testnet.apiKey = settings.testnet_apiKey
strategy.testnet.secret = settings.testnet_secret
strategy.start()
    parser.add_argument('--config', type=argparse.FileType('r'))
    parser.add_argument('--bbos')
    parser.add_argument('--trds')
    args = parser.parse_args()

    config = json.load(args.config)

    log = Logger('backtest')
    log.operation({'config': config})

    watch_threshold = config['watch_threshold']
    watch_duration = config['watch_duration']
    slowdown_threshold = config['slowdown_threshold']
    slowdown_duration = config['slowdown_duration']

    strategy = Strategy(watch_threshold, watch_duration,
            slowdown_threshold, slowdown_duration)

    with io.TextIOWrapper(gzip.open(args.bbos, 'r')) as fh:
        fh.readline() # skip header
        bbos = collections.deque((process_bbo(line) for line in fh))

    with io.TextIOWrapper(gzip.open(args.trds, 'r')) as fh:
        fh.readline() # skip header
        trds = collections.deque((process_trd(line) for line in fh))

    current_trd = {'px': np.nan}
    current_bbo = {'bid_px': np.nan, 'ask_px': np.nan}

    end_of_time = np.datetime64('3000-01-01T00:00:00.000000')

    while bbos or trds:
Exemple #58
0
    def _generate_strategies(self):
        """Generates a pool of strategies to play."""

        size = self._config.get("number_strategies")
        return [Strategy(self._config) for _ in range(size)]