Beispiel #1
0
def portfolio(request, portfolio_pk):

    portfolio = Portfolio.objects.get(pk=portfolio_pk)
    check_ownership(request, portfolio)
    stock_not_found = False

    quote_name = request.POST.get('quote', None)
    if quote_name:
        quote_name = quote_name.upper()
        answer = ystockquote.get(quote_name)
        if answer["stock_exchange"] != '"N/A"':
            try:
                stock = Stock.objects.get(name=quote_name)
            except Stock.DoesNotExist:
                stock = Stock.objects.create(
                    name=quote_name,
                    stock_exchange=answer['stock_exchange'],
                    market_cap=convert_number(answer['market_cap']),
                    last_price=convert_number(answer['price']))
            PortfolioStock.objects.get_or_create(stock=stock,
                                                 portfolio=portfolio)
        else:
            stock_not_found = True

    stocks = PortfolioStock.objects.filter(
        portfolio=portfolio).order_by("-stock__value_score")

    operations = Operation.objects.filter(
        portfolio_stock__portfolio=portfolio)[0:10]

    total_value, total_spent, profit = portfolio.balance_sheet()
    if total_spent != 0:
        profit_purcent = round(profit / total_spent * 100, 2)
    else:
        profit_purcent = 0

    total_cash_value = total_value + portfolio.cash

    c = {
        'quote_name': quote_name,
        'stock_not_found': stock_not_found,
        'portfolio': portfolio,
        'stocks': stocks,
        'operations': operations,
        'total_value': total_value,
        'total_spent': total_spent,
        'profit': profit,
        'profit_purcent': profit_purcent,
        'total_cash_value': total_cash_value,
    }
    c.update(csrf(request))

    return render_to_response('portfolio.html', c)
Beispiel #2
0
def portfolio(request, portfolio_pk):

    portfolio = Portfolio.objects.get(pk=portfolio_pk)
    check_ownership(request, portfolio)
    stock_not_found = False

    quote_name = request.POST.get('quote', None)
    if quote_name:
        quote_name = quote_name.upper()
        answer = ystockquote.get(quote_name)
        if answer["stock_exchange"] != '"N/A"':
            try:
                stock = Stock.objects.get(name=quote_name)
            except Stock.DoesNotExist:
                stock = Stock.objects.create(
                    name=quote_name,
                    stock_exchange=answer['stock_exchange'],
                    market_cap=convert_number(answer['market_cap']),
                    last_price=convert_number(answer['price'])
                )
                PortfolioStock.objects.get_or_create(stock=stock,
                    portfolio=portfolio)
        else:
            stock_not_found = True

    stocks = PortfolioStock.objects.filter(portfolio=portfolio).order_by("-stock__value_score")

    operations = Operation.objects.filter(portfolio_stock__portfolio=portfolio)[0:10]

    total_value, total_spent, profit = portfolio.balance_sheet()
    if total_spent != 0:
        profit_purcent = round(profit / total_spent * 100, 2)
    else:
        profit_purcent = 0

    total_cash_value = total_value + portfolio.cash

    c = {
        'quote_name': quote_name,
        'stock_not_found': stock_not_found,
        'portfolio':portfolio,
        'stocks': stocks,
        'operations':operations,
        'total_value':total_value,
        'total_spent':total_spent,
        'profit':profit,
        'profit_purcent':profit_purcent,
        'total_cash_value':total_cash_value,
    }
    c.update(csrf(request))

    return render_to_response('portfolio.html', c)
Beispiel #3
0
def update_shares(request, portfolio_pk):

    portfolio = Portfolio.objects.get(pk=portfolio_pk)
    check_ownership(request, portfolio)
    pstocks = PortfolioStock.objects.filter(portfolio=portfolio)
    for pstock in pstocks:
        stock = pstock.stock
        answer = ystockquote.get(stock.name)
        stock.last_price = convert_number(answer['price'])
        stock.price_sales_ratio = convert_number(answer['price_sales_ratio'])
        stock.dividend_yield = convert_number(answer['dividend_yield'])

        stock.save()
    return http.HttpResponseRedirect('..')
Beispiel #4
0
def update_shares(request, portfolio_pk):

    portfolio = Portfolio.objects.get(pk=portfolio_pk)
    check_ownership(request, portfolio)
    pstocks = PortfolioStock.objects.filter(portfolio=portfolio)
    for pstock in pstocks:
        stock = pstock.stock
        answer = ystockquote.get(stock.name)
        stock.last_price = convert_number(answer['price'])
        stock.price_sales_ratio = convert_number(answer['price_sales_ratio'])
        stock.dividend_yield = convert_number(answer['dividend_yield'])

        stock.save()
    return http.HttpResponseRedirect('..')
