# -*- 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)
"""
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()
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[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', 'constants'] # Public non-indicator methods
exclude_methods = kwargs.pop('exclude', None)
as_list = kwargs.pop('as_list', False)
ta_indicators = list((x for x in dir(pd.DataFrame().ta) if not x.startswith('_') and not x.endswith('_')))
for x in helper_methods:
ta_indicators.remove(x)
if isinstance(exclude_methods, list) and exclude_methods in ta
没有合适的资源?快使用搜索试试~ 我知道了~
pandas_ta-0.1.31b.tar.gz
需积分: 1 0 下载量 114 浏览量
2024-03-17
13:29:21
上传
评论
收藏 37KB GZ 举报
温馨提示
Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
资源推荐
资源详情
资源评论
收起资源包目录
pandas_ta-0.1.31b.tar.gz (99个子文件)
pandas_ta-0.1.31b
README 56B
PKG-INFO 1KB
pandas_ta
utils.py 5KB
__init__.py 4KB
performance
__init__.py 23B
log_return.py 2KB
percent_return.py 1KB
trend_return.py 3KB
overlap
fwma.py 2KB
__init__.py 23B
hl2.py 464B
ema.py 3KB
hma.py 2KB
hlc3.py 518B
kama.py 2KB
vwma.py 1KB
linreg.py 4KB
vwap.py 2KB
tema.py 2KB
dema.py 2KB
trima.py 2KB
ohlc4.py 578B
t3.py 2KB
rma.py 1KB
ichimoku.py 4KB
midpoint.py 1KB
swma.py 2KB
sma.py 1KB
pwma.py 2KB
zlma.py 2KB
wma.py 2KB
midprice.py 1KB
volume
__init__.py 23B
eom.py 3KB
nvi.py 2KB
adosc.py 2KB
pvi.py 2KB
cmf.py 2KB
ad.py 2KB
efi.py 2KB
obv.py 2KB
pvol.py 1KB
pvt.py 2KB
vp.py 3KB
mfi.py 3KB
aobv.py 3KB
core.py 41KB
trend
__init__.py 23B
qstick.py 2KB
decreasing.py 2KB
linear_decay.py 1KB
increasing.py 2KB
amat.py 2KB
long_run.py 1KB
short_run.py 1KB
vortex.py 3KB
dpo.py 2KB
aroon.py 3KB
adx.py 5KB
momentum
__init__.py 23B
uo.py 3KB
roc.py 2KB
cmo.py 2KB
apo.py 2KB
macd.py 3KB
tsi.py 2KB
bop.py 1KB
trix.py 2KB
mom.py 1KB
cci.py 2KB
coppock.py 2KB
rsi.py 2KB
ppo.py 3KB
stoch.py 3KB
fisher.py 2KB
ao.py 2KB
kst.py 3KB
slope.py 2KB
willr.py 2KB
cg.py 1KB
statistics
__init__.py 23B
variance.py 1KB
median.py 1KB
mad.py 1KB
quantile.py 1KB
kurtosis.py 1KB
skew.py 1KB
stdev.py 1KB
zscore.py 1KB
volatility
__init__.py 23B
accbands.py 4KB
true_range.py 2KB
donchian.py 3KB
atr.py 2KB
kc.py 3KB
bbands.py 3KB
massi.py 2KB
natr.py 2KB
setup.cfg 0B
共 99 条
- 1
资源评论
程序员Chino的日记
- 粉丝: 3688
- 资源: 5万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 2024-12-2 二阶问题(复杂区域)
- 开卡工具SM2258XT(AD)-B16A-PKGT1216A-FWT1125A0
- google go lang 示例.zip
- GoodbyeDPI - 深度数据包检测规避实用程序(适用于 Windows).zip
- java开发的CMS后台管理系统源码带本地搭建教程数据库 MySQL源码类型 WebForm
- 图书管理系统(php5.6+mysql5.7) ,一个值得学习的程序源码
- Blog 是一个十年 Java 程序员的博客
- JAVASSM房屋租赁管理系统源码带本地搭建教程数据库 MySQL源码类型 WebForm
- 《OpenHarmony轻量设备开发理论与实战》目前唯一支持到OpenHarmony 4.0的南向书籍 支持所有在用的39个OpenHarmony版本
- GoDS(Go 数据结构)-集合、列表、堆栈、映射、树、队列等等.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功