Comments (11)
Hello @similang,
Which version of Pandas TA are you using?
The KeyError: 'high'
means that 'high' was not found in your DataFrame df
. Are you sure you did not mean: df1.ta.strategy(name='all')
in your function: ta_pd_v2(df)
?
Hope this helps!
KJ
from pandas-ta.
Version: 0.1.66b0
Ah, my bad - I didn't put my 3rd customised function. Not use to GitHub comment sections. Perhaps it will be easier to diagnose with data.
Here you go:
from pandas-ta.
Hello @similang,
Give this a shot.
import pandas as pd
import pandas_ta as ta
if __name__ == "__main__":
df = pd.read_csv("ch.csv") # Or wherever your csv is located
df["open-1"] = df["open"].shift(1)
df["high-1"] = df["high"].shift(1)
df["low-1"] = df["low"].shift(1)
df["close-1"] = df["close"].shift(1)
df.ta.strategy(name='all', verbose=True) # appends to df by default
print(df.tail())
print(', '.join(list(df.columns))) # For verification of columns added
The output I got from above:
Trend Return
As a side note, trend_return
is a special function and is naturally excluded from all
since it requires trend logic, see the last example for a comprehensive version.
In short, suppose you wanted to calculate the Cumulative Log Returns of the trend EMA 10 > SMA 50
. Here are two different ways using TA Lib vs Pandas DataFrame Style (whichever is more logical for you):
import pandas as pd
import pandas_ta as ta
def tr_talib_style(df, cumulative):
# TA Lib Style
closedf = df['close']
long = ta.ema(closedf, 10) > ta.sma(closedf, 50)
return ta.trend_return(closedf, long, cumulative=cumulative)
def tr_dataframe_style(df, cumulative):
# DataFrame Style
long = df.ta.ema(length=10) > df.ta.sma(length=50)
df.ta.trend_return(trend=long, cumulative=cumulative, append=True)
return df
if __name__ == "__main__":
cumulative = True
df = pd.read_csv("ch.csv") # Or wherever your csv is located
df['CumLogTR'] = tr_talib_style(df, cumulative=cumulative)
df = tr_dataframe_style(df, cumulative=cumulative)
print(df.tail(10))
Hope this helps! Let me know how it works out.
Thanks,
KJ
from pandas-ta.
Hello @similang,
I assume by no response that the response provided was sufficient. Thus I will be closing this issue in a few days.
Don't forget to ⭐ if you find the library useful.
Thanks,
KJ
from pandas-ta.
Thanks. Will give it a try first and respond accordingly when I am slightly more free.
from pandas-ta.
Hi, just wondering - the 2nd part - tr_talib_style, tr_dataframe_style i hit error, i.e: in column 'close'; not sure why...
Also, how to select a subset of all strategy columns?
Thanks.
from pandas-ta.
Hey,
the 2nd part - tr_talib_style, tr_dataframe_style i hit error, i.e: in column 'close'; not sure why...
I do not know either. 🤷♂️ You have given little for me to diagnose. Is there a 'close' column in the DataFrame? Are the open, high, low, close, volume
all lowercase as mentioned in the README? Your 'volume' column is misspelled in the ch.csv
, but that wouldn't throw as 'close' column error in the simple trend_return
example.
Here are my results from the 2nd part:
Also, how to select a subset of all strategy columns?
What do you mean? Just the momentum
indicators or the overlap
indicators et al? Or do you mean, you want to select certain columns after df.ta.strategy()
has completed?
from pandas-ta.
To be exact on part 1 - gotta rename 'volumn' to 'volume' for the script to run.
Oh ya, I meant selecting certain columns for df.ta.strategy() => if i do not want all variables be populated since I am doing mass processing on multiple indices/equities.
from pandas-ta.
To be exact on part 1 - gotta rename 'volumn' to 'volume' for the script to run.
👍
Oh ya, I meant selecting certain columns for df.ta.strategy() => if i do not want all variables be populated since I am doing mass processing on multiple indices/equities.
Of course. That is something I have been trying to finish for the next release: Custom Strategies and Strategy Composition/Chaining. Because running df.ta.strategy()
, which defaults to "All" and appending currently 152 new columns is both unwise and inefficient imo even if multiprocessing enabled.
Here are some ways to target the columns. The last one is specific but requires knowing the name of the columns.
import pandas as pd
import pandas_ta as ta
if __name__ == "__main__":
_df = pd.read_csv("data/similang-ch.csv")
df = _df.copy()
df.ta.strategy(verbose=True)
cols_as_list = list(df.columns)
cols_as_string = ', '.join(cols_as_list)
# print("DataFrame Columns Property (hard to figure which to use):\n", df.columns)
# print("\n", "DataFrame Columns Names (a bit easier to find):\n", cols_as_list)
print("\n", "DataFrame Columns Names (way easier to find):\n", cols_as_string)
print("\n", "If you want say, the last ten columns:\n", df[df.columns[-10:]])
print("\n", "Or maybe the Column Indicies from 5 to 20:\n", df[df.columns[5:20]])
print("\n", "If you know what you want, say MACD and RSI:")
print(df[["RSI_14", "MACD_12_26_9", "MACDh_12_26_9", "MACDs_12_26_9"]])
Custom Strategies
Almost finished!
import pandas as pd
import pandas_ta as ta
if __name__ == "__main__":
_df = pd.read_csv("data/similang-ch.csv")
df = _df.copy()
df.ta.strategy(ta.CommonStrategy, verbose=True)
print("\nSoon a Builtin Common Strategy:", ta.CommonStrategy.name)
print(ta.CommonStrategy, "\n")
print(df)
df = _df.copy()
momo_bands_sma_ta = [
{"kind":"sma", "length": 50},
{"kind":"sma", "length": 200},
{"kind":"bbands", "length": 20},
{"kind":"macd"},
{"kind":"rsi"},
{"kind":"log_return", "cumulative": True},
{"kind":"sma", "close": "CUMLOGRET_1", "length": 5, "suffix": "CUMLOGRET"},
]
momo_bands_sma_strategy = ta.Strategy(
"Momo, Bands and SMAs and Cumulative Log Returns", # name
momo_bands_sma_ta, # ta
"MACD and RSI Momo with BBANDS and SMAs 50 & 200 and Cumulative Log Returns" # description
)
print("\nOr your own Custom Strategy:", momo_bands_sma_strategy.name)
print(momo_bands_sma_strategy, "\n")
df.ta.strategy(momo_bands_sma_strategy, timed=True)
print(df)
Yielding:
from pandas-ta.
@similang
Check out the latest version!
$ pip install -U git+https://github.com/twopirllc/pandas-ta
I assume by no response that the response provided was sufficient!?
Regards
from pandas-ta.
Nice - let me check it up. Thanks.
from pandas-ta.
Related Issues (20)
- how to use it ? HOT 1
- Simple bug on downloading data using example Backtesting with vectorbt HOT 4
- Having trouble attempting to "import pandas_ta as ta" HOT 2
- NATR in non TA-lib mode HOT 1
- How To Test TMO Indicator HOT 8
- Adjusted Close vs Close HOT 4
- Pythonv3.12 support HOT 2
- Indicators using moving averages variable does not pass kwargs to ma(mamode, close, length=length) HOT 1
- Attribute error when I remove a specific group from dataframe HOT 2
- Fix for RMA - adjust=False
- natr behaves the same as atr(percent=True)
- ta.cci returns entire original dataframe if there aren't enough rows for the period value HOT 1
- outstanding tickets for next release? HOT 3
- Weird behaviour in RSI moment indicator on development branch HOT 9
- Failing tests HOT 3
- EVERYONE: Removing the 'fillna' keyword option if there is no opposition!
- can you support smc/bos/choch smart money indicator HOT 2
- The Jurik Moving Average (JMA) is a proprietary indicator, How likely is it to be close to the actual implementation as it looks quite like a closely guarded secret? HOT 4
- Discripency Between Yahoo Finance and Panda's TA in Accumulation/Distribution Indicator HOT 1
- StochRSI on development branch HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pandas-ta.