Beispiel #5
0
    def get_quote(self):

        quote_name = self.edit.GetValue()
        answer = ystockquote.get(quote_name)

        if answer["stock_exchange"] == '"N/A"':
            wx.MessageBox("Quote name seems incorrect", "Info", wx.OK | wx.ICON_INFORMATION)
            self.edit.SetSelection(-1, -1)
            self.edit.SetFocus()
            return

        self.grid.SetCellValue(len(self.quotes), 0, quote_name)

        column = 0

        for col in self.column_definition:

            if col["name"] in answer:
                self.grid.SetCellValue(len(self.quotes), column, str(answer[col["name"]]))

            column = column + 1

        self.quotes.append({"name": quote_name})
Beispiel #6
0
def analyze_stock(pstock):

    days = 1000
    now = datetime.datetime.now()
    year_before = now - datetime.timedelta(days=days)

    stock = pstock.stock
    infos = ystockquote.get(stock.name)
    stock_analysis = StockAnalysis(infos)

    # update important fields
    stock.last_price = convert_number(infos['price'])
    stock.price_sales_ratio = convert_number(infos['price_sales_ratio'])
    stock.dividend_yield = convert_number(infos['dividend_yield'])

    historical_prices = ystockquote.legacy.get_historical_prices(stock.name,
        year_before.strftime('%Y%m%d'), now.strftime('%Y%m%d'))

    #[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos']
    history = []
    historical_prices = historical_prices[1:]
    has_history = True
    for p in historical_prices:
        # error index out of range here
        if(len(p) == 1):
            has_history = False
            break
        close_v = float(p[4])
        date = datetime.datetime.strptime(p[0],'%Y-%m-%d')
        history.append({"date":date, "close_value":close_v})

    price_trends = []
    volatilities = [
        {'days':100},
        {'days':300},
        {'days':600},
    ]
    if has_history:
        # today first
        history = sorted(history, key=lambda p: p['date'])
        assert history[1]['date'] > history[0]['date']

        for v in volatilities:
            if len(history) < v['days']:
                v['days'] = len(history)

            v['volatility'] = round(calculate_historical_volatility(history[-v['days']:]), 2)
            v['start_date'] = history[-v['days']:][0]['date']

        stock_analysis.volatility = volatilities[1]['volatility']
        stock.volatility = stock_analysis.volatility

        start = 0
        interval = int(len(history) / 5.0)
        while len(history) > (start + interval) and interval > 0:
            trend = calculate_historical_price_trend(history[start:start+interval])
            price_trends.append(trend)
            start = start + interval
            #if len(history) < (start + interval):
            #    interval = len(history) - start - 1

        trend = calculate_historical_price_trend(history)
        price_trends.append(trend)
        stock_analysis.trend = trend

    stock.value_score = stock_analysis.value_score_analysis()
    stock.save()

    return {
        'price_trends':price_trends,
        'stock':stock,
        'infos':infos,
        'volatilities':volatilities,
        'stock_analysis':stock_analysis,
        'days':days,
        'history': history
    }
Beispiel #7
0
def analyze_stock(pstock):

    days = 1000
    now = datetime.datetime.now()
    year_before = now - datetime.timedelta(days=days)

    stock = pstock.stock
    infos = ystockquote.get(stock.name)
    stock_analysis = StockAnalysis(infos)

    # update important fields
    stock.last_price = convert_number(infos['price'])
    stock.price_sales_ratio = convert_number(infos['price_sales_ratio'])
    stock.dividend_yield = convert_number(infos['dividend_yield'])

    historical_prices = ystockquote.legacy.get_historical_prices(
        stock.name, year_before.strftime('%Y%m%d'), now.strftime('%Y%m%d'))

    #[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos']
    history = []
    historical_prices = historical_prices[1:]
    has_history = True
    for p in historical_prices:
        # error index out of range here
        if (len(p) == 1):
            has_history = False
            break
        close_v = float(p[4])
        date = datetime.datetime.strptime(p[0], '%Y-%m-%d')
        history.append({"date": date, "close_value": close_v})

    price_trends = []
    volatilities = [
        {
            'days': 100
        },
        {
            'days': 300
        },
        {
            'days': 600
        },
    ]
    if has_history:
        # today first
        history = sorted(history, key=lambda p: p['date'])
        assert history[1]['date'] > history[0]['date']

        for v in volatilities:
            if len(history) < v['days']:
                v['days'] = len(history)

            v['volatility'] = round(
                calculate_historical_volatility(history[-v['days']:]), 2)
            v['start_date'] = history[-v['days']:][0]['date']

        stock_analysis.volatility = volatilities[1]['volatility']
        stock.volatility = stock_analysis.volatility

        start = 0
        interval = int(len(history) / 5.0)
        while len(history) > (start + interval) and interval > 0:
            trend = calculate_historical_price_trend(history[start:start +
                                                             interval])
            price_trends.append(trend)
            start = start + interval
            #if len(history) < (start + interval):
            #    interval = len(history) - start - 1

        trend = calculate_historical_price_trend(history)
        price_trends.append(trend)
        stock_analysis.trend = trend

    stock.value_score = stock_analysis.value_score_analysis()
    stock.save()

    return {
        'price_trends': price_trends,
        'stock': stock,
        'infos': infos,
        'volatilities': volatilities,
        'stock_analysis': stock_analysis,
        'days': days,
        'history': history
    }