예제 #1
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()
예제 #2
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
예제 #3
0
def test_stock_create_new_stock():
    """
    Tests Stock.create_new_stock()
    """
    Stock.create_new_stock(ticker="ABC", name="DEF")
    with mock.patch.object(Fetcher, "__init__", side_effect=KeyError()):
        with pytest.raises(Exception):
            Stock.create_new_stock(ticker="ABC", name="DEF")
예제 #4
0
def generate_stocks(request):
    Stock.objects.all().delete()
    for i in xrange(20):
        s = Stock()
        s.ticker = ''.join(random.choice(string.uppercase) for x in xrange(random.randint(3, 4)))
        s.current_price = Decimal.from_float(random.triangular(0, 1000, 0)).quantize(Decimal('.01'))
        s.save()
    
    return HttpResponseRedirect(reverse('stocks.views.dashboard'))
예제 #5
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))
예제 #6
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
예제 #7
0
    def resolve_stock_find(_self, _info, text, first=None, **_args):
        """
        Finds a stock given a case insensitive name.
        (see :py:meth:`stocks.models.Stock.find_stock`)

        :param text: The text the user want to search for.
        :type name: str.
        :param first: The maximum number of results to return
        :type name: int.
        :returns: :py:class:`django.db.models.query.QuerySet` of :py:class:`stocks.stocks.Stock`
        """
        if first:
            return Stock.find_stock(text, first)
        return Stock.find_stock(text)
예제 #8
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
예제 #9
0
def test_tradebucket_current_value():
    """
    Tests TradeBucket.current_value()
    """
    account = account_helper()

    value_of_stock1 = 3
    stock1 = Stock.create_new_stock(name="Name1X", ticker="TKRC")
    stock1.daily_quote.create(value=value_of_stock1, date="2016-06-03")

    invest_bucket = InvestmentBucket(name="Bucket Test",
                                     public=True,
                                     owner=account.profile,
                                     available=1)
    invest_bucket.save()
    InvestmentStockConfiguration(
        quantity=1,
        stock=stock1,
        bucket=invest_bucket,
        start="2016-07-11",
        end="2016-06-10",
    ).save()
    quantity = 4
    trade_bucket = TradeBucket(quantity=quantity,
                               account=account,
                               stock=invest_bucket)
    trade_bucket.save()
    assert trade_bucket.current_value() == -quantity
예제 #10
0
def test_investmentbucket_value_on():
    """
    Tests InvestmentBucket.value_on()
    """
    user = user_helper()

    value_of_stock1 = 3
    stock = Stock.create_new_stock(name="Name1X", ticker="TKRC")
    stock.daily_quote.create(value=value_of_stock1, date="2016-06-03")
    available = 3
    bucket = InvestmentBucket(name="Bucket Test",
                              public=True,
                              owner=user.profile,
                              available=available)
    bucket.save()

    InvestmentStockConfiguration(
        quantity=1,
        stock=stock,
        bucket=bucket,
        start="2016-06-08",
        end="2016-06-10",
    ).save()

    assert bucket.value_on() == available
    assert bucket.value_on(date="2016-06-08") == available + value_of_stock1
    assert bucket.value_on(date="2016-07-19") == available
예제 #11
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)
예제 #12
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)
예제 #13
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
예제 #14
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
예제 #15
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()
예제 #16
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
예제 #17
0
def getStockCodeFromFile(filePath):
    f = open(filePath)           
    line = f.readline()             
    while line:
        a = re.findall("\S+\(\d{6}\)",line)
        for s in a:
            code = re.search("\(\d{6}\)",s)
            #print code.group(0)
            npos = s.index(code.group(0))
            #print s[0:npos].decode('utf-8')+"-"+s[npos+1:npos+7]
            sname =s[0:npos]
            scode = s[npos+1:npos+7]
            print sname+"_"+scode
            if Stock.objects.filter(code=scode).count()==0 :
                s = Stock(code=scode,name=sname.decode("gbk").encode("utf-8"),listDate=timezone.now(),marketType='sz')
                print sname+"("+scode+")"
                s.save()
        line = f.readline()
    f.close()
