ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python f'{formating}'] 봇 메시지 포맷팅
    Python/텔레그램봇:채권모니터링 2020. 12. 16. 16:00

    pandas의 DataFrame에 저장된 데이터를 가져와서 f"{}" 방식으로 포맷팅한다.


     

    봇으로 메시지를 보내려면 적당한 형식으로 포맷팅을 해야한다.

    내 핸드폰에서는 한글 22자가 한 줄에 들어가는 맥시멈이어서, 아래와 같은 형식을 취하기로 했다.

    파라다이스6
     D-1042    A ₩10,043.0(3.302%)
     10,043(3.302%)  9,900(3.831%)
    
    

    이걸 위해서는 pandas dataframe 형태의 데이터를 string 형태로 바꿔주어야 한다.

    f"{변수}" 형태로 입력하면 변수를 손쉽게 문자열로 바꿀 수 있다.

    a = 98765.4321
    print(f"{a}")  # 98765.4321
    

    특정 공간에 맞춰 정렬하는 것도 가능하다.

    print(f"{a:>20}")
    #          98765.4321
    
    print(f"{a:<20}")
    #98765.4321          /<-여기까지
    
    print(f"{a:^20}")
    #     98765.4321     /<

    해당 공간을 공백이 아닌 다른 문자로 채우고 싶다면 해당 문자를 입력하면 된다.

    print(f"{a:*^20}")
    #*****98765.4321*****

    숫자의 경우, 쉼표 표시도 가능.

    print(f"{438765434567654345:,}")
    #438,765,434,567,654,345

    물론 정렬과도 함께 사용할 수 있다.

    print(f"{438765434567654345:,>50,}")
    #,,,,,,,,,,,,,,,,,,,,,,,,,,,438,765,434,567,654,345

    특정 개수만큼만 출력하는 경우, 정수는 지원하지 않는다. 정수를 자르고 싶다면 문자로 변환한 다음 변환하자.

    print('{:*^10.3}'.format("sadffd"))
    #***sad****
    
    print('{:*^10.2f}'.format(1111.1111))
    #*1111.11**
    
    print('{:*^10.2}'.format(1111))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: Precision not allowed in integer format specifier
    
    print(f'{f"{1234567890:,}":>20.5}')
    #               1,234

     

    가지고 있는 데이터는 이렇게 생겼다. df.loc[idx, '가격']처럼 접근하면 된다.

    종목명             풍산105
    가격                NaN
    수익률               NaN
    거래량               NaN
    거래대금              NaN
    매도호가            10053
    매도수익률           2.443
    매수호가                0
    매수수익률               0
    신용등급                A
    잔존기간         02.04.17
    표준코드     KR6103141A47
    Y2D               867
    Name: 1600, dtype: object

    필요한 데이터는 아래와 같다.

    df.loc[idx, '종목명']
     D-df.loc[idx, 'Y2D']    df.loc[idx, '신용등급'] ₩df.loc[idx, '가격'](df.loc[idx, '수익률']%)
     df.loc[idx, '매도가격'](df.loc[idx, '매도수익률']%)  df.loc[idx, '매수가격'](df.loc[idx, '매수수익률']%)

    종목명은 22글자까지만 출력하고, Y2D는 가독성을 위해 4칸을 확보하고 오른쪽 정렬을 한다. 신용등급도 마찬가지.

    텍스트는 [:22] 인덱싱으로 자르고, 4칸 확보는 f'{}' 포맷팅의 width와 :>를 이용한다.

    가격 종류는 10,000.0이 8칸이니 8칸으로 통일하고, 수익률도 0.000%니까 정수 1칸, 소숫점 3칸을 확보한다.

    혹시나 값이 없다면 nan은 그대로 nan으로 출력하기로 한다.

    f"{df.loc[d, '종목명'][:22]:<22}\n" \
    + f" D-{df.loc[d, 'Y2D']:>4}" \
    + f"    {df.loc[d, '신용등급']:^4}" \
    + f"    {df.loc[d, '가격']:>8,}({df.loc[d, '수익률']:>1.3f}%)\n" \
    + f" {df.loc[d, '매도호가']:>8,}({df.loc[d, '매도수익률']:>1.3f}%)" \
    + f"  {df.loc[d, '매수호가']:>8,}({df.loc[d, '매수수익률']:>1.3f}%)"\
    + "\n\n"

     

    함수로 정리해두었다.

    def sendingForm(df):
        message = ''
        for idx in df.index:
            message = message + f"{df.loc[idx, '종목명'][:22]:<22}\n" \
                + f" D-{df.loc[idx, 'Y2D']:>4}" \
                + f"    {df.loc[idx, '신용등급']:^4}" \
                + f"    {df.loc[idx, '가격']:>8,}({df.loc[idx, '수익률']:>1.3f}%)\n" \
                + f" {df.loc[idx, '매도호가']:>8,}({df.loc[idx, '매도수익률']:>1.3f}%)" \
                + f"  {df.loc[idx, '매수호가']:>8,}({df.loc[idx, '매수수익률']:>1.3f}%)"\
                + "\n\n"
        return message
    
    print(sendingForm(csv_sorted))
    '''
    칼제이십오차유동화전문1-4
     D- 475     A           nan(nan%)
     10,050.0(2.921%)   9,800.0(4.911%)
    
    한일홀딩스68
     D- 883     A+          nan(nan%)
     10,085.0(2.184%)       0.0(0.000%)
    
    풍산105
     D- 867     A           nan(nan%)
     10,053.0(2.443%)       0.0(0.000%)
     '''

     

    참조문서:

    docs.python.org/3/library/string.html#formatexamplesa

     

    string — Common string operations — Python 3.9.1 documentation

    string — Common string operations Source code: Lib/string.py String constants The constants defined in this module are: string.ascii_letters The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-

    docs.python.org

     

    댓글

Designed by Tistory.