Exemplo n.º 1
0
def register_stock_financial_data(code):
    result = {
        'code': code,
        'StockFinancialData': [],
        'status': False,
    }
    try:
        # 情報取得
        detail = asset_scraping.yf_detail(code)
        profiles = asset_scraping.yf_profile(code, is_consolidated=True)
        if profiles['status'] and profiles['data'][0]['決算期'] is None:
            # 単体の情報を取得
            profiles = asset_scraping.yf_profile(code, is_consolidated=False)
        # stock情報
        stock = Stock.objects.get(code=code)
        # 今年度を含めて3年分
        for i in range(3):
            profile = profiles['data'][i]
            if not StockFinancialData.objects.filter(date=profile["決算発表日"], stock__code=code).exists():
                data = {
                    "stock": stock,
                    # profile
                    "date": profile["決算発表日"],
                    'equity': profile['自己資本'],
                    'equity_ratio': profile["自己資本比率"],
                    'capital': profile["資本金"],
                    'operating_income': profile["営業利益"],
                    'assets': profile["総資産"],
                    'recurring_profit': profile["経常利益"],
                    'net_income': profile["当期利益"],
                    'interest_bearing_debt': profile["有利子負債"],
                    'eps': profile["EPS(一株当たり利益)"],
                    'bps': profile["BPS(一株当たり純資産)"],
                    'sales': profile["売上高"],
                    'roa': profile["ROA(総資産利益率)"],
                    'roa_2': profile["総資産経常利益率"],
                    'roe': profile["ROE(自己資本利益率)"],
                }
                # 今年度分はdetail情報を利用
                if i == 0 and detail['status']:
                    data['market_value'] = detail['data']['financial_data']["時価総額"]
                    data['dividend_yield'] = detail['data']['financial_data']["配当利回り(会社予想)"]
                    data['bps_f'] = detail['data']['financial_data']["BPS(実績)"]
                    data['eps_f'] = detail['data']['financial_data']["EPS(会社予想)"]
                    data['pbr_f'] = detail['data']['financial_data']["PBR(実績)"]
                    data['per_f'] = detail['data']['financial_data']["PER(会社予想)"]
                # 保存
                logger.debug(data)
                sfd = StockFinancialData.objects.create(**data)
                result['StockFinancialData'].append(sfd)
        # status=Trueに設定
        result['status'] = True
    except Exception as e:
        print(e)
        logger.error(e)
        # status=Falseに設定
        result['status'] = False
    finally:
        return result
Exemplo n.º 2
0
 def profit(self):
     profit = 0
     orders = self.order_set.all()
     for o in orders:
         if o.is_buy:
             profit -= (o.num * o.val + o.commission)
         else:
             profit += (o.num * o.val - o.commission)
     if not self.is_closed:
         data = asset_scraping.yf_detail(self.stock.code)
         if data['status']:
             profit += data['data']['val'] * self.remaining()
     if profit > 0 and not self.is_nisa:
         profit = round(profit * 0.8)
     return profit
Exemplo n.º 3
0
def register_stock_value_data_alt(code):
    '''
    record_stock_value_data_alt
    :desc: yahooファイナンスからHLOCTを取得し、StockValueDataに格納
    :param code: 銘柄コード
    :return: StockValueDataの追加数等
    '''
    # for result
    counter = 0
    list_added = list()
    # main process
    data = asset_scraping.yf_detail(code)
    stock = Stock.objects.get(code=code)
    if data['status']:
        today = date.today()
        if StockValueData.objects.filter(stock=stock, date=today).__len__() == 0:
            counter += 1
            if stock.is_trust:
                s = StockValueData.objects.create(
                    stock=stock,
                    date=today,
                    val_open=data['data']['val']*10000,
                    val_high=data['data']['val']*10000,
                    val_low=data['data']['val']*10000,
                    val_close=data['data']['val']*10000,
                    turnover=data['data']['balance'],
                )
            else:
                s = StockValueData.objects.create(
                    stock=stock,
                    date=today,
                    val_open=data['data']['val_open'],
                    val_high=data['data']['val_high'],
                    val_low=data['data']['val_low'],
                    val_close=data['data']['val_close'],
                    turnover=data['data']['turnover'],
                )
            list_added.append(s.date.__str__())
            logger.info('StockValueData of {} are updated'.format(stock))
    result = {
        "counter": counter,
        "stock": {
            "name": stock.name,
            "code": stock.code,
        },
        "list": list_added,
    }
    return result
