Etc/주식 자동 매매2022. 3. 20. 01:15
728x90

1. TA(Technical Analysis) Library in Python

 - Pandas, Numpy 기반을 작성되었고, financial time Series dataset(Open, Close, High, Low, Volume) 자료로 지표자료를 계산합니다.

 

 - 라이브러리 사용 URL: https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html

 - github URL: https://github.com/bukosabino/ta

 - matplotlib : https://matplotlib.org/3.5.1/index.html

2. 사용가능한 지표

Volume

  • Money Flow Index (MFI)
  • Accumulation/Distribution Index (ADI)
  • On-Balance Volume (OBV)
  • Chaikin Money Flow (CMF)
  • Force Index (FI)
  • Ease of Movement (EoM, EMV)
  • Volume-price Trend (VPT)
  • Negative Volume Index (NVI)
  • Volume Weighted Average Price (VWAP)

Volatility

  • Average True Range (ATR)
  • Bollinger Bands (BB)
  • Keltner Channel (KC)
  • Donchian Channel (DC)
  • Ulcer Index (UI)

Trend

  • Simple Moving Average (SMA)
  • Exponential Moving Average (EMA)
  • Weighted Moving Average (WMA)
  • Moving Average Convergence Divergence (MACD)
  • Average Directional Movement Index (ADX)
  • Vortex Indicator (VI)
  • Trix (TRIX)
  • Mass Index (MI)
  • Commodity Channel Index (CCI)
  • Detrended Price Oscillator (DPO)
  • KST Oscillator (KST)
  • Ichimoku Kinkō Hyō (Ichimoku) (일목균형표)
  • Parabolic Stop And Reverse (Parabolic SAR)
  • Schaff Trend Cycle (STC)

Momentum

  • Relative Strength Index (RSI)
  • Stochastic RSI (SRSI)
  • True strength index (TSI)
  • Ultimate Oscillator (UO)
  • Stochastic Oscillator (SR)
  • Williams %R (WR)
  • Awesome Oscillator (AO)
  • Kaufman's Adaptive Moving Average (KAMA)
  • Rate of Change (ROC)
  • Percentage Price Oscillator (PPO)
  • Percentage Volume Oscillator (PVO)

Others

  • Daily Return (DR)
  • Daily Log Return (DLR)
  • Cumulative Return (CR)

3. 사용법

설치

pip install --upgrade ta

 

전체 지표 계산코드. 한번에 계산할 수 있는 모든 지표를 처리하는데, 지표가 많다보니 경고가 나옵니다.

계산 시간도 있을 테고, 비효율적이라 추천하지는 않습니다.

import pandas as pd
from ta import add_all_ta_features
from ta.utils import dropna


# Load datas
df = pd.read_csv('ta/tests/data/datas.csv', sep=',')

# Clean NaN values
df = dropna(df)

# Add all ta features
df = add_all_ta_features(
    df, open="Open", high="High", low="Low", close="Close", volume="Volume_BTC")

 

4. 샘플

https://github.com/bukosabino/ta/tree/master/examples_to_use

 

GitHub - bukosabino/ta: Technical Analysis Library using Pandas and Numpy

Technical Analysis Library using Pandas and Numpy. Contribute to bukosabino/ta development by creating an account on GitHub.

github.com

 

import numpy as np
import pandas as pd
from trade.util.db_helper import *
from ta.trend import IchimokuIndicator
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
from matplotlib import rc, font_manager
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# 종목코드
code = '010060'
db_name = 'RSIStrategy'

# 300건으로 분석
sql = f"""
SELECT *
FROM (
SELECT `index`, open, high, low, close, volumn as volume FROM `{code}` ORDER BY `index` DESC LIMIT 300
)
ORDER BY `INDEX`            
"""

# database에서 일별 거래정보 조회
cur = execute_sql(db_name, sql)

cols = [column[0] for column in cur.description]
df = pd.DataFrame.from_records(data=cur.fetchall(), columns=cols)
df = df.set_index('index')

# 일목균형표 데이터 생성
id_ichimoku = IchimokuIndicator(high=df['high'], low=df['low'], visual=True, fillna=True)
df['span_a'] = id_ichimoku.ichimoku_a()
df['span_b'] = id_ichimoku.ichimoku_b()
df['base_line'] = id_ichimoku.ichimoku_base_line()
df['conv_line'] = id_ichimoku.ichimoku_conversion_line()

# 한글폰트
f_path = "C:/windows/Fonts/malgun.ttf"
font_manager.FontProperties(fname=f_path).get_name()
rc('font', family='Malgun Gothic')

fig = plt.figure(figsize=(12, 8))
fig.set_facecolor('w')
gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])

# fig, ax = plt.subplots(1, 1, figsize=(10, 6), constrained_layout=True)
axs = []
axs.append(plt.subplot(gs[0]))
axs.append(plt.subplot(gs[1], sharex=axs[0]))

for ax in axs:
    ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=range(1, 13)))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())

# ax. 캔들 차트
ax = axs[0]
x = np.arange(len(df.index))
ohlc = df[['open', 'high', 'low', 'close']].astype(int).values
dohlc = np.hstack((np.reshape(x, (-1, 1)), ohlc))
candlestick_ohlc(ax, dohlc, width=0.5, colorup='r', colordown='b')

# 일목균형표 추가
# ax.plot(df.close, label='close', linestyle='solid', color='purple', linewidth=2)
ax.plot(df.span_a, label='span_a', linestyle='solid', color='pink')
ax.plot(df.span_b, label='span_b', linestyle='solid', color='lightsteelblue')
ax.plot(df.base_line, label='base_line', linestyle='solid', color='green', linewidth=2)
ax.plot(df.conv_line, label='conv_line', linestyle='solid', color='darkorange')
ax.grid(True, axis='y', color='grey', alpha=0.5, linestyle='--')
ax.fill_between(df.index, df.span_a, df.span_b, alpha=0.3)

ax.set_title(f'OCI({code}) - 일목균형표')
ax.legend()

# ax2. 거래량 차트
ax2 = axs[1]
ax2.bar(x, df['volume'], color='k', width=0.6, align='center')

plt.tight_layout()
plt.show()

 

 

end.

728x90
Posted by 하루y