Example #1
0
def test_bucket_get_stock_configs():
    """
    Tests InvestmentBucket.get_stock_configs()
    """
    user1 = User.objects.create(username='******', password="******")
    stock1 = Stock(name="Name1X", ticker="TKRC")
    stock2 = Stock(name="Name2X", ticker="TKRCF")
    stock1.save()
    stock2.save()
    bucket = InvestmentBucket(name="Bucket1",
                              public=True,
                              owner=user1.profile,
                              available=1)
    bucket.save()
    InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=bucket,
        start="2016-06-06",
        end="2016-06-08",
    ).save()
    InvestmentStockConfiguration(quantity=1,
                                 stock=stock1,
                                 bucket=bucket,
                                 start="2016-06-08").save()
    InvestmentStockConfiguration(quantity=1,
                                 stock=stock2,
                                 bucket=bucket,
                                 start="2016-06-06").save()
    assert bucket.get_stock_configs().count() == 2
    assert bucket.get_stock_configs("2016-06-06").count() == 2
    assert bucket.get_stock_configs("2016-06-08").count() == 3
Example #2
0
def test_bucket_historical():
    """
    Tests InvestmentBucket.historical()
    """
    user = User.objects.create(username='******', password="******")
    stock = Stock(name="Name1X", ticker="TKRC")
    stock.save()
    value = [3, 5, 7, 2]
    skip = 2
    for idx, val in enumerate(value):
        stock.daily_quote.create(value=val,
                                 date=datetime.datetime.now().date() -
                                 datetime.timedelta(days=idx + 2))
    available = 2
    bucket = InvestmentBucket(name="bucket",
                              public=True,
                              owner=user.profile,
                              available=available)
    bucket.save()
    quantity = 3
    config = InvestmentStockConfiguration(
        quantity=quantity,
        stock=stock,
        bucket=bucket,
        start=datetime.datetime.now().date() -
        datetime.timedelta(days=len(value) + 2))
    config.save()
    historical = bucket.historical(count=len(value), skip=skip)
    for idx, val in enumerate(value):
        assert historical[idx] == (datetime.datetime.now().date() -
                                   datetime.timedelta(days=idx + 2),
                                   val * quantity + available)
    stock2 = Stock(name="Name2X", ticker="Testes")
    stock2.save()
    value = list(range(1, 31))
    for val in value:
        idx = val - 1
        stock2.daily_quote.create(value=val,
                                  date=datetime.datetime.now().date() -
                                  datetime.timedelta(days=idx))
    bucket2 = InvestmentBucket(name="bucket2",
                               public=True,
                               owner=user.profile,
                               available=0)
    bucket2.save()
    config2 = InvestmentStockConfiguration(
        quantity=1,
        stock=stock2,
        bucket=bucket2,
        start=datetime.datetime.now().date() -
        datetime.timedelta(days=len(value)))
    config2.save()
    historical2 = bucket2.historical()
    for val in value:
        idx = val - 1
        assert historical2[idx] == (datetime.datetime.now().date() -
                                    datetime.timedelta(days=idx), val)
Example #3
0
def test_stock_find_stock():
    """
    Tests Stock.find_stock()
    """
    stock1 = Stock(name="Name1X", ticker="TKRC")
    stock1.save()
    stock2 = Stock(name="Name2Y", ticker="TKFF")
    stock2.save()
    TestCase.assertCountEqual(None, [stock1, stock2], Stock.find_stock(""))
    TestCase.assertCountEqual(None, [stock1, stock2], Stock.find_stock("Name"))
    TestCase.assertCountEqual(None, [stock1], Stock.find_stock("Name1"))
    TestCase.assertCountEqual(None, [stock2], Stock.find_stock("e2"))
    single_stock_find = Stock.find_stock("", 1)[0]
    assert single_stock_find == stock1 or single_stock_find == stock2
