Exemple #1
0
import matplotlib.pyplot as plt
from datetime import datetime
import pytz

from alephnull.algorithm import TradingAlgorithm
from alephnull.utils.factory import load_from_yahoo

SYMBOL = 'GS'


class BuyStock(TradingAlgorithm):  # inherit from TradingAlgorithm
    """This is the simplest possible algorithm that does nothing but
    buy 1 share of SYMBOL on each event.
    """
    def handle_data(self, data):  # overload handle_data() method
        self.order(SYMBOL, 1)  # order SID (=0) and amount (=1 shares)


if __name__ == '__main__':
    start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=[SYMBOL], indexes={}, start=start, end=end)
    simple_algo = BuyStock()
    results = simple_algo.run(data)

    ax1 = plt.subplot(211)
    results.portfolio_value.plot(ax=ax1)
    ax2 = plt.subplot(212, sharex=ax1)
    stock_data = getattr(data, SYMBOL)
    stock_data.plot(ax=ax2)
    plt.gcf().set_size_inches(18, 8)
Exemple #2
0
    def sell_spread(self):
        """
		decrease exposure, regardless of position long/short.
		buy for a short position, sell for a long.
		"""
        ko_amount = self.portfolio.positions['KO'].amount
        self.order('KO', -1 * ko_amount)
        pep_amount = self.portfolio.positions['PEP'].amount
        self.order('PEP', -1 * pep_amount)


if __name__ == '__main__':
    start = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=['PEP', 'KO'],
                           indexes={},
                           start=start,
                           end=end)

    pairtrade = Pairtrade()
    results = pairtrade.run(data)
    data['spreads'] = np.nan

    ax1 = plt.subplot(211)
    data[['PEP', 'KO']].plot(ax=ax1)
    plt.ylabel('price')
    plt.setp(ax1.get_xticklabels(), visible=False)

    ax2 = plt.subplot(212, sharex=ax1)
    results.zscores.plot(ax=ax2, color='r')
    plt.ylabel('zscored spread')
        elif self.short_ema < self.long_ema and self.invested:
            self.order('AAPL', -100)
            self.invested = False
            self.sell = True

        self.record(AAPL=data['AAPL'].price,
                    short_ema=self.short_ema['AAPL'],
                    long_ema=self.long_ema['AAPL'],
                    buy=self.buy,
                    sell=self.sell)