Exemplo n.º 4
0
def register_stock(code):
    result = {
        "code": code,
        "stock": None,
        "status": False
    }
    if Stock.objects.filter(code=code).exists():
        raise Exception('Already existing')
    try:
        yf_detail = asset_scraping.yf_detail(code)
        if yf_detail['status']:
            data = yf_detail['data']
            data.pop('financial_data')
            stock = Stock.objects.create(**data)
            result['stock'] = stock
            result['status'] = True
            logger.info("New stock object of {}".format(stock))
    except Exception as e:
        print(e)
        logger.error(e)
        result['status'] = False
    finally:
        return result
Exemplo n.º 5
0
def order(request):
    if request.method == "POST":
        try:
            with transaction.atomic():
                val = json.loads(request.body.decode())
                logger.info("request_json: {}".format(val))
                o = Order()
                o.datetime = val["datetime"]
                o.order_type = val["kind"]
                o.is_buy = True if o.order_type == "現物買" else False
                # Stocksにデータがない→登録
                if Stock.objects.filter(code=val["code"]).__len__() == 0:
                    stockinfo = asset_scraping.yf_detail(val["code"])
                    if stockinfo['status']:
                        stock = Stock()
                        stock.code = val["code"]
                        stock.name = stockinfo['data']['name']
                        stock.industry = stockinfo['data']['industry']
                        stock.market = stockinfo['data']['market']
                        stock.is_trust = False if len(str(
                            stock.code)) == 4 else True
                        stock.save()
                    # kabuoji3よりデータ取得
                    if stock.is_trust:
                        # 投資信託→スキップ
                        pass
                    else:
                        # 株→登録
                        data = asset_scraping.kabuoji3(stock.code)
                        if data['status']:
                            # 取得成功時
                            for d in data['data']:
                                # (date, stock)の組み合わせでデータがなければ追加
                                if StockValueData.objects.filter(
                                        stock=stock, date=d[0]).__len__() == 0:
                                    svd = StockValueData()
                                    svd.stock = stock
                                    svd.date = d[0]
                                    svd.val_open = d[1]
                                    svd.val_high = d[2]
                                    svd.val_low = d[3]
                                    svd.val_close = d[4]
                                    svd.turnover = d[5]
                                    svd.save()
                            logger.info('StockValueData of "%s" are updated' %
                                        stock.code)
                        else:
                            # 取得失敗時
                            logger.error(data['msg'])
                        # StockFinancialInfoを登録
                        check = asset_scraping.yf_profile(stock.code)
                        if check:
                            logger.info(
                                "StockFinancialData of {} was saved.".format(
                                    stock.code))

                    smsg = "New stock was registered:{}".format(stock.code)
                else:
                    stock = Stock.objects.get(code=val["code"])
                    smsg = "This stock has been already registered:{}".format(
                        stock.code)
                logger.info(smsg)
                o.stock = stock
                o.num = val["num"]
                o.value = val["price"]
                o.is_nisa = False
                o.commission = asset_lib.get_commission(o.num * o.value)
                o.save()
                logger.info("New Order is created: {}".format(o))
                # order時のholding stocks, asset status の変更
                res = asset_lib.order_process(o, request.user)
                # message
                d = {
                    "is_nisa": o.is_nisa,
                    "commission": o.commission,
                    "val": o.val,
                    "num": o.num,
                    "datetime": str(o.datetime),
                    "is_buy": o.is_buy,
                    "stock": {
                        "code": o.stock.code,
                        "name": o.stock.name,
                    }
                }
                data = {
                    "status": True,
                    "data": d,
                }
                messages.success(request, "Done")
        except Exception as e:
            logger.error(e)
            messages.error(request, e)
        finally:
            json_str = json.dumps(data, ensure_ascii=False, indent=2)
            response = HttpResponse(
                json_str,
                content_type='application/json; charset=UTF-8',
                status=None)
            return response
    elif request.method == "GET":
        data = {"status": False, "message": "Please use POST method"}
        json_str = json.dumps(data, ensure_ascii=False, indent=2)
        response = HttpResponse(json_str,
                                content_type='application/json; charset=UTF-8',
                                status=None)
        return response
