Exemple #1
0
 def test_history_run_data_fetching(self):
     #parameters:
     pca.k = 2
     pca.H = 4
     pca.regime_switcher = False
     amount = 5
     stocks = stockdata.get_stock_names(self.nasdaq_path, amount)
     index = '^GSPC'
     time_period = 9
     start_date = datetime.date(2014, 2, 11)
     end_date = datetime.date(2014, 3, 13)
     dates, prices, signals = stockdata.history_run(stocks, index,
                                                    time_period, start_date,
                                                    end_date)
     right_signals = [['sell', 'sell', 'sell', 'sell', 'sell'],
                      ['sell', 'sell', 'sell', 'sell', 'sell'],
                      ['buy', 'sell', 'sell', 'buy', 'buy'],
                      ['buy', 'sell', 'sell', 'sell', 'buy'],
                      ['sell', 'sell', 'sell', 'sell', 'sell']]
     right_dates = [datetime.date(2014, 3, 7),
                    datetime.date(2014, 3, 10),
                    datetime.date(2014, 3, 11),
                    datetime.date(2014, 3, 12),
                    datetime.date(2014, 3, 13)]
     right_prices = [[5.41, 5.46, 5.47, 5.46, 5.36],
                     [8.11, 8.13, 8.0, 7.89, 7.97],
                     [10.25, 10.3, 10.25, 10.25, 10.3],
                     [32.12, 32.01, 31.67, 31.94, 31.81],
                     [7.87, 7.9, 7.81, 7.79, 7.64]]
     self.assertEqual(dates, right_dates)
     self.assertEqual(prices, right_prices)
     self.assertEqual(signals, right_signals)
Exemple #2
0
    def test_get_stock_names_5_from_1(self):
        amount = 5

        first_5_nasdaq_stocks = stockdata.get_stock_names(self.nasdaq_path,
                                                          amount)
        self.assertEqual(first_5_nasdaq_stocks,
                         ['FLWS', 'FCTY', 'FCCY', 'SRCE', 'FUBC'])
Exemple #3
0
 def test_get_stock_names_10_from_27(self):
     amount = 10
     start = 27
     path = 'stock_names/NASDAQ.csv'
     first_10_nasdaq_stocks = stockdata.get_stock_names(self.nasdaq_path,
                                                        amount, start)
     right_stocks = ['ACET', 'ACHN', 'ACIW', 'ACNB', 'ACOR',
             'ACFN', 'ACTS', 'ACPW', 'ATVI', 'BIRT']
     self.assertEqual(first_10_nasdaq_stocks, right_stocks)
Exemple #4
0
 def test_history_run_big_data(self):
     """
     start_date	      u'2010-01-05'
     end_date          u'2014-03-20'
     H	              u'10'
     k	              u'5'
     regime_switcher   u'off'
     stock_amount	  u'10'
     time_period	      u'20'
     """
     #parameters:
     pca.k = 5
     pca.H = 10
     pca.regime_switcher = False
     amount = 10
     stocks = stockdata.get_stock_names(self.nasdaq_path, amount)
     index = '^GSPC'
     time_period = 20
     start_date = datetime.date(2010, 1, 5)
     end_date = datetime.date(2014, 3, 20)
     dates, prices, signals = stockdata.history_run(stocks, index,
                                                    time_period, start_date,
                                                    end_date)
Exemple #5
0
def run(request):
    def graph_img(x, y, name):
        def y_precise():
            result = ["chd=t:"]
            for elem in y:
                result.append(str(elem))
                result.append(',')
            result[-1] = '&'
            return ''.join(result)

        G = Line(y, encoding='text')
        G.axes.type('xy')
        min_y = min(y)
        max_y = max(y)
        G.axes.range(1, min_y, max_y)
        G.scale(min_y, max_y)
        G.axes.label(0, x[0], x[-1])
        G.axes.label(1, min_y, max_y)
        G.title(name)
        image_code = G.img()
        norm_img = re.sub(r'chd=t.*?\&', y_precise(), image_code)
        if len(norm_img) > 2000:
            if len(image_code) > 2000:
                raise LongPeriodException()
            else:
                return image_code
        return norm_img
    try:
        # getting parameters
        start_date = datetime.strptime(request.POST['start_date'],
                                       '%Y-%m-%d').date()
        end_date = datetime.strptime(request.POST['end_date'],
                                     '%Y-%m-%d').date()
        stock_amount = int(request.POST['stock_amount'])
        time_period = int(request.POST['time_period'])
        k = int(request.POST['k'])
        H = int(request.POST['H'])
        regime_switcher = request.POST['regime_switcher']
    except KeyError:
        raise
    # starting our job
    pca.k = k
    pca.H = H
    if regime_switcher == 'off':
        pca.regime_switcher = False
    else:
        pca.regime_switcher = True
    index = '^GSPC'
    source = os.path.join(settings.BASE_DIR,
                          'strategy_runner/stock_names/'
                          'NASDAQ.csv')
    stocks = stockdata.get_stock_names(source, stock_amount)
    try:
        dates, prices, signals = stockdata.history_run(stocks, index,
                                                       time_period, start_date,
                                                       end_date)
    except (pca.WrongParameterException, pca.WrongPricesError) as e:
        return render(request, 'strategy_runner/base_history.html',
                      {'error_message': str(e)})
    date_strings = [date.strftime('%Y-%m-%d') for date in dates]
    returns, pl = stockdata.get_returns_and_pl(prices, signals)

    #prepare img tags with graphs to pass to the template
    graph_imgs = []
    try:
        for i, price_list in enumerate(prices):
            graph_imgs.append(graph_img(date_strings, price_list, stocks[i]))
        graph_imgs.append(graph_img(date_strings, returns,
                                    'Cumulative Log Returns'))
        graph_imgs.append(graph_img(date_strings, pl, r'Profit/Loss'))
    except LongPeriodException as e:
        return render(request, 'strategy_runner/base_history.html',
                      {'error_message': str(e)})

    # NamedPrices = namedtuple('NamedPrices', ['stock', 'prices'])
    # named_prices = []
    # for i, stock in enumerate(stocks):
    #     named_prices.append(NamedPrices(stock, prices[i]))
    return render(request,
                  'strategy_runner/base_history.html',
                  {'graph_imgs': graph_imgs})