자료가 너무 많은 것도 고민... ㅎ...

 

참조주소: https://github.com/wilsonfreitas/awesome-quant#python

 

Python

Numerical Libraries & Data Structures

  • numpy - NumPy is the fundamental package for scientific computing with Python.
  • scipy - SciPy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.
  • pandas - pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
  • quantdsl - Domain specific language for quantitative analytics in finance and trading.
  • statistics - Builtin Python library for all basic statistical calculations.
  • sympy - SymPy is a Python library for symbolic mathematics.
  • pymc3 - Probabilistic Programming in Python: Bayesian Modeling and Probabilistic Machine Learning with Theano.

Financial Instruments and Pricing

  • PyQL - QuantLib's Python port.
  • pyfin - Basic options pricing in Python. [ARCHIVED]
  • vollib - vollib is a python library for calculating option prices, implied volatility and greeks.
  • QuantPy - A framework for quantitative finance In python.
  • Finance-Python - Python tools for Finance.
  • ffn - A financial function library for Python.
  • pynance - Lightweight Python library for assembling and analysing financial data.
  • tia - Toolkit for integration and analysis.
  • hasura/base-python-dash - Hasura quickstart to deploy Dash framework. Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python.
  • hasura/base-python-bokeh - Hasura quickstart to visualize data with bokeh library.
  • pysabr - SABR model Python implementation.
  • FinancePy - A Python Finance Library that focuses on the pricing and risk-management of Financial Derivatives, including fixed-income, equity, FX and credit derivatives.
  • gs-quant - Python toolkit for quantitative finance
  • willowtree - Robust and flexible Python implementation of the willow tree lattice for derivatives pricing.
  • financial-engineering - Applications of Monte Carlo methods to financial engineering projects, in Python.
  • optlib - A library for financial options pricing written in Python.
  • tf-quant-finance - High-performance TensorFlow library for quantitative finance.
  • finoptions - Complete python implementation of R package fOptions with partial implementation of fExoticOptions for pricing various options.

Indicators

