Giter Site home page Giter Site logo

peerchemist / finta Goto Github PK

View Code? Open in Web Editor NEW
2.1K 83.0 676.0 764 KB

Common financial technical indicators implemented in Pandas.

License: GNU Lesser General Public License v3.0

Python 99.93% Shell 0.07%
pandas trading-algorithms fintech python technical-analysis trading algorithmic-trading algotrading trading-strategy

finta's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

finta's Issues

GPL

Hi,

I'd just like to enquire as to why you decided to put this project under the GPL license, instead of something less restrictive.

Robert

PSAR indicator?

PSAR is both valuable and often used by traders. Can we implement PSAR?

Using Numpy Arrays Instead of Pandas DataFrames

Hello,

I am using finta library from Julia. I noticed I must pass price as Pandas DataFrame, and this adds extra function calls and overhead through PyCall. Is there a way I can use finta functions using Numpy Arrays instead of Pandas DataFrames? A lower level API maybe?!

Thank you!

Relative Strength Index (RSI) calculation

First of all, many thanks for this nice python library. I am using the version 0.4.4.

I computed the RSI on data fetched using ccxt, and compared it with the RSI shown on cryptowat.ch.
Unfortunately, the RSI calculated by finta did not match the RSI calculated by cryptowat.ch.

After investigation, I realized that the way the exponential moving average (EMA) is calculated is different.

In finta, the EMA is computed with alpha = 2 / (1 + period) (i.e. the parameter span in https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html )
In cryptowat.ch, the EMA seems computed with alpha = 1 / period.

As an example, I took the BTC/USDT symbol from binance.
https://cryptowat.ch/charts/BINANCE:BTC-USDT?period=1h

To test my assumption, I wrote a script for plotting different RSI values (requires ccxt, finta, mplfinance and pandas).

#!/usr/bin/env python3

import ccxt
from finta import TA
from datetime import datetime
import mplfinance as mpf
import pandas as pd

# https://cryptowat.ch/charts/BINANCE:BTC-USDT?period=1h
exchange_id = "binance"
symbol_id = "BTC/USDT"
timeframe = "1h"
period = 14


def fetch(exchange_id, symbol_id, timeframe):
    exchange = getattr(ccxt, exchange_id)()
    data = exchange.fetch_ohlcv(symbol_id, timeframe=timeframe)
    columns = ["date", "open", "high", "low", "close", "volume"]
    df = pd.DataFrame.from_records(data, index=["date"], columns=columns)
    df.index = pd.to_datetime(df.index, unit="ms")
    return df


def my_RSI(df, period):
    delta = df["close"].diff()
    up, down = delta.copy(), delta.copy()
    up[up < 0] = 0
    down[down > 0] = 0
    _gain = up.ewm(alpha=1.0 / period).mean()
    _loss = down.abs().ewm(alpha=1.0 / period).mean()
    rs = _gain / _loss
    return pd.Series(100.0 - (100.0 / (1.0 + rs)), name=f"{period} period RSI")


def plot(df):
    plots = [
        mpf.make_addplot(df["TA_RSI_1"], color="r", panel="lower"),
        mpf.make_addplot(df["TA_RSI_2"], color="g", panel="lower"),
        mpf.make_addplot(df["my_RSI"], color="b", panel="lower"),
    ]
    mpf.plot(df, type="candle", addplot=plots)


df = fetch(exchange_id, symbol_id, timeframe)
df["TA_RSI_1"] = TA.RSI(df, period)
df["TA_RSI_2"] = TA.RSI(df, 2 * period - 1)
df["my_RSI"] = my_RSI(df, period)

print(df.tail(20))
plot(df.tail(100))

The script above outputs the OHLC columns, plus:

  • TA_RSI_1: the RSI calculated by finta with span = period.
  • TA_RSI_2: the RSI calculated by finta with span = 2 * period - 1 (should be equivalent to setting alpha = 1/period).
  • my_RSI: the RSI calculated by my function my_RSI that computes the EMA with alpha = 1/period.

Here is the resulting table:

                        open     high      low    close       volume   TA_RSI_1   TA_RSI_2     my_RSI
