Code Monkey home page Code Monkey logo

Comments (11)

twopirllc avatar twopirllc commented on May 13, 2024

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.

skwskwskwskw avatar skwskwskwskw commented on May 13, 2024

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:

ch.zip

from pandas-ta.

twopirllc avatar twopirllc commented on May 13, 2024

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:

Screen Shot 2020-07-20 at 8 33 28 AM

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.

twopirllc avatar twopirllc commented on May 13, 2024

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.

skwskwskwskw avatar skwskwskwskw commented on May 13, 2024

Thanks. Will give it a try first and respond accordingly when I am slightly more free.

from pandas-ta.

skwskwskwskw avatar skwskwskwskw commented on May 13, 2024

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.

twopirllc avatar twopirllc commented on May 13, 2024

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:
Screen Shot 2020-07-24 at 12 58 27 PM

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.

skwskwskwskw avatar skwskwskwskw commented on May 13, 2024

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.

twopirllc avatar twopirllc commented on May 13, 2024

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:

Screen Shot 2020-07-25 at 10 56 53 AM

from pandas-ta.

twopirllc avatar twopirllc commented on May 13, 2024

@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.

skwskwskwskw avatar skwskwskwskw commented on May 13, 2024

Nice - let me check it up. Thanks.

from pandas-ta.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.