Trading & Backtesting

  • Blankly - Fully integrated backtesting, paper trading, and live deployment.
  • TA-Lib - perform technical analysis of financial market data.
  • trade - trade is a Python framework for the development of financial applications.
  • zipline - Pythonic algorithmic trading library.
  • QuantSoftware Toolkit - Python-based open source software framework designed to support portfolio construction and management.
  • quantitative - Quantitative finance, and backtesting library.
  • analyzer - Python framework for real-time financial and backtesting trading strategies.
  • bt - Flexible Backtesting for Python.
  • backtrader - Python Backtesting library for trading strategies.
  • pythalesians - Python library to backtest trading strategies, plot charts, seamlessly download market data, analyse market patterns etc.
  • pybacktest - Vectorized backtesting framework in Python / pandas, designed to make your backtesting easier.
  • pyalgotrade - Python Algorithmic Trading Library.
  • tradingWithPython - A collection of functions and classes for Quantitative trading.
  • Pandas TA - Pandas TA is an easy to use Python 3 Pandas Extension with 115+ Indicators. Easily build Custom Strategies.
  • ta - Technical Analysis Library using Pandas (Python)
  • algobroker - This is an execution engine for algo trading.
  • pysentosa - Python API for sentosa trading system.
  • finmarketpy - Python library for backtesting trading strategies and analyzing financial markets.
  • binary-martingale - Computer program to automatically trade binary options martingale style.
  • fooltrader - the project using big-data technology to provide an uniform way to analyze the whole market.
  • zvt - the project using sql,pandas to provide an uniform and extendable way to record data,computing factors,select securites, backtesting,realtime trading and it could show all of them in clearly charts in realtime.
  • pylivetrader - zipline-compatible live trading library.
  • pipeline-live - zipline's pipeline capability with IEX for live trading.
  • zipline-extensions - Zipline extensions and adapters for QuantRocket.
  • moonshot - Vectorized backtester and trading engine for QuantRocket based on Pandas.
  • PyPortfolioOpt - Financial portfolio optimisation in python, including classical efficient frontier and advanced methods.
  • Eiten - Eiten is an open source toolkit by Tradytics that implements various statistical and algorithmic investing strategies such as Eigen Portfolios, Minimum Variance Portfolios, Maximum Sharpe Ratio Portfolios, and Genetic Algorithms based Portfolios.
  • riskparity.py - fast and scalable design of risk parity portfolios with TensorFlow 2.0
  • mlfinlab - Implementations regarding "Advances in Financial Machine Learning" by Marcos Lopez de Prado. (Feature Engineering, Financial Data Structures, Meta-Labeling)
  • pyqstrat - A fast, extensible, transparent python library for backtesting quantitative strategies.
  • NowTrade - Python library for backtesting technical/mechanical strategies in the stock and currency markets.
  • pinkfish - A backtester and spreadsheet library for security analysis.
  • aat - Async Algorithmic Trading Engine
  • Backtesting.py - Backtest trading strategies in Python
  • catalyst - An Algorithmic Trading Library for Crypto-Assets in Python
  • quantstats - Portfolio analytics for quants, written in Python
  • qtpylib - QTPyLib, Pythonic Algorithmic Trading http://qtpylib.io
  • Quantdom - Python-based framework for backtesting trading strategies & analyzing financial markets [GUI]
  • freqtrade - Free, open source crypto trading bot
  • algorithmic-trading-with-python - Free pandas and scikit-learn resources for trading simulation, backtesting, and machine learning on financial data.
  • DeepDow - Portfolio optimization with deep learning
  • Qlib - An AI-oriented Quantitative Investment Platform by Microsoft. Full ML pipeline of data processing, model training, back-testing; and covers the entire chain of quantitative investment: alpha seeking, risk modeling, portfolio optimization, and order execution.
  • machine-learning-for-trading - Code and resources for Machine Learning for Algorithmic Trading
  • AlphaPy - Automated Machine Learning [AutoML] with Python, scikit-learn, Keras, XGBoost, LightGBM, and CatBoost
  • jesse - An advanced crypto trading bot written in Python
  • rqalpha - A extendable, replaceable Python algorithmic backtest && trading framework supporting multiple securities.
  • FinRL-Library - A Deep Reinforcement Learning Library for Automated Trading in Quantitative Finance. NeurIPS 2020.
  • bulbea - Deep Learning based Python Library for Stock Market Prediction and Modelling.
  • ib_nope - Automated trading system for NOPE strategy over IBKR TWS.
  • OctoBot - Open source cryptocurrency trading bot for high frequency, arbitrage, TA and social trading with an advanced web interface.
  • bta-lib - Technical Analysis library in pandas for backtesting algotrading and quantitative analysis.
  • Stock-Prediction-Models - Gathers machine learning and deep learning models for Stock forecasting including trading bots and simulations.
  • tda-api - Gather data and trade equities, options, and ETFs via TDAmeritrade.
  • vectorbt - Find your trading edge, using a powerful toolkit for backtesting, algorithmic trading, and research.
  • Lean - Lean Algorithmic Trading Engine by QuantConnect (Python, C#).
  • fast-trade - Low code backtesting library utilizing pandas and technical analysis indicators.

Risk Analysis

  • pyfolio - Portfolio and risk analytics in Python.
  • empyrical - Common financial risk and performance metrics.
  • fecon235 - Computational tools for financial economics include: Gaussian Mixture model of leptokurtotic risk, adaptive Boltzmann portfolios.
  • finance - Financial Risk Calculations. Optimized for ease of use through class construction and operator overload.
  • qfrm - Quantitative Financial Risk Management: awesome OOP tools for measuring, managing and visualizing risk of financial instruments and portfolios.
  • visualize-wealth - Portfolio construction and quantitative analysis.
  • VisualPortfolio - This tool is used to visualize the perfomance of a portfolio.
  • universal-portfolios - Collection of algorithms for online portfolio selection.
  • FinQuant - A program for financial portfolio management, analysis and optimisation.
  • Empyrial - Portfolio's risk and performance analytics and returns predictions.
  • risktools - Risk tools for use within the crude and crude products trading space with partial implementation of R's PerformanceAnalytics.
  • Riskfolio-Lib - Portfolio Optimization and Quantitative Strategic Asset Allocation in Python.

Factor Analysis

  • alphalens - Performance analysis of predictive alpha factors.
  • Spectre - GPU-accelerated Factors analysis library and Backtester

Time Series

  • ARCH - ARCH models in Python.
  • statsmodels - Python module that allows users to explore data, estimate statistical models, and perform statistical tests.
  • dynts - Python package for timeseries analysis and manipulation.
  • PyFlux - Python library for timeseries modelling and inference (frequentist and Bayesian) on models.
  • tsfresh - Automatic extraction of relevant features from time series.
  • hasura/quandl-metabase - Hasura quickstart to visualize Quandl's timeseries datasets with Metabase.
  • Facebook Prophet - Tool for producing high quality forecasts for time series data that has multiple seasonality with linear or non-linear growth.
  • tsmoothie - A python library for time-series smoothing and outlier detection in a vectorized way.
  • pmdarima - A statistical library designed to fill the void in Python's time series analysis capabilities, including the equivalent of R's auto.arima function.

Calendars

Data Sources

  • yfinance - Yahoo! Finance market data downloader (+faster Pandas Datareader)
  • findatapy - Python library to download market data via Bloomberg, Quandl, Yahoo etc.
  • googlefinance - Python module to get real-time stock data from Google Finance API.
  • yahoo-finance - Python module to get stock data from Yahoo! Finance.
  • pandas-datareader - Python module to get data from various sources (Google Finance, Yahoo Finance, FRED, OECD, Fama/French, World Bank, Eurostat...) into Pandas datastructures such as DataFrame, Panel with a caching mechanism.
  • pandas-finance - High level API for access to and analysis of financial data.
  • pyhoofinance - Rapidly queries Yahoo Finance for multiple tickers and returns typed data for analysis.
  • yfinanceapi - Finance API for Python.
  • yql-finance - yql-finance is simple and fast. API returns stock closing prices for current period of time and current stock ticker (i.e. APPL, GOOGL).
  • ystockquote - Retrieve stock quote data from Yahoo Finance.
  • wallstreet - Real time stock and option data.
  • stock_extractor - General Purpose Stock Extractors from Online Resources.
  • Stockex - Python wrapper for Yahoo! Finance API.
  • finsymbols - Obtains stock symbols and relating information for SP500, AMEX, NYSE, and NASDAQ.
  • FRB - Python Client for FRED® API.
  • inquisitor - Python Interface to Econdb.com API.
  • yfi - Yahoo! YQL library.
  • chinesestockapi - Python API to get Chinese stock price.
  • exchange - Get current exchange rate.
  • ticks - Simple command line tool to get stock ticker data.
  • pybbg - Python interface to Bloomberg COM APIs.
  • ccy - Python module for currencies.
  • tushare - A utility for crawling historical and Real-time Quotes data of China stocks.
  • jsm - Get the japanese stock market data.
  • cn_stock_src - Utility for retrieving basic China stock data from different sources.
  • coinmarketcap - Python API for coinmarketcap.
  • after-hours - Obtain pre market and after hours stock prices for a given symbol.
  • bronto-python - Bronto API Integration for Python.
  • pytdx - Python Interface for retrieving chinese stock realtime quote data from TongDaXin Nodes.
  • pdblp - A simple interface to integrate pandas and the Bloomberg Open API.
  • tiingo - Python interface for daily composite prices/OHLC/Volume + Real-time News Feeds, powered by the Tiingo Data Platform.
  • iexfinance - Python Interface for retrieving real-time and historical prices and equities data from The Investor's Exchange.
  • pyEX - Python interface to IEX with emphasis on pandas, support for streaming data, premium data, points data (economic, rates, commodities), and technical indicators.
  • alpaca-trade-api - Python interface for retrieving real-time and historical prices from Alpaca API as well as trade execution.
  • metatrader5 - API Connector to MetaTrader 5 Terminal
  • akshare - AkShare is an elegant and simple financial data interface library for Python, built for human beings! https://akshare.readthedocs.io
  • yahooquery - Python interface for retrieving data through unofficial Yahoo Finance API.
  • investpy - Financial Data Extraction from Investing.com with Python! https://investpy.readthedocs.io/
  • yliveticker - Live stream of market data from Yahoo Finance websocket.
  • bbgbridge - Easy to use Bloomberg Desktop API wrapper for Python.
  • alpha_vantage - A python wrapper for Alpha Vantage API for financial data.
  • FinanceDataReader - Open Source Financial data reader for U.S, Korean, Japanese, Chinese, Vietnamese Stocks
  • pystlouisfed - Python client for Federal Reserve Bank of St. Louis API - FRED, ALFRED, GeoFRED and FRASER

Excel Integration

  • xlwings - Make Excel fly with Python.
  • openpyxl - Read/Write Excel 2007 xlsx/xlsm files.
  • xlrd - Library for developers to extract data from Microsoft Excel spreadsheet files.
  • xlsxwriter - Write files in the Excel 2007+ XLSX file format.
  • xlwt - Library to create spreadsheet files compatible with MS Excel 97/2000/XP/2003 XLS files, on any platform.
  • DataNitro - DataNitro also offers full-featured Python-Excel integration, including UDFs. Trial downloads are available, but users must purchase a license.
  • xlloop - XLLoop is an open source framework for implementing Excel user-defined functions (UDFs) on a centralised server (a function server).
  • expy - The ExPy add-in allows easy use of Python directly from within an Microsoft Excel spreadsheet, both to execute arbitrary code and to define new Excel functions.
  • pyxll - PyXLL is an Excel add-in that enables you to extend Excel using nothing but Python code.

Visualization

  • D-Tale - Visualizer for pandas dataframes and xarray datasets.
  • mplfinance - matplotlib utilities for the visualization, and visual analysis, of financial data.
  • finplot - Performant and effortless finance plotting for Python.
  • finvizfinance - Finviz analysis python library.
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

일목균형표를 해외에서는 Ichimoku Kinkō Hyō 라고 부럽니다. (일본어를 영어식 발음으로 한 듯)

 

사이트 URL: https://stockcharts.com/h-sc/ui

지표에대한 설명: https://school.stockcharts.com/doku.php?id=technical_indicators:ichimoku_cloud 

 

설정을 아래와 같이 몇가지 변경해야, 국내에서 볼 수 있는 차표처럼 보입니다.

아래 Indicators 에 지표 추가도 가능하네요.

 

 

728x90

엠피엘파이낸스 패키지를 이용한 캔들 차트 표시

일거래 데이터는 증권사로 부터 내려받아서 RSIStrategy.db에 종목별로 보관하고 있고, 

테이블 조회 후 캐들 차트를 표시함.

 

일자를 datetime으로 변화해줘야 함.

 

엠피엘파이낸스 패키지 링크: https://github.com/matplotlib/mplfinance

 

import sqlite3
import pandas as pd
import mplfinance as mpf


def execute_sql(sql, param={}):
    with sqlite3.connect('RSIStrategy.db') as con:
        cur = con.cursor()
        cur.execute(sql, param)
        return cur

code = '010060' # OCI
sql = '''SELECT Date, Open, High, Low, Close, Volume
  FROM (
		SELECT `index` as Date, Open, High, Low, Close, Volumn as Volume
		 , ROW_NUMBER() over(order by "index" desc ) as rownum 
		  FROM `{}`
       )
where rownum <= 150  
'''.format(code)

cur = execute_sql(sql)
cols = [column[0] for column in cur.description]
df = pd.DataFrame.from_records(data=cur.fetchall(), columns=cols)
df = df.sort_values(by='Date')
df.index = pd.to_datetime(df['Date'], format='%Y%m%d')
df = df[['Open', 'High', 'Low', 'Close', 'Volume']]
print(df)

kwargs = dict(title='OCI candle chart', type='candle', mav=(5, 10, 20), volume=True, ylabel='ohlc candles')
mc = mpf.make_marketcolors(up='r', down='b', inherit=True)
s = mpf.make_mpf_style(marketcolors=mc)
# mpf.plot(df, title='OCI candle chart', type='candle')
mpf.plot(df, **kwargs, style=s)

 

728x90

+ Recent posts