date                                                                                                 
...
2020-07-11 20:00:00  9205.10  9217.24  9201.55  9216.86   635.630615  45.234820  46.166655  46.166655
2020-07-11 21:00:00  9216.86  9224.68  9207.74  9220.21   436.291969  47.639032  47.260102  47.260102
2020-07-11 22:00:00  9220.19  9236.11  9210.36  9218.41   835.240810  46.376785  46.711094  46.711094
2020-07-11 23:00:00  9218.42  9253.00  9218.02  9234.03   718.692534  57.620173  51.929694  51.929694
2020-07-12 00:00:00  9234.02  9268.52  9230.61  9250.99   994.539305  66.436767  56.868698  56.868698
2020-07-12 01:00:00  9250.99  9294.00  9243.48  9268.56  1859.797089  73.120963  61.304329  61.304329
2020-07-12 02:00:00  9268.56  9280.01  9260.09  9270.16   761.173114  73.671899  61.690696  61.690696
2020-07-12 03:00:00  9270.36  9284.15  9266.51  9272.47   858.523274  74.541190  62.276332  62.276332
2020-07-12 04:00:00  9272.47  9286.69  9261.22  9269.11   788.583932  70.627428  60.819928  60.819928
2020-07-12 05:00:00  9269.17  9277.21  9253.48  9264.84   344.009624  65.578534  58.933693  58.933693

The chart on cryptowat.ch shows the following:

binance-btcusdt

The bottom panel contains the curve of the RSI as computed by cryptowat.ch.

The chart shown by my python script is the following:

binance_finta

The RSI is shown in the bottom panel.
The red curve is the RSI computed by finta (column TA_RSI_1), the blue curve is the RSI computed by my_RSI. We can see that the TA_RSI_1 in red has some peaks far above 75, whereas my_RSI stays below 75 (sometimes reaches nearly 75), the latter matches strongly the behavior of the cryptowat.ch curve. So it supports the fact that cryptowat.ch uses alpha = 1/period.