Example #4
0
def test_stock_config_value_on():
    """
    Tests InvestmentStockConfiguration.value_on()
    """
    user = User.objects.create(username='******', password="******")
    stock = Stock(name="Name1X", ticker="TKRC")
    stock.save()
    value = 5
    stock.daily_quote.create(value=value, date="2016-06-06")
    bucket = InvestmentBucket(name="bucket",
                              public=True,
                              owner=user.profile,
                              available=2)
    bucket.save()
    quantity = 3
    config = InvestmentStockConfiguration(quantity=quantity,
                                          stock=stock,
                                          bucket=bucket,
                                          start="2016-06-08")
    config.save()
    with pytest.raises(Exception):
        config.value_on("2016-06-01")
    assert config.value_on("2016-06-08") == quantity * value
    mock_quote = namedtuple('mock_quote', 'value')
    with mock.patch.object(
            Stock, "latest_quote",
            mock.MagicMock(return_value=mock_quote(float('NaN')))):
        with pytest.raises(Exception):
            config.value_on()
Example #5
0
 def update_by_ticker(ticker):
     """
     Get recent stock data of given ticker from AlphaVantage API and POSTs
     latest data to database, then DELETEs oldest data from database.
     Fails if company doesn't exist in database or record for current
     date exists.
     :param ticker: Ticker symbol to update data
     :return: 0: success
              1: record already exists
              2: company not found in database
              -1: undefined error
     """
     if not Stock.objects.filter(ticker=ticker).exists():
         return 2
     api_response = AlphaAPICaller().get_compact_date(ticker, meta=True)
     try:
         last_refresh = api_response['latest_data']['date'][:10]
     except TypeError:
         return -1
     if Stock.objects.filter(ticker=ticker, date=last_refresh).exists():
         return 1
     # Delete oldest entry
     oldest_obj = Stock.objects.filter(ticker=ticker).earliest('date')
     oldest_obj.delete()
     # Add to database using model or API
     json_data = api_response['latest_data']
     new_entry = Stock(ticker=json_data['ticker'],
                       opening=json_data['opening'],
                       high=json_data['high'], low=json_data['low'],
                       closing=json_data['closing'],
                       volume=json_data['volume'], date=json_data['date'])
     new_entry.save()
     return 0
Example #6
0
 def test_fill_stock_data(self):
     """
     Filling data for stock
     """
     Stock(name="Facebook", ticker="FB").save()
     request = self.client.get('/stocks/fill/', follow=True, secure=True)
     self.assertEqual(request.status_code, 200)
Example #7
0
 def test_back_fill_helper(self):
     """
     Testing fill helper
     """
     stock = Stock(name="Facebook", ticker="FB")
     stock.save()
     historical.fill()
     stock_db = DailyStockQuote.objects.values('stock_id')[0]
     data = DailyStockQuote.objects.filter(stock_id=stock_db['stock_id'])
     self.assertEqual(4, len(data))
def selenium_task(worker, ticker):

    worker.set_window_size(randint(100, 200), randint(200, 400))
    logger.info("Getting Google")
    worker.get(f'https://sec.report/Ticker/{ticker}')

    try:
        cik = worker.find_element_by_xpath(
            '/html/body/div[1]/div/h2[1]').text.split()[-1]
    except:
        no_cik.append(ticker)
        Stock(ticker=ticker, exchange='NASDAQ').save()
        return
    try:
        firm = Firm.objects.get(pk=cik)
    except:
        name = worker.find_element_by_xpath(
            '/html/body/div[1]/div/h1').text.split(':')[-1].lstrip()
        sic1 = worker.find_elements_by_xpath(
            '/html/body/div[1]/div/div[3]/div[2]/table/tbody/tr[6]/td')
        if sic1 != [] and sic1[0].text == 'SIC':
            sic = sic1[1].text.split()[0]
        else:
            sic2 = worker.find_elements_by_xpath('/html/body/div[1]/div/div[3]/div[2]/table/tbody/tr[5]/td')
            if sic2 != [] and sic2[0].text == 'SIC':
                sic = sic2[1].text.split()[0]
            else:
                sic3 = worker.find_elements_by_xpath(
                    '/html/body/div[1]/div/div[4]/div[2]/table/tbody/tr[6]/td')
                if sic3 != [] and sic3[0].text == 'SIC':
                    sic = sic3[1].text.split()[0]
                else:
                    sic4 = worker.find_elements_by_xpath(
                        '/html/body/div[1]/div/div[4]/div[2]/table/tbody/tr[5]/td')
                    if sic4 != [] and sic4[0].text == 'SIC':
                        sic = sic4[1].text.split()[0]
                    else:
                        sic = 9999
        firm = Firm(cik=cik, name=name, sic_id=int(sic))
        firm.save()

    Stock(ticker=ticker, firm=firm, exchange='NASDAQ').save()