Exemplo n.º 6
0
def entry_detail(request, entry_id):
    msg = "Hello Entry Detail"
    if request.method == "POST":
        try:
            with transaction.atomic():
                pks = request.POST.getlist('pk')
                orders = Order.objects.filter(pk__in=pks)
                entry = Entry.objects.get(pk=entry_id, user=request.user)
                # link_orders
                if request.POST['post_type'] == "link_orders":
                    orders.update(entry=entry)
                    msg = "Orders {} are linked to Entry {}".format(
                        pks, entry_id)
                    entry.save()
                    messages.success(request, msg)
                # unlink_orders
                elif request.POST['post_type'] == "unlink_orders":
                    orders.update(entry=None)
                    msg = "Orders {} are unlinked from Entry {}".format(
                        pks, entry_id)
                    entry.save()
                    messages.success(request, msg)
        except Exception as e:
            logger.error(e)
            messages.error(request, e)
        finally:
            return redirect('web:entry_detail', entry_id=entry_id)
    elif request.method == "GET":
        # production以外ではmsg表示
        if not settings.ENVIRONMENT == "production":
            messages.info(request, msg)
        logger.info(msg)
        try:
            # 各種情報取得
            entry = Entry.objects.prefetch_related('order_set')\
                .select_related().get(pk=entry_id, user=request.user)
            orders_unlinked = Order.objects.filter(
                entry=None, stock=entry.stock).order_by('datetime')
            orders_linked = entry.order_set.all().order_by('datetime')
            edo = entry.date_open().date()
            edc = entry.date_close().date() if entry.is_closed else date.today(
            )
            # days日のマージンでグラフ化範囲を指定
            days = 60
            od = edo - relativedelta(days=days)
            cd = edc + relativedelta(
                days=days) if entry.is_closed else date.today()
            svds = StockValueData.objects.filter(stock=entry.stock,
                                                 date__gt=od,
                                                 date__lt=cd).order_by('date')
            df = asset_analysis.prepare(svds)
            df_check = asset_analysis.check(df)
            df_trend = asset_analysis.get_trend(df)
            # グラフ化範囲のデータ数
            svds_count = svds.count()
            # 日付とindex番号の紐付け
            date_list = dict()
            for i, svd in enumerate(svds):
                date_list[svd.date.__str__()] = i
            # 売買注文のグラフ化
            bos_detail = [None for i in range(svds_count)]
            sos_detail = [None for i in range(svds_count)]
            for o in entry.order_set.all():
                order_date = str(o.datetime.date())
                if order_date in list(date_list.keys()):
                    if o.is_buy:
                        bos_detail[date_list[
                            order_date]] = o.val * 10000 if entry.stock.is_trust else o.val
                    else:
                        sos_detail[date_list[
                            order_date]] = o.val * 10000 if entry.stock.is_trust else o.val
        except Exception as e:
            logger.error(e)
            messages.error(request, "Not found or not authorized to access it")
            if not settings.ENVIRONMENT == "production":
                messages.add_message(request, messages.ERROR, e.args)
                messages.add_message(request, messages.ERROR, type(e))
                # messages.info(list(date_list[order_date].keys()))
            return redirect('web:main')
        output = {
            "msg": msg,
            "user": request.user,
            "entry": entry,
            "orders_unlinked": orders_unlinked,
            "orders_linked": orders_linked,
            "svds": svds,
            "bos_detail": bos_detail,
            "sos_detail": sos_detail,
            "od": od,
            "cd": cd,
            "df": df,
            "df_check": df_check,
            "df_trend": df_trend,
        }
        # openの場合、現在情報を取得
        if not entry.is_closed:
            overview = asset_scraping.yf_detail(entry.stock.code)
            if overview['status']:
                output['overview'] = overview['data']
        logger.info(output)
        return TemplateResponse(request, "web/entry_detail.html", output)