if __name__ == '__main__':
    start = datetime(1990, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(1991, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start, end=end)

    dma = DualEMATaLib()
    results = dma.run(data).dropna()

    fig = plt.figure()
    ax1 = fig.add_subplot(211, ylabel='portfolio value')
    results.portfolio_value.plot(ax=ax1)

    ax2 = fig.add_subplot(212)
    results[['AAPL', 'short_ema', 'long_ema']].plot(ax=ax2)

    ax2.plot(results.ix[results.buy].index,
             results.short_ema[results.buy],
             '^',
             markersize=10,
                else:
                    self.order(SYMBOL, quantity_to_buy
                               )  # order SID (=0) and amount (=1 shares)

                if quantity_to_buy == 0:
                    TRACK.append(str(timestamp) + " had a 0-sell!")

        self.last_price = price


if __name__ == '__main__':
    start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=[SYMBOL],
                           indexes={},
                           start=start,
                           end=end,
                           adjusted=True)
    simple_algo = BuyStock()
    results = simple_algo.run(data)

    ax1 = plt.subplot(211)
    ax2 = plt.subplot(212)
    TRACK_STRIPPED = [x for x in TRACK if type(x) == tuple]
    futures_indexes = [timestamp for (_, _, timestamp) in TRACK_STRIPPED]
    futures_quantity_data = [
        quantity_owned for (_, quantity_owned, _) in TRACK_STRIPPED
    ]
    futures_margin_data = [margin for (margin, _, _) in TRACK_STRIPPED]

    futures_margin_series = TimeSeries(index=futures_indexes,
            self.buy = True
        elif self.short_ema < self.long_ema and self.invested:
            self.order('AAPL', -100)
            self.invested = False
            self.sell = True

        self.record(AAPL=data['AAPL'].price,
                    short_ema=self.short_ema['AAPL'],
                    long_ema=self.long_ema['AAPL'],
                    buy=self.buy,
                    sell=self.sell)

if __name__ == '__main__':
    start = datetime(1990, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(1991, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
                           end=end)

    dma = DualEMATaLib()
    results = dma.run(data).dropna()

    fig = plt.figure()
    ax1 = fig.add_subplot(211, ylabel='portfolio value')
    results.portfolio_value.plot(ax=ax1)

    ax2 = fig.add_subplot(212)
    results[['AAPL', 'short_ema', 'long_ema']].plot(ax=ax2)

    ax2.plot(results.ix[results.buy].index, results.short_ema[results.buy],
             '^', markersize=10, color='m')
    ax2.plot(results.ix[results.sell].index, results.short_ema[results.sell],
             'v', markersize=10, color='k')
Exemple #6
0
    Original matlab implementation: John Duchi ([email protected])
    Python-port: Copyright 2013 by Thomas Wiecki ([email protected]).
    """

    v = np.asarray(v)
    p = len(v)

    # Sort v into u in descending order
    v = (v > 0) * v
    u = np.sort(v)[::-1]
    sv = np.cumsum(u)

    rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1]
    theta = np.max([0, (sv[rho] - b) / (rho + 1)])
    w = (v - theta)
    w[w < 0] = 0
    return w

if __name__ == '__main__':
    import pylab as pl
    start = datetime(2004, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=STOCKS, indexes={}, start=start,
                           end=end)
    data = data.dropna()
    olmar = OLMAR()
    results = olmar.run(data)
    results.portfolio_value.plot()
    pl.show()
Exemple #7
0
import pytz

from alephnull.algorithm import TradingAlgorithm
from alephnull.utils.factory import load_from_yahoo

SYMBOL = "GS"


class BuyStock(TradingAlgorithm):  # inherit from TradingAlgorithm
    """This is the simplest possible algorithm that does nothing but
    buy 1 share of SYMBOL on each event.
    """

    def handle_data(self, data):  # overload handle_data() method
        self.order(SYMBOL, 1)  # order SID (=0) and amount (=1 shares)


if __name__ == "__main__":
    start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=[SYMBOL], indexes={}, start=start, end=end)
    simple_algo = BuyStock()
    results = simple_algo.run(data)

    ax1 = plt.subplot(211)
    results.portfolio_value.plot(ax=ax1)
    ax2 = plt.subplot(212, sharex=ax1)
    stock_data = getattr(data, SYMBOL)
    stock_data.plot(ax=ax2)
    plt.gcf().set_size_inches(18, 8)
Exemple #8
0
	def sell_spread(self):
		"""
		decrease exposure, regardless of position long/short.
		buy for a short position, sell for a long.
		"""
		ko_amount = self.portfolio.positions['KO'].amount
		self.order('KO', -1 * ko_amount)
		pep_amount = self.portfolio.positions['PEP'].amount
		self.order('PEP', -1 * pep_amount)


if __name__ == '__main__':
	start = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
	end = datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc)
	data = load_from_yahoo(stocks=['PEP', 'KO'], indexes={},
	                       start=start, end=end)

	pairtrade = Pairtrade()
	results = pairtrade.run(data)
	data['spreads'] = np.nan

	ax1 = plt.subplot(211)
	data[['PEP', 'KO']].plot(ax=ax1)
	plt.ylabel('price')
	plt.setp(ax1.get_xticklabels(), visible=False)

	ax2 = plt.subplot(212, sharex=ax1)
	results.zscores.plot(ax=ax2, color='r')
	plt.ylabel('zscored spread')

	plt.show()
                # it is just distributed over a larger number of contracts
                if quantity_to_buy == 0:
                    TRACK.append("0 to buy, what a shame")
                else:
                    self.order(SYMBOL, quantity_to_buy)  # order SID (=0) and amount (=1 shares)

                if quantity_to_buy == 0:
                    TRACK.append(str(timestamp) + " had a 0-sell!")

        self.last_price = price


if __name__ == '__main__':
    start = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=[SYMBOL], indexes={}, start=start,
                           end=end, adjusted=True)
    simple_algo = BuyStock()
    results = simple_algo.run(data)

    ax1 = plt.subplot(211)
    ax2 = plt.subplot(212)
    TRACK_STRIPPED = [x for x in TRACK if type(x) == tuple]
    futures_indexes = [timestamp for (_, _, timestamp) in TRACK_STRIPPED]
    futures_quantity_data = [quantity_owned for (_, quantity_owned, _) in TRACK_STRIPPED]
    futures_margin_data = [margin for (margin, _, _) in TRACK_STRIPPED]

    futures_margin_series = TimeSeries(index=futures_indexes, data=futures_margin_data)
    futures_margin_series.plot(ax=ax1)
    futures_quantity_series = TimeSeries(index=futures_indexes, data=futures_quantity_data)
    futures_quantity_series.plot(ax=ax2)
Exemple #10
0
    Original matlab implementation: John Duchi ([email protected])
    Python-port: Copyright 2013 by Thomas Wiecki ([email protected]).
    """

    v = np.asarray(v)
    p = len(v)

    # Sort v into u in descending order
    v = (v > 0) * v
    u = np.sort(v)[::-1]
    sv = np.cumsum(u)

    rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1]
    theta = np.max([0, (sv[rho] - b) / (rho + 1)])
    w = (v - theta)
    w[w < 0] = 0
    return w


if __name__ == '__main__':
    import pylab as pl
    start = datetime(2004, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
    data = load_from_yahoo(stocks=STOCKS, indexes={}, start=start, end=end)
    data = data.dropna()
    olmar = OLMAR()
    results = olmar.run(data)
    results.portfolio_value.plot()
    pl.show()