Example #9
0
def test_change_bucket_composition(selenium, live_server, client):
    """
    Test selling a bucket
    """
    user = User.objects.create_user('temporary', '*****@*****.**', 'temporary')
    user.save()
    user.userbank.create(
        item_id='dummy1', access_token='dummy2',
        institution_name='dummy3', current_balance_field=0,
        account_name_field="dummy4", income_field=0,
        expenditure_field=0
    )
    stock = Stock(
        name="Name1", ticker="poooooop"
    )
    stock.save()
    stock.daily_quote.create(
        value=1000, date="2016-03-03"
    )
    client.login(username='******', password='******')
    cookie = client.cookies['sessionid']
    buck = InvestmentBucket.create_new_bucket(
        name="IAMATESTBUCKET",
        public=True,
        owner=user.profile)
    buck.save()
    InvestmentStockConfiguration(quantity=1, stock=stock, bucket=buck, start="2016-03-03").save()
    assert user.profile.owned_bucket.count() == 1
    user.profile.default_acc().trade_bucket(buck, .01)
    selenium.get('%s%s' % (live_server, '/login'))
    selenium.add_cookie({
        'name': 'sessionid',
        'value': cookie.value,
        'secure': False,
        'path': '/',
    })
    selenium.get('%s%s' % (live_server, '/home'))
    selenium.implicitly_wait(10)
    edit_button = selenium.find_element_by_id("edit-comp")
    edit_button.click()
    slider = selenium.find_element_by_class_name("rc-slider-handle-2")
    actions = ActionChains(selenium)
    actions.click_and_hold(slider)
    actions.move_by_offset(-100, 0)
    actions.release(slider)
    actions.perform()
    save_composition = selenium.find_element_by_xpath("//button[contains(.,'Save')]")
    save_composition.click()
    time.sleep(1)
    assert buck.stocks.count() == 2
Example #10
0
def test_stock_latest_quote():
    """
    Tests Stock.latest_quote()
    """
    stock = Stock(name="Name1", ticker="TKRC")
    stock.save()
    correct_quote3 = stock.daily_quote.create(value=3, date="2016-06-03")
    correct_quote1 = stock.daily_quote.create(value=4, date="2016-06-05")
    correct_quote2 = stock.daily_quote.create(value=5, date="2016-06-06")
    assert stock.latest_quote("2016-06-05") == correct_quote1
    assert stock.latest_quote() == correct_quote2
    assert stock.latest_quote("2016-06-04") == correct_quote3
    with pytest.raises(Exception):
        stock.latest_quote("2016-06-02")
    with pytest.raises(Exception):
        stock.latest_quote(datetime.datetime.now() +
                           datetime.timedelta(days=3))
