示例#1
0
def transaction_purchase_stock(portfolio_id: int, purchase_count: int,
                               purchase_date: str, stock_code: str):
    try:
        portfolio = Portfolios.objects.get(id=portfolio_id)
        # 해당날짜 가격 * 매입 수량
        purchase_price = StockPrice.objects.get(
            stocks_id=Stocks.objects.get(stock_code=stock_code).id,
            date=purchase_date).close_price * purchase_count
        # 남은 예수금으로 매입할 수 있는지 체크
        if portfolio.portfolio_deposit < purchase_price:
            raise TransactionError('매입금액이 예수금을 초과합니다.')

    except Portfolios.DoesNotExist:
        raise TransactionError('Invalid portfolio_id')
    except StockPrice.DoesNotExist:
        raise TransactionError('Price of stock is not saved')

    with transaction.atomic():
        # 구매 정보 입력
        PortfoliosDetail.objects.purchase(purchase_date, purchase_count,
                                          portfolio_id, stock_code)

        # 예수금 = 현재 예수금 - 매입금액
        Portfolios.objects.filter(id=portfolio_id).update(
            portfolio_deposit=portfolio.portfolio_deposit - purchase_price,
            update_date=today_dateformat(time_format='%Y-%m-%d'))

    return True
示例#2
0
    def _to_dict(self, scrap_data_list):
        result = []

        for data in scrap_data_list:
            year = today_dateformat('%Y')

            result.append({
                'date':
                '{}-{}'.format(year, data[0].replace('.', '-')),
                'foreign_total_own':
                int(escape_number(data[1])),
                'foreign_total_own_ratio':
                float(escape_char(data[2])),
                'foreign_purchase_volume':
                int(escape_number(data[3])),
                'company_purchase_volume':
                int(escape_number(data[4])),
                'closing_price':
                int(escape_number(data[5])),
                'compare_prev_day':
                str(escape_number(data[6])),
                'fluctuation_ratio':
                float(escape_char(data[7])),
            })

        return result
示例#3
0
    def __init__(self, start_date: str, end_date: str = None):
        """
        :param start_date: 시작날짜 (ex, 1991-01-01) (default : 1991-01-01)
        :param end_date: 종료날짜 (ex, 2020-01-01) (default : today)
        :type end_date: default None
        """
        plt.rcParams["font.family"] = 'NanumGothic'
        plt.rcParams['font.size'] = 15
        plt.rcParams["figure.figsize"] = (30, 20)
        plt.rcParams['lines.linewidth'] = 2
        plt.rcParams["axes.grid"] = True

        if len(start_date) == 4:
            self._start_date = start_date + '-01-01'
        elif len(start_date) == 7:
            self._start_date = start_date + '-01'
        else:
            self._start_date = start_date

        if end_date is None:
            self._end_date = today_dateformat(time_format = '%Y-%m-%d')
        else:
            self._end_date = end_date

        self._file_name = '{}_{}.png'.format(self._start_date, self._end_date)
示例#4
0
    def get(self, request, *args, **kwargs):
        """
        market 1:KOSPI / 2:KOSDAQ
        """
        market = self.kwargs.get('market', '1')

        return render(request, self.template_name, context = {
            'view_title'    : '{} 투자자 동향'.format({ '1': 'KOSPI', '2': 'KOSDAQ' }.get(market)),
            'market_name'   : { '1': 'KOSPI', '2': 'KOSDAQ' }.get(market),
            'date_condition': (current_day_subtract(30), today_dateformat(time_format = '%Y-%m-%d')),
        })
示例#5
0
    def handle(self, *args, **options):
        """
        python manage.py register_index KS11 all
        python manage.py register_index IXIC all
        python manage.py register_index DJI all
        python manage.py register_index US500 all
        """
        index_name = options['index'].upper()
        if options['date'] == 'all':
            start_date = '1970-01-01'
        else:
            start_date = today_dateformat(time_format='%Y-%m-%d')

        register(index_name, start_date)
示例#6
0
    def get(self, request, *args, **kwargs):
        try:
            stock_price = StockPrice.objects.values('close_price', 'high_price', 'low_price').get(
                stocks_id = Stocks.objects.get(stock_name = kwargs.get('stock_name')).id,
                date = today_dateformat('%Y-%m-%d')
            )

            return JsonResponse({
                'content': '[오늘 주가]\n시가 : {}\n고가 : {}\n저가 : {}'.format(stock_price['close_price'], stock_price['high_price'], stock_price['low_price'])
            }, status = 200)

        except Stocks.DoesNotExist:
            return JsonResponse({ 'content': '주식명을 확인해주세요.' }, status = 400)
        except StockPrice.DoesNotExist:
            return JsonResponse({ 'content': '해당 주식은 현재 주가를 추적중이지 않습니다.' }, status = 400)
        except Exception:
            print_exception()
            return JsonResponse({ 'content': '띠용? 에러 발생' }, status = 400)
示例#7
0
    def register(self, stocks_id: int, date: str, open_price: int,
                 high_price: int, low_price: int, close_price: int):
        try:
            self.get(date=date, stocks_id=stocks_id)

            if date == today_dateformat(time_format='%Y-%m-%d'):
                self.filter(date=date, stocks_id=stocks_id).update(
                    open_price=open_price,
                    high_price=high_price,
                    low_price=low_price,
                    close_price=close_price,
                )

        except StockPrice.DoesNotExist:
            self.create(date=date,
                        open_price=open_price,
                        high_price=high_price,
                        low_price=low_price,
                        close_price=close_price,
                        stocks_id=Stocks.objects.get(id=stocks_id))
示例#8
0
    def handle(self, *args, **options):
        """
        https://www.macroption.com/rsi-calculation/

        * RSI Calculation Formula
            RSI = 100 – 100 / ( 1 + RS )
            RS = Relative Strength = AvgU / AvgD
            AvgU = average of all up moves in the last N price bars
            AvgD = average of all down moves in the last N price bars
            N = the period of RSI
            There are 3 different commonly used methods for the exact calculation of AvgU and AvgD (see details below)

        * RSI Calculation Step by Step
            Calculate up moves and down moves (get U and D)
            Average the up moves and down moves (get AvgU and AvgD)
            Calculate Relative Strength (get RS)
            Calculate the Relative Strength Index (get RSI)
        """
        rsi_message, price_message = '', ''
        stock_list = StockSubs.objects.values('stocks_id__stock_name').all()

        for stock in stock_list:
            try:
                stock_name = stock['stocks_id__stock_name']
                price = StockPrice.objects.values('open_price', 'close_price', 'low_price', 'high_price').get(
                    stocks_id = Stocks.objects.get(stock_name = stock_name).id,
                    date = today_dateformat(time_format = '%Y-%m-%d')
                )
            except StockPrice.DoesNotExist:
                continue

            RSI = StockPrice.objects.current_rsi(stock_name)
            if RSI >= 60 or RSI <= 40:
                rsi_message += '[{}]  현재: {}   |   RSI : {}\n'.format(stock_name, format(price['close_price'], ',d'), RSI)

            price_condition = my_stock_price_condition(stock_name, price['close_price'])
            if price_condition:
                price_message += '[{}]  종목이  {}  이하로 내려왔습니다.\n'.format(stock_name, format(price_condition, ',d'))

        send_discord(rsi_message)
        send_discord(price_message)
示例#9
0
def current_date():
    return today_dateformat(time_format='%Y-%m-%d')