Esempio n. 1
0
    def test_get_stock_info(self):
        response = stock_api.get_stock_info(self.stock_object['symbol'])
        self.assertIsNotNone(response)
        self.assertEqual(response['symbol'], self.stock_object['symbol'])

        with self.assertRaises(Exception):
            response = stock_api.get_stock_info("")
Esempio n. 2
0
def single_stock(request, symbol):
    try:
        data = stock_api.get_stock_info(symbol)
    except Exception:
        data = -1
    try:
        recs_data = stock_api.get_analyst_recommendations(symbol)
        rec = recs_data[0]
        try:
            rec['corporateActionsAppliedDate'] = datetime.fromtimestamp(
                (rec['corporateActionsAppliedDate'] /
                 1000.0)).strftime("%Y-%m-%d")
        except TypeError:
            rec['corporateActionsAppliedDate'] = "Unavailable"
    except Exception as e:
        rec = -1
    favorite = []
    if request.user.is_authenticated:
        try:
            favorite = FavoriteStock.objects.get(
                user_id=request.user.id).stocks.values_list('symbol',
                                                            flat=True).all()
        except Exception as e:
            pass
    is_favorite = True if symbol in favorite else False
    return render(
        request,
        'single_stock.html',
        {
            'page_title': 'Stock Page - %s' % symbol,
            'data': data,
            'rec': rec,
            'is_favorite': is_favorite
        },
    )
Esempio n. 3
0
def single_stock(request, symbol):
    """Returns stock's info and the related comments for this stock.

	**Template:**

	:template:'myapp/templates/signle_stock.html'
	"""

    with open('myapp/static/currencies.json', 'r') as f:
        currency_json_obj = json.load(f)

    data = stock_api.get_stock_info(symbol)
    comments = Comment.objects.filter(stock_id=symbol)

    #Getting stock's currency
    currency = currency_json_obj[symbol]
    #adding currency key to data
    data['currency'] = currency

    return render(
        request, 'single_stock.html', {
            'page_title': 'Stock Page - %s' % symbol,
            'data': data,
            'comments': comments
        })
Esempio n. 4
0
def single_stock(request, symbol):
    data = stock_api.get_stock_info(symbol)
    print(data['change'])
    return render(request, 'single_stock.html', {
        'page_title': 'Stock Page - %s' % symbol,
        'data': data
    })
Esempio n. 5
0
def update_existing_stocks():
    s = WatchedStock.objects.all().values("stock_id").distinct()
    for w in s:
        stock = Stock.objects.all().filter(symbol=w.get('stock_id'))[0]
        if (datetime.now(stock.last_modified.tzinfo) - stock.last_modified).total_seconds() > 5:
            data = stock_api.get_stock_info(stock.symbol)
            Stock.objects.filter(symbol=stock.symbol).update(
                name=data['companyName'],
                top_rank=None,
                price=data['latestPrice'],
                change=data['change'],
                change_percent=data['changePercent'],
                market_cap=data['marketCap'],
                last_modified=datetime.now(stock.last_modified.tzinfo))
Esempio n. 6
0
def update_bought_stocks():
    needed_bought_stocks = list(BoughtStock.objects.exclude(sold_quantity=F("quantity")))
    unneeded_bought_stocks_to_preserve = list(BoughtStock.objects.filter(sold_quantity=F("quantity")).order_by(
        "-created_on")[:MAX_UNNEEDED_HISTORY_TO_PRESERVE_IN_PORTFOLIO])
    for bought_stock in needed_bought_stocks + unneeded_bought_stocks_to_preserve:
        data = stock_api.get_stock_info(bought_stock.stock.symbol)
        Stock.objects.filter(symbol=bought_stock.stock.symbol).update(
            name=data['companyName'],
            top_rank=None,
            price=data['latestPrice'],
            change=data['change'],
            change_percent=data['changePercent'],
            market_cap=data['marketCap'],
            last_modified=datetime.now(bought_stock.stock.last_modified.tzinfo))
Esempio n. 7
0
def change_threshold_rule():
    rules = ChangeThresholdRule.get_rules()
    for rule in rules:
        if not rule.fired:
            data = stock_api.get_stock_info(
                symbol=rule.watched_stock.stock.symbol,
                filter=("changePercent", ))
            if "changePercent" in data:
                if rule.when == "B" and rule.percentage_threshold > data[
                        'changePercent']:
                    title = f"Below Threshold value Reached for {rule.watched_stock.stock}"
                    description = f"the change value percentage " \
                                  f"{round(data['changePercent'])}% reached below the threshold" \
                                  f" {rule.percentage_threshold}%"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
                elif rule.when == 'A' and rule.percentage_threshold < data[
                        'changePercent']:
                    title = f"Above Threshold value Reached for {rule.watched_stock.stock.name}"
                    description = f"the change value percentage " \
                                  f"{round(data['changePercent'])}% reached above the threshold" \
                                  f" {rule.percentage_threshold}%"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
                elif rule.when == 'O' and rule.percentage_threshold == data[
                        'changePercent']:
                    title = f"On Threshold value Reached for {rule.watched_stock.stock.name}"
                    description = f"the change value percentage reached the threshold" \
                                  f" {rule.percentage_threshold}%"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