Example #11
0
def test_bucket_add_stock(selenium, live_server, client):
    """
    Test adding stock to bucket
    """
    user = User.objects.create_user('temporary', '*****@*****.**', 'temporary')
    user.save()
    user.userbank.create(
        item_id='dummy1', access_token='dummy2',
        institution_name='dummy3', current_balance_field=0,
        account_name_field="dummy4", income_field=0,
        expenditure_field=0
    )
    stock = Stock(
        name="Name1", ticker="poooooop"
    )
    stock.save()
    stock.daily_quote.create(
        value=10000, date="2016-03-03"
    )
    client.login(username='******', password='******')
    cookie = client.cookies['sessionid']
    buck = InvestmentBucket.create_new_bucket(
        name="IAMATESTBUCKET", public=True,
        owner=user.profile)
    buck.save()
    assert user.profile.owned_bucket.count() == 1
    selenium.get('%s%s' % (live_server, '/login'))
    selenium.add_cookie({
        'name': 'sessionid',
        'value': cookie.value,
        'secure': False,
        'path': '/',
    })
    selenium.get('%s%s' % (live_server, '/home'))
    selenium.implicitly_wait(30)
    bucket = user.profile.owned_bucket.get(name="IAMATESTBUCKET")
    assert bucket.get_stock_configs().count() == 0
    edit_button = selenium.find_element_by_id("edit-comp")
    edit_button.click()
    stock_field = selenium.find_element_by_id("stockname")
    stock_field.send_keys("Name1")
    add_stock = selenium.find_element_by_id("add-stock")
    add_stock.click()
    save_composition = selenium.find_element_by_xpath("//button[contains(.,'Save')]")
    save_composition.click()
    assert bucket.get_stock_configs().count() == 1
Example #12
0
def test_mutation_add_stock_to_bucket(rf, snapshot):
    """
    This submits a massive graphql query to verify all fields work
    """
    # pylint: enable=invalid-name
    request = rf.post('/graphql')
    pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9))
    request.user = User.objects.create(username='******', password=pw1)
    bucket = InvestmentBucket(name="i1",
                              public=False,
                              available=100,
                              owner=request.user.profile)
    bucket.save()
    post_save.disconnect(receiver=create_stock, sender=Stock)
    stock = Stock(name="Google", ticker="GOOGL")
    stock.save()
    DailyStockQuote(value=9, date="2017-05-08", stock=stock).save()
    DailyStockQuote(value=10, date="2017-05-10", stock=stock).save()
    DailyStockQuote(value=9, date="2017-05-09", stock=stock).save()
    client = Client(SCHEMA)
    executed = client.execute("""
            mutation {{
              addStockToBucket(stockId: "{}", bucketId: "{}", quantity: {}) {{
                bucket {{
                    available
                    isOwner
                    public
                    name
                    stocks {{
                        edges {{
                            node {{
                                quantity
                                stock {{
                                    ticker
                                }}
                            }}
                        }}
                    }}
                }}
              }}
            }}
        """.format(to_global_id("GStock", stock.id),
                   to_global_id("GInvestmentBucket", bucket.id), 3.5),
                              context_value=request)
    snapshot.assert_match(executed)
    assert InvestmentStockConfiguration.objects.count() == 1
Example #13
0
def test_trading_acc_trade_stock():
    """
    Test trade stock
    """
    user = user_helper()
    trading_account = user.profile.trading_accounts.create(
        account_name="spesh")
    stock = Stock(name="sto", ticker='sto')
    stock.save()
    stock.daily_quote.create(value=4, date="2016-06-05")
    with pytest.raises(Exception):
        trading_account.trade_stock(stock, -2)
    trading_account.trade_stock(stock, 2)
    with pytest.raises(Exception):
        trading_account.trade_stock(stock, -3)
    assert trading_account.has_enough_stock(stock, 2)
    trading_account.trade_stock(stock, -2)
    assert trading_account.available_stocks(stock) == 0
