Пример #1
0
def display_index(request, index_name=None):
    user = get_or_create_user(request)
    index = None

    if index_name:
        try:
            index = Index.objects.get(name=index_name.upper())
        except Index.DoesNotExist:
            raise BadRequestException(
                "Index does not exist: '{}'".format(index_name))
    else:
        indexes = Index.objects.filter(user=user)
        if not indexes:
            return mattermost_text("You do not have any indexes.\n\t" +
                                   "\n\t".join([p.name for p in indexes]))
        elif len(indexes) == 1:
            index = indexes[0]
        else:
            return mattermost_text(
                "You have multiple indexes. Specify the index you want to view.\n\t"
                + "\n\t".join([p.name for p in indexes]))

    aggregator = Aggregator(index)

    return print_index(index, aggregator, index.user == user)
Пример #2
0
def rename_index(index, parts):
    if not parts:
        raise BadRequestException("Usage: /index rename [newname]")

    # Check index name
    name = parts[0].upper()
    valid_index_name(name)

    try:
        existing_index = Index.objects.get(name=name)
        if existing_index.user_id == user.id:
            raise BadRequestException(
                "Your index is already named {}".format(name))
        else:
            raise BadRequestException(
                "{} already exists and belongs to {}".format(
                    name, existing_index.user.name))
    except Index.DoesNotExist:
        # Rename the user's current index name
        pass

    index.name = name
    index.save()

    return mattermost_text("Index renamed to {}".format(name))
Пример #3
0
def stock_info(request):
    symbol = request.POST.get('text', None)

    if not symbol:
        raise BadRequestException("No stock was specified")

    fundamentals = Stock.Fundamentals.get(symbol)
    response = fundamentals.description if fundamentals else 'Stock was not found'
    return mattermost_text(response)
Пример #4
0
def print_index(index, aggregator, is_owner=True):
    quotes = aggregator.quotes()

    assets = index.asset_set.all()
    for a in assets:
        a.instrument_object = aggregator.get_instrument(a.identifier)
    total_value = sum([asset_value(quotes, a) for a in assets])

    asset_str = assets_table(assets, quotes, total_value, is_owner)

    index_str = index.name
    if is_owner:
        index_str += " (${:,.2f}):".format(total_value)
    index_str += "\n\n{}".format(asset_str)

    return mattermost_text(index_str)
Пример #5
0
def rename_index(index, new_index_name):
    validate_index_name(new_index_name)

    try:
        existing_index = Index.objects.get(name=new_index_name)
        if existing_index.user_id == user.id:
            raise BadRequestException(
                "You already have an index named {}".format(new_index_name))
        else:
            raise BadRequestException(
                "{} already exists and belongs to {}".format(
                    new_index_name, existing_index.user.name))
    except Index.DoesNotExist:
        pass

    index.name = new_index_name
    index.save()

    return mattermost_text("Index renamed to {}".format(new_index_name))
Пример #6
0
    def process_exception(self, request, exception):
        if isinstance(exception, BadRequestException):
            status = 400
        elif isinstance(exception, ConfigurationException):
            status = 401
        elif isinstance(exception, ApiForbiddenException) or isinstance(
                exception, ForbiddenException):
            status = 403
        elif isinstance(exception, NotFoundException):
            status = 404
        elif isinstance(exception, NotAcceptableException):
            status = 406
        else:
            raise (exception)

        if request.method == 'POST':
            # Return a JSON message for Mattermost requests
            return mattermost_text(str(exception))
        else:
            return HttpResponse(str(exception), status=status)
Пример #7
0
def delete_index(index):
    index.delete()
    return mattermost_text("{} deleted.".format(index.name))
Пример #8
0
def index_action(request):
    body = request.POST.get('text', None)
    parts = re.split('[,\s]+', body)
    # Remove empty parts
    parts = [p for p in parts if p.strip()]
    if not parts:
        return display_index(request, None)

    command = parts[0]
    parts.pop(0)

    should_remove = False

    user = get_or_create_user(request)

    if command.lower() not in INDEX_COMMANDS:
        if re.match(INDEX_NAME_PATTERN, command):
            try:
                return display_index(request, command)
            except BadRequestException:
                raise BadRequestException(
                    f"Unknown command or index: '{command}'\n{GENERAL_USAGE_STR}"
                )
        else:
            raise BadRequestException(GENERAL_USAGE_STR)

    command = command.lower()

    if command == 'create':
        return create_index(user, parts)

    user_indexes = Index.objects.filter(user=user)

    if len(user_indexes) == 0:
        raise BadRequestException(
            f"You do not have any indexes. You must create an index to use the {command} command."
        )

    if len(user_indexes) == 1:
        index = user_indexes[0]
        if parts and parts[0].upper() == index.name:
            # The index name was provided unnecessarily, simply ignore it
            parts.pop(0)
    elif is_valid_index_name(parts[0]):
        try:
            index = next(i for i in user_indexes if i.name == parts[0].upper())
        except StopIteration:
            raise BadRequestException(
                f"You do not have an index named '{parts[0].upper()}'")
        parts.pop(0)
    else:
        return mattermost_text(
            "You have multiple indexes. You must specify the index you want to modify.\n\t"
            + "\n\t".join([p.name for p in user_indexes]))

    if command == 'rename':
        return rename_index(index, parts[0].upper())

    if command == 'destroy':
        if parts and parts[0].upper() != index.name:
            raise BadRequestException(
                f"You do not have an index named '{parts[0].upper()}'")
        return delete_index(index)

    if command == 'remove':
        should_remove = True

    if not parts:
        # This is an add/remove command, but no parts have been specified
        usage_str = (
            "Usage: /index {0} [asset1] [asset2]..." + "\nExamples:" +
            "\n\t/index {0} AAPL ({0} a single share of AAPL)" +
            "\n\t/index {0} MSFT:5 ({0} five shares of MSFT)" +
            "\n\t/index {0} AAPL:2 MSFT:3 ({0} two shares of AAPl and three shares of MSFT)"
            +
            "\n\t/index {0} AMZN$2000C@7/20 ({0} AMZN $2000 call option expiring July 20)"
            +
            "\n\t/index {0} AAPL180P8-31-20 ({0} AAPL $180 put option expiring August 31, 2020)"
            +
            "\n\t/index {0} MSFT200C ({0} MSFT $200 put option expiring end of this week)"
            +
            "\n\t/index {0} MSFT200.5C:10 ({0} ten MSFT $200.50 put options expiring end of this week)"
        )

        raise BadRequestException(usage_str.format(command))

    return update_index(index, parts, should_remove=should_remove)