alvarobartt / trendet

:chart_with_upwards_trend: Python package for trend detection on stock time series data :chart_with_downwards_trend:
https://trendet.readthedocs.io/
MIT License
457 stars 79 forks source link

'int' object has no attribute 'days' #8

Open sefati opened 4 years ago

sefati commented 4 years ago

Hi, I'm using this great python library. I was wondering why I come up with this error: 'int' object has no attribute 'days' my code is here:

import trendet

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

sns.set(style='darkgrid')

dff = pd.read_csv('setran.csv')

df = trendet.identify_df_trends(df=dff , column='Close')

print(df['Up Trend'].values)
df.reset_index(inplace=True)

plt.figure(figsize=(20, 10))

ax = sns.lineplot(x=df.index, y=df['Close'])
ax.set(xlabel='Date')

labels = df['Up Trend'].dropna().unique().tolist()

for label in labels:
    sns.lineplot(x=df[df['Up Trend'] == label].index,
                 y=df[df['Up Trend'] == label]['Close'],
                 color='green')

    ax.axvspan(df[df['Up Trend'] == label].index[0],
               df[df['Up Trend'] == label].index[-1],
               alpha=0.2,
               color='green')

labels = df['Down Trend'].dropna().unique().tolist()

for label in labels:
    sns.lineplot(x=df[df['Down Trend'] == label].index,
                 y=df[df['Down Trend'] == label]['Close'],
                 color='red')

    ax.axvspan(df[df['Down Trend'] == label].index[0],
               df[df['Down Trend'] == label].index[-1],
               alpha=0.2,
               color='red')

locs, _ = plt.xticks()
labels = []

for position in locs[1:-1]:
    labels.append(str(df['Date'].loc[position])[:-9])

plt.xticks(locs[1:-1], labels)
plt.show()

Can you please answer me to solve this issue (or just my problem) ?

alvarobartt commented 4 years ago

Hi @sefati, thank you for reporting this issue and sorry for taking too long to answer!

Could you please share the setran.csv file so that I can see what the problem is? Based on the error code you provided, I can guess that the error is that your index values (the ones from the CSV file) are not dates, and in trendet.identify_df_trends I suppose that the index will be a datetime one. So on, I guess that can also be improved with maybe converting the str date to datetime, raising an error if the index is not datetime, etc.

As soon as you share with me the CSV file I will start working on it! Remember to STAR the repo if you found it useful and FOLLOW ME at GitHub so as to get notified of all the updates!

jackure commented 4 years ago

It is an algorithm bug. This error happens when trends overlap. The algorithm compares the overlap locations and calculates what is the predominant trend. However, the algorithm tries to get an attribute "days" at the interval indices, absurd and wrong of course.

Traceback (most recent call last): File "d:/xx/trend_data/trendet_demo2.py", line 62, in <module> res = trendet.identify_df_trends(df=get_data(), column='Close') File "D:\xx\Python37\lib\site-packages\trendet\identification.py", line 612, in identify_df_trends if (up['to'] - up['from']).days < (down['to'] - down['from']).days: AttributeError: 'int' object has no attribute 'days'

alvarobartt commented 4 years ago

Hi again @jackure, as I told you in the other issue, could you please share with me the data you are using so as to reproduce that error and fix it as soon as possible?

Thank you! Remember to star the repo if you found it useful and follow me at GitHub so as to get notified of all the updates!

thebadguyfromstarwars commented 3 years ago

I am having this exact problem..

clopez131211 commented 3 years ago

Having the same issue when using this file and this file for my data

AAP.csv

ZEN.csv

imtiazsattar commented 9 months ago

Its 2024. Was this issue resolved? Still getting the same error.

taglitis commented 5 months ago

I got the same problem:

I tried to use AAPL data to define trend for the last two years. I set up window_size = 5 it gave, an error below. I changed it to 10, it ran ok. Then, changed the ticker to AMZAN it gave me the error for 5 and 10.

Please, let me know if you have any suggestions

AttributeError Traceback (most recent call last) File G:\My Drive\development\swing\main.py:392 385 print('script is completed') 390 if name == 'main': --> 392 main() 402 # WMA https://corporatefinanceinstitute.com/resources/career-map/sell-side/capital-markets/weighted-moving-average-wma/

File G:\My Drive\development\swing\main.py:284, in main() 280 df['day'] = df['timestamp'].dt.strftime('%Y-%m-%d') 281 # trend_df = alpaca_paral_data_col([ticker], start_date_ms, end_date_ms, timespan = 'day', multiplier=1) 282 # print(f'{ticker} i = {i} trend_df\n', trend_df.head()) 283 # trend_df = sf.trend_define(ticker, start_date_ms, end_date_ms) --> 284 trend_df = sf.trend_define_trendet(ticker, start_date_ms, end_date_ms) 285 print(f'{ticker} i = {i} trend_df\n', trend_df.head()) 286 df = df.merge(trend_df[['ticker', 'day', 'trend']], on=['ticker', 'day'], how='inner')

File G:\My Drive\development\swing\swing_functions.py:197, in trend_define_trendet(ticker, start_date_ms, end_date_ms) 195 trend_df = alpaca_paral_data_col([ticker], start_date_ms, end_date_ms, timespan = 'day', multiplier=1) 196 trend_df['close'] = trend_df['close'].astype('float64') --> 197 trend_df = trendet.identify_df_trends(df=trend_df, 198 column='close', 199 window_size=5, 200 identify='both')#.rename(columns={'Up Trend': 'trend'}) 201 trend_df['trend'] = trend_df['Up Trend'].notnull().replace({True: 'uptrend', False: None}) 202 trend_df['Down Trend'] = trend_df['Down Trend'].notnull().replace({True: 'downtrend', False: None})

File ~\Anaconda3\envs\VENV_SWING_P3_9_11\lib\site-packages\trendet\identification.py:589, in identify_df_trends(df, column, window_size, identify) 587 for down in results['Down Trend']: 588 if down['from'] < up['from'] < down['to'] or down['from'] < up['to'] < down['to']: --> 589 if (up['to'] - up['from']).days > (down['to'] - down['from']).days: 590 flag = True 591 else:

AttributeError: 'int' object has no attribute 'days'