Example #14
0
	def setUp(self):
		test_stock = Stock(name='Test Stock', ticker='TEST0')
		test_stock.save()
		test_portfolio = Portfolio(name='testportfolio')
		test_portfolio.save()

		for i in xrange(1, 10):
			test_action = PortfolioStockAction(
				buy=True,
				sell=False,
				date=date.today(),
				amount=i,
				value_at_action_time=10.0,
				stock=test_stock
			)
			test_action.save()
			test_portfolio.actions.add(test_action)
			test_portfolio.save()
Example #15
0
def test_stock_quote_in_range():
    """
    Tests Stock.quote_in_range()
    """
    stock = Stock(name="Name1X", ticker="TKRC")
    stock.save()
    quote1 = stock.daily_quote.create(value=3, date="2016-06-03")
    quote3 = stock.daily_quote.create(value=5, date="2016-06-06")
    quote2 = stock.daily_quote.create(value=4, date="2016-06-05")
    assert [quote1, quote2, quote3] == list(stock.quote_in_range())
    assert [quote1, quote2, quote3] == list(
        stock.quote_in_range(start="2016-06-03", end="2016-06-06"))
    assert [] == list(
        stock.quote_in_range(start="2016-06-03", end="2016-06-02"))
    assert [quote1, quote2,
            quote3] == list(stock.quote_in_range(start="2016-06-03"))
    assert [quote2, quote3] == list(stock.quote_in_range(start="2016-06-04"))
    assert [quote1, quote2,
            quote3] == list(stock.quote_in_range(end="2016-06-06"))
    assert [quote1, quote2] == list(stock.quote_in_range(end="2016-06-05"))
Example #16
0
def test_stocks_trade_sell_no_stock(api_client, get_or_create_token):
    """
    Selling, stock not available in inventory.
    """
    # setup sample stock and inventory
    apple = Stock(name='Apple', unit_price=5.00, units_available=100)
    apple.save()
    # build request json data
    data = dict(transaction_type='sell', stock_id=apple.id, quantity=5)
    # call endpoint
    url = '/stocks/trade/'
    api_client.credentials(HTTP_AUTHORIZATION='Token %s' % get_or_create_token)
    response = api_client.post(url,
                               json.dumps(data),
                               content_type="application/json")
    # test response
    assert response.status_code == 200
    rjson = response.json()
    assert rjson['message'] == 'You do not have %s in your inventory' % (
        apple.name)
Example #17
0
def test_trading_acc_av_stk():
    """
    Test available stocks
    """
    user = user_helper()
    trading_account = user.profile.trading_accounts.create(
        account_name="spesh")
    stock = Stock(name="sto", ticker="sto")
    stock.save()
    stock.daily_quote.create(value=4, date="2016-06-05")
    assert trading_account.available_stocks(stock) == 0
    trading_account.trade_stock(stock, 1)
    assert trading_account.available_stocks(stock) == 1
    with pytest.raises(Exception):
        trading_account.trade_stock(stock, 2342342342342234)
    assert trading_account.available_stocks(stock) == 1
    with pytest.raises(Exception):
        trading_account.trade_stock(stock, -2342342342342234)
    assert trading_account.available_stocks(stock) == 1
    trading_account.trade_stock(stock, -1)
    assert trading_account.available_stocks(stock) == 0
Example #18
0
def portfolio(request):
    user = request.user
    if request.method == 'POST':
        form = StockForm(request.POST)
        if form.is_valid():
            symbol = form.cleaned_data['symbol'].upper()
            is_exist = Stock.objects.filter(user=user, symbol=symbol).count()
            if not is_exist:
                Stock(user=user, symbol=symbol).save()
    form = StockForm()
    infos = []
    stocks = Stock.objects.filter(user=user).values_list('pk', 'symbol')
    if stocks:
        symbols = [s[1] for s in stocks]
        data = get_current_info(symbols)
        infos = [data] if data.__class__ == dict else data
        for i, v in enumerate(infos):
            v.update({'pk': stocks[i][0]})

    return render(request, 'stocks/portfolio.html', {'form': form,
                                                     'infos': infos})
