# -*- coding: utf-8 -*-
from dataclasses import dataclass, field
from multiprocessing import cpu_count, Pool
from pathlib import Path
from time import perf_counter
from typing import List, Tuple
import pandas as pd
from numpy import log10 as npLog10
from numpy import ndarray as npNdarray
from pandas.core.base import PandasObject
from pandas_ta import Category, Imports, version
from pandas_ta.candles.cdl_pattern import ALL_PATTERNS
from pandas_ta.candles import *
from pandas_ta.cycles import *
from pandas_ta.momentum import *
from pandas_ta.overlap import *
from pandas_ta.performance import *
from pandas_ta.statistics import *
from pandas_ta.trend import *
from pandas_ta.volatility import *
from pandas_ta.volume import *
from pandas_ta.utils import *
df = pd.DataFrame()
# Strategy DataClass
@dataclass
class Strategy:
"""Strategy DataClass
A way to name and group your favorite indicators
Args:
name (str): Some short memorable string. Note: Case-insensitive "All" is reserved.
ta (list of dicts): A list of dicts containing keyword arguments where "kind" is the indicator.
description (str): A more detailed description of what the Strategy tries to capture. Default: None
created (str): At datetime string of when it was created. Default: Automatically generated. *Subject to change*
Example TA:
ta = [
{"kind": "sma", "length": 200},
{"kind": "sma", "close": "volume", "length": 50},
{"kind": "bbands", "length": 20},
{"kind": "rsi"},
{"kind": "macd", "fast": 8, "slow": 21},
{"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
]
"""
name: str # = None # Required.
ta: List = field(default_factory=list) # Required.
# Helpful. More descriptive version or notes or w/e.
description: str = "TA Description"
# Optional. Gets Exchange Time and Local Time execution time
created: str = get_time(to_string=True)
def __post_init__(self):
has_name = True
is_ta = False
required_args = ["[X] Strategy requires the following argument(s):"]
name_is_str = isinstance(self.name, str)
ta_is_list = isinstance(self.ta, list)
if self.name is None or not name_is_str:
required_args.append(' - name. Must be a string. Example: "My TA". Note: "all" is reserved.')
has_name != has_name
if self.ta is None:
self.ta = None
elif self.ta is not None and ta_is_list and self.total_ta() > 0:
# Check that all elements of the list are dicts.
# Does not check if the dicts values are valid indicator kwargs
# User must check indicator documentation for all indicators args.
is_ta = all([isinstance(_, dict) and len(_.keys()) > 0 for _ in self.ta])
else:
s = " - ta. Format is a list of dicts. Example: [{'kind': 'sma', 'length': 10}]"
s += "\n Check the indicator for the correct arguments if you receive this error."
required_args.append(s)
if len(required_args) > 1:
[print(_) for _ in required_args]
return None
def total_ta(self):
return len(self.ta) if self.ta is not None else 0
# All Default Strategy
AllStrategy = Strategy(
name="All",
description="All the indicators with their default settings. Pandas TA default.",
ta=None,
)
# Default (Example) Strategy.
CommonStrategy = Strategy(
name="Common Price and Volume SMAs",
description="Common Price SMAs: 10, 20, 50, 200 and Volume SMA: 20.",
ta=[
{"kind": "sma", "length": 10},
{"kind": "sma", "length": 20},
{"kind": "sma", "length": 50},
{"kind": "sma", "length": 200},
{"kind": "sma", "close": "volume", "length": 20, "prefix": "VOL"}
]
)
# Base Class for extending a Pandas DataFrame
class BasePandasObject(PandasObject):
"""Simple PandasObject Extension
Ensures the DataFrame is not empty and has columns.
It would be a sad Panda otherwise.
Args:
df (pd.DataFrame): Extends Pandas DataFrame
"""
def __init__(self, df, **kwargs):
if df.empty: return
if len(df.columns) > 0:
common_names = {
"Date": "date",
"Time": "time",
"Timestamp": "timestamp",
"Datetime": "datetime",
"Open": "open",
"High": "high",
"Low": "low",
"Close": "close",
"Adj Close": "adj_close",
"Volume": "volume",
"Dividends": "dividends",
"Stock Splits": "split",
}
# Preemptively drop the rows that are all NaNs
# Might need to be moved to AnalysisIndicators.__call__() to be
# toggleable via kwargs.
# df.dropna(axis=0, inplace=True)
# Preemptively rename columns to lowercase
df.rename(columns=common_names, errors="ignore", inplace=True)
# Preemptively lowercase the index
index_name = df.index.name
if index_name is not None:
df.index.rename(index_name.lower(), inplace=True)
self._df = df
else:
raise AttributeError(f"[X] No columns!")
def __call__(self, kind, *args, **kwargs):
raise NotImplementedError()
# Pandas TA - DataFrame Analysis Indicators
@pd.api.extensions.register_dataframe_accessor("ta")
class AnalysisIndicators(BasePandasObject):
"""
This Pandas Extension is named 'ta' for Technical Analysis. In other words,
it is a Numerical Time Series Feature Generator where the Time Series data
is biased towards Financial Market data; typical data includes columns
named :"open", "high", "low", "close", "volume".
This TA Library hopefully allows you to apply familiar and unique Technical
Analysis Indicators easily with the DataFrame Extension named 'ta'. Even
though 'ta' is a Pandas DataFrame Extension, you can still call Technical
Analysis indicators individually if you are more comfortable with that
approach or it allows you to easily and automatically apply the indicators
with the strategy method. See: help(ta.strategy).
By default, the 'ta' extension uses lower case column names: open, high,
low, close, and volume. You can override the defaults by 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")
If you do not want to use a DataFrame Extension, just call it normally.
>>> sma10 = ta.sma(df["Close"]) # Default length=10
>>> sma50 = ta.sma(df["Close"], length=50)
>>> ichimoku, span = ta.ichimoku(df["High"], df["Low"], df["Close"])
Args:
kind (str, optional): Default: None. Kind is the 'name' of the indicator.
It converts kind to lowercase before calling.
timed (bool, optional): Default: False. Curious about the execution
speed?
kwargs: Extension specific modifiers.
append (bool, optional): Default: False. When True, it appends the
resultant column(s) to 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
没有合适的资源?快使用搜索试试~ 我知道了~
pandas_ta-0.3.02b.tar.gz
需积分: 1 0 下载量 153 浏览量
2024-03-17
13:29:23
上传
评论
收藏 107KB GZ 举报
温馨提示
共164个文件
py:162个
pkg-info:1个
cfg:1个
Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
资源推荐
资源详情
资源评论
收起资源包目录
pandas_ta-0.3.02b.tar.gz (164个子文件)
setup.cfg 0B
PKG-INFO 1KB
core.py 82KB
yahoofinance.py 24KB
squeeze_pro.py 10KB
_metrics.py 9KB
squeeze.py 9KB
_math.py 8KB
stc.py 7KB
qqe.py 6KB
hwc.py 6KB
adx.py 5KB
_signals.py 5KB
psar.py 5KB
ichimoku.py 5KB
rsx.py 5KB
hilo.py 4KB
macd.py 4KB
xsignals.py 4KB
cdl_pattern.py 4KB
linreg.py 4KB
thermo.py 4KB
vp.py 4KB
bbands.py 4KB
uo.py 4KB
supertrend.py 4KB
ebsw.py 4KB
_time.py 4KB
rvi.py 4KB
_core.py 4KB
kvo.py 4KB
kst.py 4KB
__init__.py 4KB
tos_stdevall.py 3KB
cksp.py 3KB
kc.py 3KB
aroon.py 3KB
fisher.py 3KB
stochrsi.py 3KB
accbands.py 3KB
smi.py 3KB
rsi.py 3KB
tsignals.py 3KB
vidya.py 3KB
ppo.py 3KB
stoch.py 3KB
ssf.py 3KB
td_seq.py 3KB
donchian.py 3KB
aberration.py 3KB
rvgi.py 3KB
ha.py 3KB
chop.py 3KB
alma.py 3KB
inertia.py 3KB
kdj.py 3KB
mfi.py 3KB
aobv.py 3KB
brar.py 3KB
kama.py 3KB
vortex.py 3KB
pvo.py 3KB
increasing.py 3KB
decreasing.py 3KB
zlma.py 3KB
er.py 3KB
atr.py 3KB
vwap.py 3KB
cdl_doji.py 3KB
eri.py 3KB
eom.py 3KB
dm.py 3KB
mcgd.py 3KB
ema.py 3KB
cmf.py 3KB
ttm_trend.py 3KB
adosc.py 3KB
cdl_z.py 3KB
tsi.py 3KB
t3.py 3KB
ui.py 2KB
trix.py 2KB
wma.py 2KB
cmo.py 2KB
setup.py 2KB
cci.py 2KB
ma.py 2KB
hwma.py 2KB
nvi.py 2KB
psl.py 2KB
drawdown.py 2KB
massi.py 2KB
pvi.py 2KB
willr.py 2KB
natr.py 2KB
ad.py 2KB
swma.py 2KB
coppock.py 2KB
pgo.py 2KB
efi.py 2KB
共 164 条
- 1
- 2
资源评论
程序员Chino的日记
- 粉丝: 2913
- 资源: 4万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功