본문 바로가기

Quant

Quant : Pandas - Series & DataFrame

시스템 트레이딩의 구성은 아래와 같다.

1. 금융 데이터 수집 -> 2. 데이터 전처리/분석 -> 3. 전략 만들기 -> 4. 백테스팅 ->5. 실전 투자

 

이전 포스팅에서 전략 설정 및 계획을 세웠지만

그전에 금융 데이터 수집/전처리/분석을 익힐 필요를 느꼈다.

 

파이썬을 많이 사용했지만, 코딩테스트/웹 개발을 주로 해서

numpy, pandas 등 실무에서 사용되는 라이브러리는 잘 모른다.

인프런 강의 : Python으로 데이터 기반 주식 퀀트 투자하기

관련 내용을 찾던 중, 해당 강의 커리큘럼이 적절해 보여 수강 중이다.


numpy (Numerical Python)

: The fundmental package for scientific computing with Python

C 언어로 구현된 파이썬 라이브러리

고성능의 수치계산을 위해 제작됨 (벡터 및 행렬 연산에 있어서 매우 편리함)

 

장점 : 강력함, C에 최적화된, 수치계산을 위한, 사용이 쉬운, 오픈소스

import numpy as np

# array 정의
data1 = [1,2,3,4,5]
arr1 = np.array(data1) // array([1,2,3,4,5]

# array 정의 (2)
arr2 = np.array([1,2,3,4,5]) // array([1,2,3,4,5])

# array의 size 확인
arr1.shape // (5,) - (row, column)

# array의 자료형 확인
arr2.dtype // dtype('int64')
# 정수 : int(8, 16, 32, 64)
# 실수 : float(16, 32, 64, 128)
# 복소수 : complex(64, 128, 256)
# 불리언 : bool
# 문자열 : string_
# 오브젝트 : object
# 유니코드 : unicode_

# N차 행렬 선언
arr3 = np.array([1,2,3],
                [4,5,6],
                [7,8,9],
                [10,11,12])
arr3.shape // (4,3)

- 그외에도 기능이 많지만, 이후 필요하다면 후술할 예정

 


Pandas

: pandas is a fast, powerful, flexible and easty to use open source data analysis and manipulation tool

 built on top of the Python programming language.

- 숫자 테이블과, 시계열 조작에 특화된 라이브러리

 

 

Series : data type

Numpy's ndarray + 숫자가 아닌 다른 type의 index(ex. 문자열)도 可

import pandas as pd

# Series 생성
s1 = pd.Series([1,2,3,4])
s2 = pd.Series([1,2,3,4], index = ['a', 'b', 'c', 'd'])
s2.head(2) # 상위 값 2개 보여줌. 기본 5개
s3 = pd.Series({'a':1, 'b':2, 'c':3, 'd':4, 'e':5})

# nan : not a number
s = pd.Series([10,0,1,1,2,3,4,5,6, np.nan])
len(s) // 10
s.shape // (10,)
s.count() // 9 : nan은 세지 않음
s.unique() // array([10., 0., 1., 2., 3., 4., 5., 6., nan])
s.nunique() // 8  unique한 값들의 총 갯수를 알려줌
s.value_counts() // 값들이 몇개씩 있는지 Series 형태로 뱉어줌. index는 실제값

 

index label을 기준으로 Series간의 operation이 일어남

- 데이터의 순서가 아니라, index label이 자동으로 정렬되어 연산이 진행됨

- index의 값이 중복될 수도 있다. 그 상태에서 + 연산을 하면 각각 연산을 한다. (SQL의 카테시안 곱처럼)

 

 

DataFrame : data type

다수의 Series를 하나의 변수로 관리할 수 있도록 만든 자료형

- Series의 dict 형태

- {'컬럼명1' : Series1, '컬럼명2' : Series2}

- DataFrame을 이루는 Series간의 index는 서로 다 같음

df = pd.DataFrame({'c1', s1, 'c2':s2})

# 1번째 방법  (Default index and columns would be set)
pd.DataFrame([[10,11],[10,12]])
pd.DataFrame(np.array([[10, 11],[20, 21]])) 

# 2번째 방법 (많이 안쓰임)
pd.DataFrame([
    	pd.Series(np.arange(10, 15)),   # 굳이 Series가 아니고 list형태이기만 하면 됨(=iterable한 object면 다 가능)
        pd.Series(np.arange(15, 20)),   # 굳이 Series가 아니고 list형태이기만 하면 됨(=iterable한 object면 다 가능)
    ])

pd.DataFrame([np.arange(10, 15),np.arange(15, 20),])

# 3번째 방법 (with column & index names)
pd.DataFrame(
    np.array(
        [[10, 11],
        [20, 21]]), 
    columns=['a', 'b'],
    index=['r1', 'r2']
)

# 4번째 방법
s1 = pd.Series(np.arange(1, 6, 1))    # 굳이 Series가 아니고 list형태이기만 하면 됨(=iterable한 object면 다 가능)
s2 = pd.Series(np.arange(6, 11, 1))   # 굳이 Series가 아니고 list형태이기만 하면 됨(=iterable한 object면 다 가능)
pd.DataFrame(
    {
        'c1': [1,2,3],    # list, np.array, Series 전부 다 올 수 있음!
        'c2': [4,5,6]
    }
)
   
# 참고: 1줄짜리 만들 때도 dictionary의 value에 해당하는 값들은 iterable한 data type(e.g. list, np.array, Series 등)으로 설정해줘야함
pd.DataFrame({'c1': [0], 'c2': [1]})

# dict에 값을 추가하는 것처럼. 새 column 추가 가능
df['c4'] = pd.Series([1,2,3,4], index=[0, 1, 2, 10])

 

 

 

Reindexing

- 새로운 index label을 기반으로 기존의 index-value의 mapping은 유지한채 재배열 하는 것

- 누락된 데이터를 처리하는데 매우 유용한 기능

# index 자체를 바꾸면, index-value의 mapping이 깨짐
s = pd.Series([1,2,3,4,5]) # 기본 index : 0,1,2,3,4
s.index = ['a','b','c','d','e']

s.set_index('c5')
# s(DataFrame)의 column 중 'c5'를 index로 활용
s2 = s.reindex(['a', 'c', 'e', 'g'])
s2['a'] = 0

# [X] 이렇게 하면 안됨
# index의 type이 맞지 않아. 예상한대로 계산되지 않음
s1 = pd.Series([0, 1, 2], index=[0, 1, 2])
s2 = pd.Series([3, 4, 5], index=['0', '1', '2'])


# 첫번째 방법
s1 = pd.Series([0, 1, 2], index=[0, 1, 2])
s2 = pd.Series([3, 4, 5], index=['0', '1', '2'])
s2.index = s2.index.astype(int)
s1 + s2

# 두번째 방법
s1 = pd.Series([0, 1, 2], index=[0, 1, 2])
s2 = pd.Series([3, 4, 5], index=['0', '1', '2'])
s1.index = ['a', 'b', 'c']
s2.index = ['a', 'b', 'c']
s1 + s2


# fill_value : reindex()의 유용한 Arguments
s2.reindex(['a', 'f'], fill_value=0) # fill 0 insted of nan
s3.reindex(np.arange(0,7), method='ffill') # nan이라면 앞의 값을 땡겨와서 채운다.

'Quant' 카테고리의 다른 글

Quant : Pandas - Grouping  (0) 2022.03.27
Quant : Pandas - API(2)  (0) 2022.03.15
Quant : Pandas - API (1)  (0) 2022.03.14
Quant : 사전 계획  (0) 2022.03.08
Quant : 개발환경 세팅  (2) 2022.03.07