Example #19
0
def request_create(request):
    """
    Creates a fully functional environment that we can test on
    """
    post_save.disconnect(receiver=create_stock, sender=Stock)
    stock = Stock(name="Google", ticker="GOOGL")
    stock.save()

    pw2 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9))
    user2 = User.objects.create(username='******', password=pw2)
    account2 = TradingAccount(profile=user2.profile,
                              account_name="testAccount2")
    account2.save()
    trade2 = Trade(quantity=2, account=account2, stock=stock)
    trade2.save()

    pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9))
    request.user = User.objects.create(username='******', password=pw1)
    account1 = TradingAccount(profile=request.user.profile,
                              account_name="testAccount1")
    account1.save()
    trade1 = Trade(quantity=1, account=account1, stock=stock)
    trade1.save()

    bucket = InvestmentBucket(name="i1",
                              public=False,
                              available=100,
                              owner=request.user.profile)
    bucket.save()
    InvestmentBucketDescription(text="Blabla", is_good=True,
                                bucket=bucket).save()
    DailyStockQuote(value=9, date="2017-05-08", stock=stock).save()
    DailyStockQuote(value=10, date="2017-05-10", stock=stock).save()
    InvestmentStockConfiguration(stock=stock,
                                 quantity=1,
                                 bucket=bucket,
                                 start="2017-05-09").save()

    return request
Example #20
0
def test_has_enough_stock():
    """
    Test has enough stock
    """
    user = user_helper()
    trading_account = user.profile.trading_accounts.create(
        account_name="spesh")
    stock = Stock(name="sto", ticker="sto")
    stock.save()
    stock.daily_quote.create(value=0.0, date="2016-06-05")
    assert trading_account.has_enough_stock(stock, 1) is False
    trading_account.trade_stock(stock, 1)
    assert trading_account.has_enough_stock(stock, 1)
    assert trading_account.has_enough_stock(stock, 2) is False
    trading_account.trade_stock(stock, 1000)
    assert trading_account.has_enough_stock(stock, 1001)
    assert trading_account.has_enough_stock(stock, 1002) is False
    trading_account.trade_stock(stock, -1000)
    assert trading_account.has_enough_stock(stock, 1)
    assert trading_account.has_enough_stock(stock, 2) is False
    trading_account.trade_stock(stock, -1)
    assert trading_account.has_enough_stock(stock, 1) is False
Example #21
0
def test_stocks_trade_sell(api_client, get_or_create_token):
    """
    Sell stocks.
    """
    # setup sample stock
    starting_units_available = 100
    apple = Stock(
            name='Apple', unit_price=5.00,
            units_available=starting_units_available
        )
    apple.save()
    user = User.objects.get(username='******')
    starting_total_units = 17
    user_stock = UserStock(
            user=user, stock=apple, total_units=starting_total_units
        )
    user_stock.save()
    # build request json data
    data = dict(
            transaction_type='sell',
            stock_id=apple.id,
            quantity=5
        )
    # call endpoint
    url = '/stocks/trade/'
    api_client.credentials(HTTP_AUTHORIZATION='Token %s' % get_or_create_token)
    response = api_client.post(
            url, json.dumps(data), content_type="application/json"
        )
    # test response
    assert response.status_code == 201
    rjson = response.json()
    assert rjson['message'][:9] == 'Thank you'
    # test product inventory
    user_stock = UserStock.objects.get(user=user, stock=apple)
    assert user_stock.total_units == starting_total_units - data['quantity']
    # test available stock units
    apple = Stock.objects.get(name='Apple')
    assert apple.units_available == starting_units_available + data['quantity']