Esempio n. 8
0
def single_stock(request, symbol):
    context = {}
    profile = None
    status_code = 200
    template = 'single_stock.html'
    try:
        # budget
        if request.user.is_authenticated:
            profile, create = Profile.objects.get_or_create(user=request.user)
            budget = profile.portfolio.budget
        else:
            budget = 0
        data = stock_api.get_stock_info(symbol)
        stock = Stock.objects.filter(symbol=symbol)[:1]
        if request.user.is_authenticated:
            profile, created = Profile.objects.get_or_create(user=request.user)
    except StockSymbolNotFound as e:
        status_code = 404  # stock symbol not found!
        context = {'error_message': e.message, "status_code": status_code}
        template = "exception.html"
    except StockServerUnReachable as e:
        status_code = 503  # Service Unavailable code
        context = {'error_message': e.message, "status_code": status_code}
        template = "exception.html"
    except Exception as e:
        status_code = 520  # Unknown Error
        context = {
            'error_message':
            "Unknown Error occurred: {}".format(", ".join(e.args)),
            "status_code": status_code
        }
        template = "exception.html"
    else:
        context = {
            'page_title': 'Stock Page - %s' % symbol,
            'data': data,
            'stock': stock,
            'profile': profile,
            'budget': budget
        }
    finally:
        response = render(request, template, context)
        response.status_code = status_code
        return response
Esempio n. 9
0
def price_threshold_rule():
    rules = PriceThresholdRule.get_rules()
    for rule in rules:
        if not rule.fired:
            data = stock_api.get_stock_info(
                symbol=rule.watched_stock.stock.symbol,
                filter=("latestPrice", ))
            if "latestPrice" in data:
                if rule.when == "B" and rule.price_threshold > data[
                        'latestPrice']:
                    title = f"Below Threshold value Reached for {rule.watched_stock.stock.name}"
                    description = f"the price value {data['latestPrice']} reached below the threshold" \
                                  f" {rule.price_threshold}"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
                elif rule.when == 'A' and rule.price_threshold < data[
                        'latestPrice']:
                    title = f"Above Threshold value Reached for {rule.watched_stock.stock.name}"
                    description = f"the price value {data['latestPrice']} reached above the threshold" \
                                  f" {rule.price_threshold}"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
                elif rule.when == 'O' and rule.price_threshold == data[
                        'latestPrice']:
                    title = f"On Threshold value Reached for {rule.watched_stock.stock.name}"
                    description = f"the price value reached the threshold" \
                                  f" {rule.price_threshold}"
                    Notification.objects.create(
                        user=rule.watched_stock.profile,
                        title=title,
                        description=description,
                        stock=rule.watched_stock.stock)
                    rule.fired = True
                    rule.save()
Esempio n. 10
0
    def check_stock_price(self):
        #testing notification system

        data = stock_api.get_stock_info(self.symbol)
        latest_price = int(data['latestPrice'])
        previous_close = int(data['previousClose'])

        difference = round(
            abs(((previous_close - latest_price) / previous_close) * 100), 2)

        if previous_close > latest_price:
            message = self.symbol + " Stock's price decreased by " + str(
                difference) + " %"
            self.save_notification(self.symbol, message)

        elif previous_close < latest_price:
            message = self.symbol + " Stock's price increased by " + str(
                difference) + " %"
            self.save_notification(self.symbol, message)
Esempio n. 11
0
def getNotifications(request, username):
    stocks = FavoriteStocks.objects.filter(username=username).values(
        'username', 'stock')

    #Notifications.objects.create(stock="goog", type="down")
    # notificatins_list=[]
    # data_notification = {}
    data = []

    # json_data = json.dumps(data_notification)

    for stock in list(stocks):

        stock_info = stock_api.get_stock_info(stock['stock'])
        if stock_info['change'] > 0:
            n = Notifications(str(stock['stock']), "up")

            # new1=Notifications(stock="asd",type="up")
            # new1.save(force_insert=False,force_update=False,using=None,update_fields=None)

            print(str(stock['stock']) + "up")

            conn = sqlite3.connect('db.sqlite3')
            cur = conn.cursor()
            cur.execute(
                'INSERT INTO myapp_notifications (stock, type) values (?, ?)',
                (n.stock, n.type))
            conn.commit()
            #n.save(force_insert=False,force_update=False,using=None,update_fields=None)
            data.append({"stock": n.stock, "type": n.type})

        if stock_info['change'] < 0:

            print(str(stock['stock']) + "down")
            n = Notifications(str(stock['stock']), "down")
            data.append({"stock": n.stock, "type": n.type})

# pick = pickle.dump(n)

    print(data)
    json_data = json.dumps(data)
    print(json_data)
    return JsonResponse(data, safe=False)
