# -*- coding: utf-8 -*-
import time
import pandas as pd
from pandas.core.base import PandasObject
from .utils import *
class BasePandasObject(PandasObject):
"""Simple PandasObject Extension
Ensures the DataFrame is not empty and has columns.
Args:
df (pd.DataFrame): Extends Pandas DataFrame
"""
def __init__(self, df, **kwargs):
if df.empty: return
if len(df.columns) > 0:
self._df = df
else:
raise AttributeError(f" [X] No columns!")
def __call__(self, kind, *args, **kwargs):
raise NotImplementedError()
@pd.api.extensions.register_dataframe_accessor('ta')
class AnalysisIndicators(BasePandasObject):
"""AnalysisIndicators is class that extends the Pandas DataFrame via
Pandas @pd.api.extensions.register_dataframe_accessor('name') decorator.
This Pandas Extension is named 'ta' for Technical Analysis that allows us
to apply technical indicators with an one extension. Even though 'ta' is
now a Pandas DataFrame Extension, you can still call the Indicators
individually. However many of the Indicators have been updated and new ones
added, so make sure to check help.
By default the 'ta' extensions uses lower case column names: open, high,
low, close, and volume. You can override the defaults but providing the
it's replacement name when calling the indicator. For example, to call the
indicator hl2().
With 'default' columns: open, high, low, close, and volume.
>>> df.ta.hl2()
>>> df.ta(kind='hl2')
With DataFrame columns: Open, High, Low, Close, and Volume.
>>> df.ta.hl2(high='High', low='Low')
>>> df.ta(kind='hl2', high='High', low='Low')
Args:
kind (str, optional): Default: None. Name of the indicator. Converts
kind to lowercase before calling.
timed (bool, optional): Default: False. Curious about the execution
speed? Well it's not ground breaking, but you can enable with True.
kwargs: Extension specific modifiers.
append (bool, optional): Default: False. When True, it appends to
result column(s) of the indicator onto the DataFrame.
Returns:
Most Indicators will return a Pandas Series. Others like MACD, BBANDS,
KC, et al will return a Pandas DataFrame. Ichimoku on the other hand
will return two DataFrames, the Ichimoku DataFrame for the known period
and a Span DataFrame for the future of the Span values.
Let's get started!
1. Loading the 'ta' module:
>>> import pandas as pd
>>> import ta as ta
2. Load some data:
>>> df = pd.read_csv('AAPL.csv', index_col='date', parse_dates=True)
3. Help!
3a. General Help:
>>> help(df.ta)
>>> df.ta()
3a. Indicator Help:
>>> help(ta.apo)
3b. Indicator Extension Help:
>>> help(df.ta.apo)
4. Ways of calling an indicator.
4a. Calling just the MACD indicator without 'ta' DataFrame extension.
>>> ta.apo(df['close'])
4b. Calling just the MACD indicator with 'ta' DataFrame extension.
>>> df.ta.apo()
4c. Calling using kind.
>>> df.ta(kind='apo')
5. Working with kwargs
5a. Append the result to the working df.
>>> df.ta.apo(append=True)
5b. Timing an indicator.
>>> apo = df.ta(kind='apo', timed=True)
>>> print(apo.timed)
"""
_adjusted = None
def __call__(self, kind=None, alias=None, timed=False, **kwargs):
try:
if isinstance(kind, str):
kind = kind.lower()
fn = getattr(self, kind)
if timed:
stime = time.time()
# Run the indicator
indicator = fn(**kwargs)
if timed:
time_diff = time.time() - stime
ms = time_diff * 1000
indicator.timed = f"{ms:2.3f} ms ({time_diff:2.3f} s)"
# print(f"execution time: {indicator.timed}")
# Add an alias if passed
if alias:
indicator.alias = f"{alias}"
return indicator
else:
self.help()
except:
self.help()
@property
def adjusted(self) -> str:
"""property: df.ta.adjusted"""
return self._adjusted
@adjusted.setter
def adjusted(self, value:str) -> None:
if value is not None and isinstance(value, str):
self._adjusted = value
else:
self._adjusted = None
def _append(self, result=None, **kwargs):
"""Appends a Pandas Series or DataFrame columns to self._df."""
if 'append' in kwargs and kwargs['append']:
df = self._df
if df is None or result is None: return
else:
if isinstance(result, pd.DataFrame):
for i, column in enumerate(result.columns):
df[column] = result.iloc[:,i]
else:
df[result.name] = result
def _get_column(self, series, default):
"""Attempts to get the correct series or 'column' and return it."""
df = self._df
if df is None: return
# Explicit passing a pd.Series to override default.
if isinstance(series, pd.Series):
return series
# Apply default if no series nor a default.
elif series is None or default is None:
return df[self.adjusted] if self.adjusted is not None else df[default]
# Ok. So it's a str.
elif isinstance(series, str):
# Return the df column since it's in there.
if series in df.columns:
return df[series]
else:
# Attempt to match the 'series' because it was likely misspelled.
matches = df.columns.str.match(series, case=False)
match = [i for i, x in enumerate(matches) if x]
# If found, awesome. Return it or return the 'series'.
cols = ', '.join(list(df.columns))
NOT_FOUND = f" [X] Ooops!!!: It's {series not in df.columns}, the series '{series}' not in {cols}"
return df.iloc[:,match[0]] if len(match) else print(NOT_FOUND)
def constants(self, apply, lower_bound=-100, upper_bound=100, every=1):
"""Constants
Useful for indicator levels or if you need some constant value.
Add constant '1' to the DataFrame
>>> df.ta.constants(True, 1, 1, 1)
Remove constant '1' to the DataFrame
>>> df.ta.constants(False, 1, 1, 1)
Adding constants that range of constants from -4 to 4 inclusive
>>> df.ta.constants(True, -4, 4, 1)
Removing constants that range of constants from -4 to 4 inclusive
>>> df.ta.constants(False, -4, 4, 1)
Args:
apply (bool): Default: None. If True, appends the range of constants to the
working DataFrame. If False, it removes the constant range from the working
DataFrame.
lower_bound (int): Default: -100. Lowest integer for the constant range.
upper_bound (int): Default: 100. Largest integer for the constant range.
every (int): Default: 10. How often to include a new constant.
Returns:
Returns nothing to the user. Either adds or removes constant ranges from the
working DataFrame.
"""
levels = [x for x in range(lower_bound, upper_bound + 1) if x % every == 0]
if apply:
for x in levels:
self._df[f'{x}'] = x
else:
for x in levels:
del self._df[f'{x}']
def indicators(self, **kwargs):
"""Indicator list"""
header = f"pandas.ta - Technical Analysis Indicators"
helper_methods = ['indicators', 'consta
没有合适的资源?快使用搜索试试~ 我知道了~
pandas_ta-0.1.39b.tar.gz
需积分: 1 0 下载量 89 浏览量
2024-03-17
13:29:22
上传
评论
收藏 39KB GZ 举报
温馨提示
共102个文件
py:100个
pkg-info:1个
cfg:1个
Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
资源推荐
资源详情
资源评论
收起资源包目录
pandas_ta-0.1.39b.tar.gz (102个子文件)
setup.cfg 0B
PKG-INFO 1KB
core.py 42KB
utils.py 5KB
adx.py 5KB
ichimoku.py 4KB
linreg.py 4KB
accbands.py 4KB
__init__.py 4KB
kc.py 4KB
kst.py 3KB
uo.py 3KB
aobv.py 3KB
stoch.py 3KB
vp.py 3KB
macd.py 3KB
ppo.py 3KB
bbands.py 3KB
rvi.py 3KB
ema.py 3KB
trend_return.py 3KB
donchian.py 3KB
vortex.py 3KB
mfi.py 3KB
eom.py 3KB
aroon.py 3KB
amat.py 2KB
cmf.py 2KB
tsi.py 2KB
kama.py 2KB
nvi.py 2KB
t3.py 2KB
cci.py 2KB
massi.py 2KB
efi.py 2KB
coppock.py 2KB
atr.py 2KB
pvi.py 2KB
adosc.py 2KB
rsi.py 2KB
wma.py 2KB
qstick.py 2KB
zlma.py 2KB
ao.py 2KB
ad.py 2KB
apo.py 2KB
willr.py 2KB
fisher.py 2KB
sinwma.py 2KB
slope.py 2KB
cmo.py 2KB
dpo.py 2KB
swma.py 2KB
setup.py 2KB
natr.py 2KB
true_range.py 2KB
trima.py 2KB
tema.py 2KB
pwma.py 2KB
fwma.py 2KB
roc.py 2KB
hma.py 2KB
trix.py 2KB
dema.py 2KB
vwap.py 2KB
obv.py 2KB
pvt.py 2KB
bop.py 2KB
log_return.py 2KB
decreasing.py 2KB
increasing.py 2KB
percent_return.py 1KB
cg.py 1KB
sma.py 1KB
pvol.py 1KB
linear_decay.py 1KB
rma.py 1KB
zscore.py 1KB
vwma.py 1KB
mom.py 1KB
mad.py 1KB
median.py 1KB
quantile.py 1KB
kurtosis.py 1KB
variance.py 1KB
stdev.py 1KB
skew.py 1KB
ft.py 1KB
midprice.py 1KB
short_run.py 1KB
long_run.py 1KB
midpoint.py 1KB
ohlc4.py 578B
hlc3.py 518B
hl2.py 464B
__init__.py 23B
__init__.py 23B
__init__.py 23B
__init__.py 23B
__init__.py 23B
共 102 条
- 1
- 2
资源评论
程序员Chino的日记
- 粉丝: 3078
- 资源: 5万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功