Example #22
0
def test_stocks_trade_invalid_quantity(api_client, get_or_create_token):
    """
    Quantity is invalid
    """
    # setup sample stock
    starting_units_available = 100
    apple = Stock(name='Apple',
                  unit_price=5.00,
                  units_available=starting_units_available)
    apple.save()
    # build request json data
    data = dict(transaction_type='buy', stock_id=apple.id, quantity=0)
    # call endpoint
    url = '/stocks/trade/'
    api_client.credentials(HTTP_AUTHORIZATION='Token %s' % get_or_create_token)
    response = api_client.post(url,
                               json.dumps(data),
                               content_type="application/json")
    # test response
    assert response.status_code == 200
    rjson = response.json()
    assert rjson['message'] == 'Invalid quantity'
Example #23
0
 def get_tradeable_assets(self):
     url = 'https://api.tradier.com/v1/markets/lookup'
     params = {'types': 'stock,etf,index', 'linebreak': 'true'}
     r = s.get(url, params=params)
     content = json.loads(r.text)
     stocks = Stock.objects.all()
     stocks = [item.symbol for item in stocks]
     for stock in content["securities"]["security"]:
         if stock["symbol"] not in stocks:
             new_stock = Stock()
             new_stock.symbol = stock["symbol"]
             new_stock.company = stock["description"]
             if StockExchange.objects.filter(code=stock["exchange"]):
                 new_stock.exchange = StockExchange.objects.get(
                     code=stock["exchange"])
                 new_stock.bid = 0
                 new_stock.ask = 0
                 new_stock.last = 0
                 new_stock.price = 0
                 new_stock.save()
     stocks = Stock.objects.all()
     stocks = [item.symbol for item in stocks]
     return stocks
Example #24
0
def test_bucket_sell_all():
    """
    Tests InvestmentBucket._sell_all()
    """
    user1 = User.objects.create(username='******', password="******")
    stock1 = Stock(name="Name1X", ticker="TKRC")
    stock1.save()
    DailyStockQuote(date="2016-06-10", value=100.0, stock=stock1).save()
    bucket = InvestmentBucket(name="Bucket1",
                              public=True,
                              owner=user1.profile,
                              available=10)
    bucket.save()
    cfg1 = InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=bucket,
        start="2016-06-06",
        end="2016-06-08",
    )
    cfg2 = InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=bucket,
        start="2016-06-08",
    )
    cfg1.save()
    cfg2.save()
    # pylint: disable=protected-access
    bucket._sell_all()
    # pylint: enable=protected-access
    bucket.refresh_from_db()
    cfg1.refresh_from_db()
    cfg2.refresh_from_db()
    assert bucket.available == 110
    assert cfg1.end == datetime.date(2016, 6, 8)
    assert cfg2.end is not None
Example #25
0
def test_bucket_change_config():
    """
    Tests InvestmentBucket.change_config()
    """
    cfg_str = namedtuple("cfg_str", ["id", "quantity"])
    user1 = User.objects.create(username='******', password="******")
    stock1 = Stock(name="Name1X", ticker="TKRC")
    stock1.save()
    DailyStockQuote(date="2016-06-10", value=100.0, stock=stock1).save()
    bucket = InvestmentBucket(name="Bucket1",
                              public=True,
                              owner=user1.profile,
                              available=10)
    bucket.save()
    cfg1 = InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=bucket,
        start="2016-06-06",
        end="2016-06-08",
    )
    cfg2 = InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=bucket,
        start="2016-06-08",
    )
    cfg1.save()
    cfg2.save()
    with pytest.raises(Exception):
        bucket.change_config([cfg_str(id=stock1.id, quantity=2)])
    bucket.available = 1000
    bucket.change_config([cfg_str(id=stock1.id, quantity=2)])
    bucket.refresh_from_db()
    assert bucket.available == 900
    assert bucket.stocks.filter(end=None).values('stock_id').annotate(
        sum_q=Sum('quantity')).get()['sum_q'] == 2