Esempio n. 12
0
 def buy_stock(self, symbol, curPrice, quantity=1, threshold=None):
     if quantity > 0:
         try:
             stock = Stock.objects.get(symbol=symbol)
         except Stock.DoesNotExist:
             data = stock_api.get_stock_info(symbol)
             stock = Stock.add_to_db(data)
         amount = quantity * curPrice
         if amount <= self.budget:
             BoughtStock.objects.create(portfolio=self,
                                        stock=stock,
                                        quantity=quantity,
                                        expense_price=amount,
                                        budget_left=(self.budget - amount),
                                        threshold=threshold)
             self.budget -= amount
             self.save()
         else:
             raise InAdequateBudgetLeft()
     else:
         raise InvalidQuantityValue()
Esempio n. 13
0
def watchlist_add_view(request, symbol):
    status_code = 200
    profile, created = Profile.objects.get_or_create(user=request.user)
    stock_in_db = Stock.objects.filter(symbol=symbol)[:1]
    if stock_in_db.exists():
        Stock.add_to_watchlist(profile, symbol)
        response = HttpResponse('OK')
    else:
        try:
            data = stock_api.get_stock_info(symbol)
            Stock.add_to_db(data)
            Stock.add_to_watchlist(profile, symbol)
            response = HttpResponse('OK')
        except StockSymbolNotFound as e:
            status_code = 404
            response = HttpResponse('Symbol Not Found')
        except StockServerUnReachable as e:
            status_code = 503
            response = HttpResponse('Service Unavailable')
        except Exception as e:
            status_code = 520
            response = HttpResponse('Unknown Error')
    response.status_code = status_code
    return response
Esempio n. 14
0
def trade(request):
    content = {'user': request.user}
    stock_list = stock_api.get_all_stocks()
    content.update({'stock_list': stock_list})

    params = request.GET
    user = request.user
    if "buy" in params or "sell" in params:
        user_profile = models.UserProfile.objects.get(user=user)
        if user.is_authenticated:

            try:
                print(int(params['number_of_stocks']))
                print(int(params['number_of_stocks'][0]))
                number_of_stocks = int(params["number_of_stocks"][0])
                if number_of_stocks <= 0:
                    raise Exception
                stock_info = stock_api.get_stock_info(params["stock_selector"])
                stock_price = float(stock_info['latestPrice'])
            except Exception:
                content.update({"error": "Error in input data"})
                return render(request, 'trade.html', content)

            stock_symbol = stock_info["symbol"]
            price = stock_price * number_of_stocks
            if 'buy' in params:
                if user_profile.balance >= stock_price * number_of_stocks:
                    t = models.Transaction.objects.create(user_id=models.UserProfile.objects.get(user=request.user),
                                                          stock_symbol=stock_symbol,
                                                          trans_date=datetime.now(),
                                                          buy_or_sell=0,
                                                          quantity=number_of_stocks,
                                                          price=price)
                    t.save()
                    user_profile.balance -= price
                    if stock_symbol in user_profile.stocks:
                        user_profile.stocks[stock_symbol] += number_of_stocks
                    else:
                        user_profile.stocks[stock_symbol] = number_of_stocks
                    user_profile.save()
                    content.update({'success': f'You have bought {number_of_stocks} {stock_symbol} for a price {price}'
                                               f'\n your current balance is: {user_profile.balance}'})

                else:
                    content.update({"error": "not enough balance"})
                    return render(request, 'trade.html', content)

            elif 'sell' in params:
                available_stocks = models.UserProfile.objects.get(user=request.user).stocks[stock_symbol]
                if available_stocks >= number_of_stocks:
                    t = models.Transaction.objects.create(user_id=models.UserProfile.objects.get(user=request.user),
                                                          stock_symbol=stock_symbol,
                                                          trans_date=datetime.now(),
                                                          buy_or_sell=1,
                                                          quantity=number_of_stocks,
                                                          price=price)
                    t.save()

                    user_profile.stocks[stock_symbol] -= number_of_stocks

                    user_profile.save()

                    content.update({'success': f'You have sold {number_of_stocks} for a price {price}'
                                               f'\n your current balance is: {user_profile.balance}'})
                else:
                    content.update({"error": "not enough stocks"})
        else:
            return redirect('login')




    rendered_page = render(request, 'trade.html', content)
    return rendered_page
Esempio n. 15
0
 def test_get_stock_info(self):
     for symbol in self.not_existed_symbols:
         self.assertRaises(StockSymbolNotFound, get_stock_info, symbol)
     for symbol in self.existed_symbols:
         response = get_stock_info(symbol)
         self.assertIsInstance(response, dict)
Esempio n. 16
0
def get_stock_price(stock_symbol):

    stock_info = stock_api.get_stock_info(stock_symbol)
    stock_price = float(stock_info['latestPrice'])
    return stock_price
Esempio n. 17
0
 def test_service_is_up(self):
     try:
         get_stock_info(self.existed_symbols[0])
     except StockServerUnReachable as e:
         raise AssertionError(e)
Esempio n. 18
0
def stock_info(request, symbol):
    return JsonResponse(
        {'price': stock_api.get_stock_info(symbol)['latestPrice']})