I wonder if there is a standard "RSI". This website ( https://www.macroption.com/rsi-calculation/#wilders-smoothing-method ) states that the inventor of the RSI computed the EMA with alpha = 1/period, that seems to be the one adopted by cryptowat.ch.

Therefore, if it makes sense, my suggestion would be to replace these lines:

finta/finta/finta.py

Lines 589 to 591 in 8642dd8

# EMAs of ups and downs
_gain = up.ewm(span=period, adjust=adjust).mean()
_loss = down.abs().ewm(span=period, adjust=adjust).mean()

by:

        # EMAs of ups and downs
        _gain = up.ewm(alpha=1.0/period, adjust=adjust).mean()
        _loss = down.abs().ewm(alpha=1.0/period, adjust=adjust).mean()

By the way, I think it would also be nice to add a parameter such as "column" to choose on which column of the dataframe the RSI is computed.

Many thanks.

SSMA - smoothed simple moving average

Hi,

first of all thank you for your amazing job.

I would like to ask you if do you know how to calculate ssma?

I saw this indicator on iqoption site but I can't found how to calc this.

I found SMA but not SSMA

Resample issue (pandas 0.25.3)

I'm unable to resample a dataset from interval "1m" to "15m".
(dataset)

Dataframe:
image

Code:

from finta import TA
from finta import utils

BTCUSDT = utils.resample(BTCUSDT, "15m")
BTCUSDT

Error message:

C:\Users\Kobe\anaconda3\lib\site-packages\finta\utils.py:19: FutureWarning: using a dict with renaming is deprecated and will be removed in a future version.

For column-specific groupby renaming, use named aggregation

    >>> df.groupby(...).agg(name=('column', aggfunc))

  return df.resample(interval).agg(d)

Add ichimoku cloud color green/red

Please let me know if this would be possible:

    'cloud_green': df['senkou_span_a'] > df['senkou_span_b'],
    'cloud_red': df['senkou_span_b'] > df['senkou_span_a']

Mark Whistler's WAVE PM Indicator

Hello, first of all thanks for your awesome work!

Not a strong programmer myself so I've been struggling to convert this indicator into python code.
I think it will be an interesting addition to the indicator list, it deals with volatility mostly. I currently only have it in c++ code from prorealcode, which is the most understandable version of it.

Here is some information on the code and the discussions on it.
https://www.prorealcode.com/prorealtime-indicators/mark-whistlers-wave-pm/

https://www.tradingview.com/chart/BTCUSD/6SIl2X3f-The-Holy-Grail-of-Trading-Advanced-Volatility-Theory/

http://fxcodebase.com/code/viewtopic.php?f=38&t=64011
https://www.prorealcode.com/topic/possible-to-code-this-in-prt/

help needed: how to pull indicator value from all time frame at one shot?

help wanted on how to pull an indicator value from all time-frame at one shot?

on TradingView, i pull out these values from an indicator

['GBPUSD', 'M: -53.00460785710888', 'W: -53.00460785710888', 'D: -18.48497324001634', 'H4: -7.875243664717016', 'H1: -33.94957983193184', 'M30: -32.47422680412316', 'M15: -22.485207100590525', 'M5: -31.232876712327133', 'M2: -41.45454545454205']
['GBPUSD']

let's take RSI as a sample,
TA.RSI(ohlc).tail(10) will pull out for Daily and the past 10 days. i would like to see current data.

no idea how to get these info hence asking for help

pandas 1.03
python 3.7.6

CCI output not matching with Tv results ;OBV result too not matching with tradingview

Tested this TA.CCI(df) output comparing with tradingview.com(TV) chart inbuilt CCI ,the output is not matching .

In finta.py did a small change and the output CCI is almost closest to tradingview output but not sure how this is very close to the result shown in TV.

Modified Code:def CCI(cls... part
tp = cls.TP(ohlc)
return pd.Series(
(tp - tp.rolling(window=period,center=False).mean()) / (0.015 * tp.rolling(window=period,center=False).std()),
name="{0} period CCI".format(period),
)

Here is the calculation method ,TV is the standard worldwide proven indicator methods ,it would be good if we see your indicator output same as TV result. I have checked many source yours is very closest.Run the above code you will get only 20points differrence in the result.

In summary if we calculate the "Mean Deviation" correctly the output will be matching with global standards.

There are several steps involved in calculating the Commodity Channel Index.
The following example is for a typical 20 Period CCI:

CCI = (Typical Price - 20 Period SMA of TP) / (.015 x Mean Deviation)

Typical Price (TP) = (High + Low + Close)/3

Constant = .015
The Constant is set at .015 for scaling purposes.
By including the constant, the majority of CCI values will fall within the 100 to -100 range.

There are three steps to calculating the Mean Deviation.

  1. Subtract the most recent 20 Period Simple Moving from each typical price (TP) for the Period.
  2. Sum these numbers strictly using absolute values.
  3. Divide the value generated in step 3 by the total number of Periods (20 in this case).

Why is the result different depending on the size of input dataframe?

Thank you for the good library!
I want to ask a question that I am not sure if it is my fault or a library issue.

I calculated MACD with 100rows of 1 minute ohlcv historical data.
First, I calculated it with whole 100 rows, and then I calculated it with last 80 rows.
And I saw that result of MACD and SIGNAL of same row (ex. index 99) of each calculation is different.

For example,

df = pd.read_csv("my_ohlcv.csv") #size of my_ohlcv is 100rows
result1 = TA.MACD(df)
df = df.iloc[-80:]
result2 = TA.MACD(df)

print(result1['MACD'].iloc[-1], result2['MACD']iloc[-1])

I expected result1.iloc[-1] and result2.iloc[-1] would be same, but the value was a little bit different.
But when I calculated CCI with same way I did with MACD, this problem doesn't happened and 2 results was totally identical.
Why these things happens with MACD? Do I need bigger size of data for accurate MACD calculation? I also tested it with more than 200rows, but result was not identical either.

I'm using python3.6.9

Future Bias

So I was experimenting with some data and it turned out that the VORTEX indicator does just have insane predictive performance. Except it does not. In finta/finta.py line 987, the it reads:

VMP = pd.Series(ohlc["high"] - ohlc["low"].shift(-1).abs())

But actually the .shift(-1) shifts values from 1 in the future to the present. Probably .shift(1) was intended, correct me if I'm wrong. Someone should go through the code and carefully review all ocurrences of .shift(-n)

STOCH formula

Hi,
shouldn't the formula for STOCH be (ohlc['close'] - lowest_low) / (highest_high - lowest_low)
instead of (highest_high - ohlc['close']) / (highest_high - lowest_low) ?

And another question,
is there a reason we have min_periods=period - 1 in SMA and some other indicators?
Seems weird to get the first average over period-1 instead of period (like the rest).
In addition, it seems inconsistent for SMA to produce one more row than WMA.

Thanks!

TA.EV_MACD UnboundLocalError: local variable 'x' referenced before assignment

Example:
import finta
print(df)
macd = finta.TA.EV_MACD(df)

Output(Partial)
open close high low volume
2018-03-19 264.293667 261.528421 265.308880 259.720376 109208442.0
2018-03-20 261.963513 261.973181 262.669327 261.228692 59757271.0
2018-03-21 261.924838 261.470409 264.216318 261.238361 78709578.0
2018-03-22 259.033899 254.934374 259.962094 254.634645 148785916.0
2018-03-23 255.417809 249.500570 255.775550 249.287859 183534751.0
[446 rows x 5 columns]

macd = finta.TA.EV_MACD(df)

File "/home/xxx/.local/lib/python3.6/site-packages/finta/finta.py", line 517, in EV_MACD
evwma_slow = cls.EVWMA(ohlcv, period_slow)
File "/home/xxx/.local/lib/python3.6/site-packages/finta/finta.py", line 317, in EVWMA
for x, y in zip(x.fillna(0).iteritems(), y.iteritems()):
UnboundLocalError: local variable 'x' referenced before assignment

Versions:
python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

Pandas 0.25.3

Ichimoku Cloud

I've read the code on the ichimoku cloud, would it be possible to make variables (9,26,52,26) to be malleable so we can do:

TA.ichimoku(ohcl, 20,60,120,30)
in an easy way rather than modifying the code from finta, if this can be done already, please let me know

Thanks!

Misleading documentation in readme.md

I think the readme contains a slightly wrong and misleading section.

From the readme.md:

select only price column, resample by time period and return daily ohlc (you can choose different time period)
ohlc = df["close"].resample("24h").ohlc()

This does not work / make sense, since pd.Series does not have a ohlc() method.

I'm not sure what this tries to accomplish either, since utils.resample does require a dataframe, not a single series.

finta/finta/utils.py

Lines 14 to 19 in 21a4242

def resample(df: pd.DataFrame, interval: str) -> pd.DataFrame:
"""Resample DataFrame by <interval>."""
d = {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"}
return df.resample(interval).agg(d)

2nd misleading section:

standardize column names of your source
df.columns = ["date", 'close', 'volume']

I think this should include all ohlc[v] columns - to be in line with the comment 2 lines before that:

finta expects properly formated ohlc DataFrame, with column names in lowercase:
["open", "high", "low", close"] and ["volume"] for indicators that expect ohlcv input.

RSI does not match TV

RSI calc does not match Tradingview RSI calculation. Please match calculations. Thanks.

WMA Calculation

Hi,
Thanks a lot for this very useful project, hoping to be helpful I'm submitting this issue about WMA function.

Seems that there are a couple of problem in the WMA calculation

The first one is that the series reversing is not needed
(line 283 finta.py) _weights = pd.Series(np.arange(1, period + 1))
(line 284 finta.py) weights = _weights.iloc[::-1] # reverse the series

(new line) weights = pd.Series(np.arange(1, period + 1))

The second is on line 292:
(line 292 finta.py) close_ = ohlc["close"].rolling(period, min_periods=period)
the fixed value "close" doesn't work if for example the WMA function is called by HMA one, the HMA use to calculate on custom field (not on close)

(NEW line 292 finta.py) close_ = ohlc[column].rolling(period, min_periods=period)

Thanks

STC returns wrong values

The STC indicator should returns nan, -inf, and values -/+ x thousands every time I use it.
The STC indicator should return values between 0 and 100.

I feed the function with dataframe from Binance which is compatible with the ohlc format you required.

` time open high low close volume date

0 1.593015e+12 42.41 42.54 42.41 42.54 404.91309 2020-06-24 16:02:00

1 1.593015e+12 42.54 42.56 42.48 42.54 891.49911 2020-06-24 16:03:00

2 1.593015e+12 42.55 42.57 42.50 42.53 273.67014 2020-06-24 16:04:00

3 1.593015e+12 42.53 42.56 42.51 42.55 1502.95409 2020-06-24 16:05:00

4 1.593015e+12 42.54 42.54 42.35 42.37 7764.08264 2020-06-24 16:06:00
.. ... ... ... ... ... ... ...
`

Thanks for your work and your time.

Mobo breakout indicator

How implementing MOBO indicator (Momentum breakout)?
It's a derivative of the a Bollinger band but:
"MOBO bands are based on a zone of 0.80 standard deviation with a 10 period look-back"
If the price breaks out of the MOBO band it can signify a trend move or price spike
Explanation around 3:58 of video
https://www.youtube.com/watch?v=Y6q06t4mp2c

One thinkscript implementation that might help:

#Bollinger Bands MOBO(MOmentum BreakOut) [Thinkscript]
#============================================
#Explanation of how this works. +/- 0.8 std deviation Bollinger Bands are the criteris for bullish/bearish plots. When the close rises above the upper band the signal is bullish and stays bullish until the ose moves below the lower band when the plot turns to bearish and remains bearish until the close rises above the upper band.
input MOBO_length = 10;#hint MOBO_length:The agg-bars used in the standard deviation(SD) calculation to define the upper and lower bands.
input Num_Dev_Dn = -0.8;#hint Num_Dev_Dn:The SD of the lower band. Similar to the 2,0 SD used in the Bollinger Bands
input Num_Dev_up = 0.8;#hint Num_Dev_up:The SD of the upper band. Similar to the 2,0 SD used in the Bollinger Bands

def sDev = StDev(data = c, length = MOBO_length);
def Midmobo = Average(c, length = MOBO_length);
def Lowermobo = Midmobo + Num_Dev_Dn * sDev;
def Uppermobo = Midmobo + Num_Dev_up * sDev;

RSI returned shape

In RSI I don't thin we need [1:] in
delta = ohlc['close'].diff()[1:].
It causes the returned series to have one less row. If we just write
delta = ohlc['close'].diff() then it's the correct shape with nan in the, previously missing, first row.

Two minor exceptions

Hello, nice lib!

However, there are two minor exceptions:

  File ".../finta.py", line 554, in STOCHD
    return pd.Series(cls.STOCHK(ohlc).rolling(center=False, window=period, min_periods=period-1).mean(), name="STOCH %D")
AttributeError: type object 'TA' has no attribute 'STOCHK
  File ".../finta.py", line 108, in VIDYA
    raise NotImplemetedError  
NameError: name 'NotImplemetedError' is not defined

Explore RuntimeWarning in Fisher

finta.py:1180: RuntimeWarning: divide by zero encountered in log
return pd.Series((np.log((1 + smooth) / (1 - smooth))).ewm(span=3).mean()

Resampling causes exception (with pandas 1.0.3)

I am trying to do simple resampling with the resample, like this:

resample(data, "5d")

Data contains just normal OHLC data, other calls like TA.ATR work on this data but resample and resample_calendar throw the following exception:

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    data = resample(data, "5d")
  File "/home/ppawel/.local/lib/python3.7/site-packages/finta/utils.py", line 19, in resample
    return df.resample(interval).agg(d)
  File "/home/ppawel/.local/lib/python3.7/site-packages/pandas/core/resample.py", line 281, in aggregate
    result, how = self._aggregate(func, *args, **kwargs)
  File "/home/ppawel/.local/lib/python3.7/site-packages/pandas/core/base.py", line 357, in _aggregate
    raise SpecificationError("nested renamer is not supported")
pandas.core.base.SpecificationError: nested renamer is not supported

I am currently using pandas 1.0.3 in this project.

Any hints or is that perhaps incompatibility with pandas 1.0?

Edit: I can confirm that it works as expected with pandas 0.25.

Example code

I am trying using this fantastic library. But i have some issues. Is there any example code? I want to learn using pandas datasets and finta together.

What did I do wrong about my BBANDS?

Hi!

Here is my program that uses Pandas and Finta and MatPlotLib to chart the dataframe.: https://gist.github.com/Industrial/597379bd4ba5168c26e49a9be8817a91/a195a385dd170fa81ca597240418eb178f3ff5dc

I am trying to add Bollinger Bands, and later a Keltner Channel and after that create my own indicator "Squeeze" which uses a BB and a KC and implement it in te same fashion as Finta methods. I hope to at some point land at BUY/SELL signals in a column and one final "Equity" which would model out what would happen to your equity over time running this"algorithm". Does that sound like a correct approach?

What is currently not working is this: big bb

  1. How do I get the BBANDS values normal?
  2. I added the Standard Deviation as a column because It's used in a BBand and in your BBANDS implementation and I am noticing that it's value is linear across the whole thing. Is that a bug or?

gr,

Tom

Bug Vortex Indicator

The Vortex Indicator is not correctly implemented.

This should be the correct implementation based on this rules https://www.investopedia.com/terms/v/vortex-indicator-vi.asp :

VMP = pd.Series((ohlc["high"] - ohlc["low"].shift(1)).abs())
VMM = pd.Series((ohlc["low"] - ohlc["high"].shift(1)).abs())

VMPx = VMP.rolling(window=period).sum()
VMMx = VMM.rolling(window=period).sum()
TR = cls.TR(ohlc).rolling(window=period).sum()

VIp = pd.Series(VMPx / TR, name="VIp").interpolate(method="index")
VIm = pd.Series(VMMx / TR, name="VIm").interpolate(method="index")

return pd.concat([VIm, VIp], axis=1)

ZLEMA not using any EMA

The ZLEMA function seems to only return the transformed data (before handling it to the ema method) but doesn't actually perform the EMA on the data.

The method code is:

       lag = (period - 1) / 2
        return pd.Series(
            (ohlc["close"] + (ohlc["close"].diff(lag))),
            name="{0} period ZLEMA.".format(period),
        )

Which doesn't include any EMA i.e. it is missing the last step in the ZLEMA pseudocode: https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average

Williams Fractal indicator implementation

https://learn.tradimo.com/technical-analysis-how-to-work-with-indicators/fractals-indicator

https://www.tradingview.com/script/Uyv9vQc2-Williams-Fractals-Tutorial-Template/

https://www.prorealcode.com/prorealtime-indicators/bill-williams-fractals/

This indicator is hot and widely used, I think it would be a very valuable addition to Finta. As plus, is not available in TA-lib or others. Note that I have edited the title because it's not FRAMA but, "Williams Fractal" which is different.

Mass Index - missing values

After creating and adding the mass index indicator in the following format

from finta import TA
dataframe['mi']=TA.MI(dataframe, 9)

i'm only getting the last 9 values of mass index.

Any help would be greatly appreciated.

Values

                          date     open     high      low    close       volume         mi     deltawma       vama10  buy  sell

...
6782 2019-10-10 14:00:00+00:00  8482.39  8510.00  8456.68  8489.98  1635.848476        NaN  8027.641851  8547.883619    0     0
6783 2019-10-10 15:00:00+00:00  8489.74  8555.40  8472.80  8540.69  1716.237902        NaN  8038.541924  8548.552000    0     0
6784 2019-10-10 16:00:00+00:00  8540.73  8573.93  8509.06  8526.18  1649.275602        NaN  8050.143981  8547.282667    0     0
6785 2019-10-10 17:00:00+00:00  8525.90  8542.15  8488.14  8489.87   850.972090        NaN  8063.350510  8545.511810    0     0
6786 2019-10-10 18:00:00+00:00  8489.87  8531.08  8482.20  8519.47  1089.157289        NaN  8076.693470  8539.016286    0     0
6787 2019-10-10 19:00:00+00:00  8519.98  8556.00  8518.24  8554.13   996.493605        NaN  8086.414588  8535.643619    1     0
6788 2019-10-10 20:00:00+00:00  8554.96  8579.96  8530.26  8552.30  1570.403528  23.473755  8096.960645  8527.076381    0     0
6789 2019-10-10 21:00:00+00:00  8551.87  8589.81  8520.00  8546.76  1239.594837  23.446802  8107.979870  8514.458000    0     0
6790 2019-10-10 22:00:00+00:00  8546.00  8570.01  8528.11  8561.00   852.013904  23.413048  8124.975436  8509.463143    0     0
6791 2019-10-10 23:00:00+00:00  8561.16  8568.00  8530.00  8558.03   735.032822  23.348156  8140.008588  8510.675238    0     0
6792 2019-10-11 00:00:00+00:00  8557.82  8572.91  8491.38  8502.41  1609.400042  23.454690  8154.769788  8511.984762    0     0
6793 2019-10-11 01:00:00+00:00  8502.41  8528.81  8475.00  8525.32  1125.748941  23.593241  8169.234850  8511.672000    1     0
6794 2019-10-11 02:00:00+00:00  8525.35  8527.98  8483.93  8508.85  1038.794517  23.736796  8186.737581  8520.223524    0     0
6795 2019-10-11 03:00:00+00:00  8509.16  8557.00  8499.41  8553.35   986.502991  23.870550  8204.404730  8526.969619    1     0
6796 2019-10-11 04:00:00+00:00  8552.47  8711.11  8530.82  8698.00  4005.058525  24.326677  8223.514110  8534.366190    0     0 

STOCH period parameter in STOCHD

I used period=5 for calculating a STOCH column and when I created a STOCHD column I realised that the library uses the default period=14 for calculating STOCH inside STOCHD which results in wrong calculations if we used a different period for STOCH e.g. period=5.

Could we have an additional parameter for STOCH's period in the STOCHD signature?
Alternatively, from a quick google search I realised the STOCHD always uses period=3, so maybe pass the period from STOCHD to STOCH and set the rolling window inside STOCHD to 3?

Implementation

I have tried and tried to format my panda dataframe to make this library work on it, but, I keep getting 'close' problems. I'll copy the error here along with the printout of my dataframe.

The error comes up from this line in the code:

TA.SMA(dataTA, 42)

                       date      open      high       low     close   volume
0       01/18/2020 17:00:00  0.000311  0.000311  0.000311  0.000311   1371.0
1       01/18/2020 17:01:00  0.000311  0.000311  0.000312  0.000312  13969.0
2       01/18/2020 17:02:00  0.000312  0.000312  0.000312  0.000312   2263.0
3       01/18/2020 17:03:00  0.000312  0.000311  0.000312  0.000312   8030.0
4       01/18/2020 17:04:00  0.000312  0.000311  0.000312  0.000311  11789.0
...                     ...       ...       ...       ...       ...      ...
276820  07/29/2020 14:42:00  0.000636  0.000636  0.000638  0.000636   2347.7
276821  07/29/2020 14:43:00  0.000636  0.000636  0.000637  0.000636   1028.5
276822  07/29/2020 14:44:00  0.000637  0.000637  0.000638  0.000637    442.4
276823  07/29/2020 14:45:00  0.000637  0.000636  0.000637  0.000636    399.9
276824  07/29/2020 14:46:00  0.000636  0.000634  0.000636  0.000634   2370.4

[276825 rows x 6 columns]
Traceback (most recent call last):
  File "/home/relskhan/anaconda3/envs/tesr/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ohlcGraphing.py", line 65, in <module>
    TA.SMA(dataTA, 42)
  File "/home/relskhan/anaconda3/envs/tesr/lib/python3.7/site-packages/finta/finta.py", line 18, in SMA
    ohlc[column].rolling(window=period).mean(),
  File "/home/relskhan/anaconda3/envs/tesr/lib/python3.7/site-packages/pandas/core/frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/relskhan/anaconda3/envs/tesr/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'close'

The one thing I'm curious about is how to formate that 'date' column. The example only shows by the day, I'm trying to get all the info by the minute and then use built in library to resample. I keep thinking that the date column has to be causing a problem here ... even though it says the 'close' column?

I'm using Python 3.7.6 in Anaconda, I pulled finTA from here.

Bug Vortex Indicator

Issue #61 addressed this but only the TR rolling issue was implemented.

VMP and VMM values need to be absolute values. like shown below.

VMP = pd.Series((ohlc["high"] - ohlc["low"].shift(1)).abs())
VMM = pd.Series((ohlc["low"] - ohlc["high"].shift(1)).abs())

VMPx = VMP.rolling(window=period).sum()
VMMx = VMM.rolling(window=period).sum()
TR = cls.TR(ohlc).rolling(window=period).sum()

VIp = pd.Series(VMPx / TR, name="VIp").interpolate(method="index")
VIm = pd.Series(VMMx / TR, name="VIm").interpolate(method="index")

return pd.concat([VIm, VIp], axis=1)

The code for VORTEX currently has this (no parenthesis around columns being subtracted and calling abs() on that):

VMP = pd.Series(ohlc["high"] - ohlc["low"].shift().abs())
VMM = pd.Series(ohlc["low"] - ohlc["high"].shift().abs())

Why take tailing end of rolling sum in VORTEX

 def VORTEX(cls, ohlc, period=14):

        VMP = pd.Series(ohlc['high'] - ohlc['low'].shift(-1).abs())
        VMM = pd.Series(ohlc['low'] - ohlc['high'].shift(-1).abs())

        VMPx = VMP.rolling(window=period).sum().tail(period)
        VMMx = VMM.rolling(window=period).sum().tail(period)

        VIp = pd.Series(VMPx / cls.TR(ohlc), name='VIp').interpolate(method='index')
        VIm = pd.Series(VMMx / cls.TR(ohlc), name='VIm').interpolate(method='index')

        return pd.concat([VIm, VIp], axis=1)

Why are you taking the tail() for VMPx and VMMx? This will just grab the last 14 values of that sum instead of taking the rolling sum of the whole array. Maybe I am missing something?

Using groupby apply with TA.HMA

Hi,

First, thank you for a great library.

I have been trying to apply TA.HMA to a dataframe structured like this:

                                        open        high         low         close         volume  
date                      symbol                                                                   
2019-09-15 00:00:00+00:00 BTC     10363.2000  10380.0000  10270.1000    10311.3000    1190.540645  
                          ETC         6.3660      6.4490      6.3010        6.3230    3848.955337  
                          XTZ         1.0000      1.0194      0.9863        1.0062  110247.320200  
                          XMR        75.9400     76.4300     74.0100       75.7000     976.875002  
                          BCH       305.0000    307.6000    302.1000      303.0000    1771.432299  
2019-09-16 00:00:00+00:00 BTC     10311.3000  10374.7000  10311.2000    10329.0000     353.164112  
                          ETC         6.3230      6.4490      6.3230        6.4150    1027.900751  
                          EOS         4.0707      4.1461      4.0707        4.0948   16762.763057  
                          XMR        75.7000     76.2500     75.4800       75.9300     353.116738  
                          XTZ         1.0062      1.0077      1.0020        1.0039    5323.913412  

Where date and symbol are used as indices. But when running:

df['hma'] = df.groupby('symbol').apply(lambda x:TA.HMA(x))

I get:

TypeError: incompatible index of inserted column with frame index

(full error output attached: error.txt)

Any ideas as to what I'm doing wrong or do you have any examples of how to do this?

Thank you,

Luis

Set custom series name

Hi, first of all THANK YOU FOR THIS AWESOME LIBRARY
A question:
how can we set custom series name? At the moment it seems not possible setting a custom series name, we must rename it after return. Do you think could be useful to pass an optional parameter to set a custom series name?

Brands needs to be rolling for std?

Hi. Think I might have spotted an issue with the bbands coding.. the window isn't rolling so it gives a single value. Switching it to ohlc["close"].rolling(window=period).std() fixed it for me.
Apologies if I'm wrong. Quite new to python. Cheers.

Implementing regression tests

Implement regtests against widely used Ta-Lib.

Ta-Lib is not the most accurate library out there, but it is widely used and a good reference. Goal is the check if values produced by finta are in the same "ballpark" as the numbers produced by the Ta-Lib. Ta-Lib specifically has problems with length of the dataset, as explained here: https://www.quantopian.com/posts/ta-lib-rsi-using-something-other-than-close-price.

Regtests should enable use to gauge out which finta indicators are absolutely incorrect and should be refactored.

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.