Example #26
0
def test_stocks_trade_buy(api_client, get_or_create_token):
    """
    Buy stocks.
    """
    # setup sample stock
    starting_units_available = 100
    apple = Stock(
            name='Apple', unit_price=5.00,
            units_available=starting_units_available
        )
    apple.save()
    # make sure user doesn't have this stock yet in inventory
    with pytest.raises(UserStock.DoesNotExist):
        _ = UserStock.objects.get(stock=apple)
    # build request json data
    data = dict(
            transaction_type='buy',
            stock_id=apple.id,
            quantity=5
        )
    # call endpoint
    url = '/stocks/trade/'
    api_client.credentials(HTTP_AUTHORIZATION='Token %s' % get_or_create_token)
    response = api_client.post(
            url, json.dumps(data), content_type="application/json"
        )
    # test response
    assert response.status_code == 201
    rjson = response.json()
    assert rjson['message'][:9] == 'Thank you'
    # test product inventory
    user = User.objects.get(username='******')
    user_stock = UserStock.objects.get(user=user, stock=apple)
    assert user_stock.total_units == data['quantity']
    # test available stock units
    apple = Stock.objects.get(name='Apple')
    assert apple.units_available == starting_units_available - data['quantity']
Example #27
0
 def to_python(self, value):
     out = []
     if not value:
         return out
     symbols = value.split(",")
     if not len(set(symbols)) == len(symbols):
         raise ValidationError("There was a duplicate stock!")
     for i in symbols:
         # TODO: This shouldn't be written like this. This is ridiculous.
         s = Stock.objects.filter(symbol=i)
         if s:
             s = s[0]
         else:
             # If a stock doesn't exist in the database already, create it silently.
             s = Stock(symbol=i)
             try:
                 s.update()
             # Unless it's not real...
             except StockAPIError:
                 raise ValidationError
             # Do I really need this line?
             s.save()
         out.append(s)
     return out
Example #28
0
    def parse_pages(self, page_collection):
        for page_object in page_collection.find({"archivedAt": ""}):
            parsed_page = html.fromstring(page_object["page"])
            price = parsed_page.xpath(self.XPATH_PRICE)[0]
            name = parsed_page.xpath(self.XPATH_NAME)[0]
            self.stdout.write("price: {}, name: {}".format(price, name))

            # Create new stock:
            company = Company.objects.get(name=name)
            stock = Stock(price=price,
                          company=company,
                          pub_date=page_object["createdAt"])
            stock.save()

            # Archive page:
            page_collection.find_one_and_update(
                {"_id": ObjectId(page_object["_id"])},
                {"$set": {
                    "archivedAt": now()
                }},
                upsert=True)

            # Update company:
            self.update_company(company)
Example #29
0
def test_stocks_trade_sell_insufficient_inventory(api_client,
                                                  get_or_create_token):
    """
    Selling, insufficient inventory.
    """
    # setup sample stock and inventory
    apple = Stock(name='Apple', unit_price=5.00, units_available=100)
    apple.save()
    user = User.objects.get(username='******')
    user_stock = UserStock(user=user, stock=apple, total_units=4)
    user_stock.save()
    # build request json data
    data = dict(transaction_type='sell', stock_id=apple.id, quantity=5)
    # call endpoint
    url = '/stocks/trade/'
    api_client.credentials(HTTP_AUTHORIZATION='Token %s' % get_or_create_token)
    response = api_client.post(url,
                               json.dumps(data),
                               content_type="application/json")
    # test response
    assert response.status_code == 200
    rjson = response.json()
    assert rjson['message'] == 'You only have %s %s(s) in your inventory' % (
        user_stock.total_units, apple.name)
Example #30
0
#Run this script to auto add all stocks to the database
#Needs to run in django shell
#(python manage.py shell) & copy and paste this in
from stocks.models import Stock
with open('NASDAQ.txt', 'r') as f:
    for line in f:
        c_line = line.strip()
        if c_line:
            entry = Stock(slug=c_line)
            entry.save()