예제 #18
0
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()
예제 #19
0
def retrieve(request):
    stockname = request.POST['stockname']
    q = GoogleIntradayQuote(stockname, 300, 1)
    qlines = q.to_csv().strip().split("\n")
    if not qlines:
        e = "Couldn't find ", stockname, " data"
        return render(request, 'stocks/index.html', {'error_message': e})
    else:
        s = Stock(ticker=q.symbol,
                  start_date=timezone.now() - datetime.timedelta(days=1))
        s.save()
        for tick in q.get_ticks():
            print "tick: ", tick,
            dt = parse_datetime(tick[0])
            p = tick[1]
            print " price: ", p
            s.tick_set.create(time=dt, price=p)
        s.save()

        # tells the R plotting device to write the plot to a file
        f = "static/stocks/images/tmp.png"
        grdevices.png(file=f, width=512, height=512)

        # make a random plot
        rnorm = stats.rnorm
        df = {'value': rnorm(300, mean=0) + rnorm(100, mean=3),
              'other_value': rnorm(300, mean=0) + rnorm(100, mean=3),
              'mean': IntVector([0, ] * 300 + [3, ] * 100)}
        dataf_rnorm = robjects.DataFrame(df)

        gp = ggplot2.ggplot(dataf_rnorm)
        pp = gp + \
            ggplot2.aes_string(x='value', y='other_value') + \
            ggplot2.geom_bin2d() + \
            ggplot2.opts(title='geom_bin2d')
        pp.plot()

        grdevices.dev_off()

        context = {'stockname': stockname,
                   'history': qlines}
        return render(request, 'stocks/retrieve.html', context)
예제 #20
0
    def fill_missing_stock(self, stock_codes: Sequence[str]) -> None:
        existing_stock_codes = (Stock.objects.filter(
            exchange=self.__exchange,
            code__in=stock_codes).values_list('code', flat=True))

        missing_codes = set(stock_codes) - set(existing_stock_codes)
        if len(missing_codes) > 0:
            missing_stocks = map(
                lambda code: Stock.get_new_record(self.__exchange, code),
                missing_codes)
            Stock.objects.bulk_create(missing_stocks)
예제 #21
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)
예제 #22
0
 def handle(self, *args, **options):
     Stock.objects.all().delete()
     Prices.objects.all().delete()
     Financials.objects.all().delete()
     # Prices.objects.all().delete()
     print('======================')
     for i in range(3):
         S0 = Stock.create_stock()
         S0.add_n_prices(10)
         S0.get_full_info()
     print('======================')
예제 #23
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
예제 #24
0
def test_trading_trading_balance():
    """
    Testing available_cash for a Trading Account
    """
    account = account_helper()

    value_of_stock1 = 3
    stock1 = Stock.create_new_stock(name="Name1X", ticker="TKRC")
    stock1.daily_quote.create(value=value_of_stock1, date="2016-06-03")

    value_of_stock2 = 4
    quantity2 = 3
    stock2 = Stock.create_new_stock(name="Name2X", ticker="TKF")
    stock2.daily_quote.create(value=value_of_stock2, date="2016-06-03")
    TradeStock(quantity=1, account=account, stock=stock1).save()

    value = account.trading_balance()
    assert value == -value_of_stock1

    TradeStock(quantity=quantity2, account=account, stock=stock2).save()
    value = account.trading_balance()
    assert value == -value_of_stock1 + -value_of_stock2 * quantity2
예제 #25
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
예제 #26
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'
예제 #27
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']
예제 #28
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
예제 #29
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
예제 #30
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']
예제 #31
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
예제 #32
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)
예제 #33
0
def test_stock_trades_for_profile():
    """
    Tests Stock.trades_for_profile()
    """
    user1 = User.objects.create(username='******', password="******")
    user2 = User.objects.create(username='******', password="******")
    t1_1 = user1.profile.trading_accounts.create(account_name="u1t1")
    t1_2 = user1.profile.trading_accounts.create(account_name="u1t2")
    t2_1 = user2.profile.trading_accounts.create(account_name="u2t")
    stock = Stock.create_new_stock(name="Name1X", ticker="TKRC")
    TradeStock(quantity=1, account=t1_1, stock=stock).save()
    TradeStock(quantity=1, account=t1_2, stock=stock).save()
    TradeStock(quantity=1, account=t2_1, stock=stock).save()
    assert stock.trades_for_profile(user1.profile).count() == 2
    assert stock.trades_for_profile(user2.profile).count() == 1
예제 #34
0
for row in reader:
    #print(row)
    try:
        stock = Stock.objects.get(security=int(row.get('Security Code')))
        print(stock)
        populate_trades(stock)
    except Stock.DoesNotExist:
        industry = row.get('Industry', '').strip()
        if industry is not None and len(industry) > 0:
            industry = Industry.objects.get(name=industry)
        else:
            industry = None
        stock = Stock(security=int(row.get('Security Code')),
              sid = row.get('Security Id'),
              name = row.get('Security Name').strip(),
              group = row.get('Group').strip(),
              face_value = row.get('Face Value').strip(),
              isin = row.get('ISIN No').strip(),
              industry = industry)
        stock.save()
        print(stock)
        populate_trades(stock)
    except:
            print("Unexpected error:", sys.exc_info()[0])

fd.close()

print(len(Stock.objects.all()))