I have the following code meant to extract my outlook calendar and show me a list of all participants in the meetings that I have scheduled.. I am running into the following error related to datatypes. I believe the issue is actually getting the events to pull because when I print the appointments list prior to the error, it shows as blank. Thoughts?
Code:
import datetime as dt
import pandas as pd
import win32com.client
def get_calendar(begin,end):
outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
calendar = outlook.getDefaultFolder(9).Items
calendar.IncludeRecurrences = True
calendar.Sort('[Start]')
restriction = "[Start] >= '" + begin.strftime('%m/%d/%Y') + "' AND [END] <= '" + end.strftime('%m/%d/%Y') + "'"
calendar = calendar.Restrict(restriction)
return calendar
def get_appointments(calendar,subject_kw = None,exclude_subject_kw = None, body_kw = None):
if subject_kw == None:
appointments = [app for app in calendar]
else:
appointments = [app for app in calendar if subject_kw in app.subject]
if exclude_subject_kw != None:
appointments = [app for app in appointments if exclude_subject_kw not in app.subject]
cal_subject = [app.subject for app in appointments]
cal_start = [app.start for app in appointments]
cal_end = [app.end for app in appointments]
cal_body = [app.body for app in appointments]
df = pd.DataFrame({'subject': cal_subject,
'start': cal_start,
'end': cal_end,
'body': cal_body})
return df
def make_cpd(appointments):
appointments['Date'] = appointments['start']
appointments['Hours'] = (appointments['end'] - appointments['start']).dt.seconds/3600
appointments.rename(columns={'subject':'Meeting Description'}, inplace = True)
appointments.drop(['start','end'], axis = 1, inplace = True)
summary = appointments.groupby('Meeting Description')['Hours'].sum()
return summary
final = r"C:\Users\rcarmody\Desktop\Python\Accelerators\Outlook Output.xlsx"
begin = dt.datetime(2021,1,1)
end = dt.datetime(2021,5,12)
print(begin)
print(end)
cal = get_calendar(begin, end)
appointments = get_appointments(cal, subject_kw = 'weekly', exclude_subject_kw = 'Webcast')
result = make_cpd(appointments)
result.to_excel(final)
Error:
Traceback (most recent call last):
File "C:\Users\Desktop\Python\Accelerators\outlook_meetings.py", line 50, in <module>
result = make_cpd(appointments)
File "C:\Users\Desktop\Python\Accelerators\outlook_meetings.py", line 34, in make_cpd
appointments['Hours'] = (appointments['end'] - appointments['start']).dt.seconds/3600
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\pandas\core\generic.py", line 5461, in __getattr__
return object.__getattribute__(self, name)
File "C:\Users\rcarmody\AppData\Roaming\Python\Python39\site-packages\pandas\core\accessor.py", line 180, in __get__
accessor_obj = self._accessor(obj)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexes\accessors.py", line 494, in __new__
raise AttributeError("Can only use .dt accessor with datetimelike values")
AttributeError: Can only use .dt accessor with datetimelike values
[Finished in 1.2s]
New Error:
Traceback (most recent call last):
File "C:\Users\Desktop\Python\Accelerators\outlook_meetings.py", line 50, in <module>
result = make_cpd(appointments)
File "C:\Users\Desktop\Python\Accelerators\outlook_meetings.py", line 34, in make_cpd
appointments['Hours'] = (appointments['end'] - appointments['start']) / pd.Timedelta(hours=1)
File "C:\Users\\AppData\Roaming\Python\Python39\site-packages\pandas\core\ops\common.py", line 65, in new_method
return method(self, other)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\pandas\core\arraylike.py", line 113, in __truediv__
return self._arith_method(other, operator.truediv)
File "C:\Users\\AppData\Roaming\Python\Python39\site-packages\pandas\core\series.py", line 4998, in _arith_method
result = ops.arithmetic_op(lvalues, rvalues, op)
File "C:\Users\\AppData\Roaming\Python\Python39\site-packages\pandas\core\ops\array_ops.py", line 185, in arithmetic_op
res_values = op(lvalues, rvalues)
File "pandas\_libs\tslibs\timedeltas.pyx", line 1342, in pandas._libs.tslibs.timedeltas.Timedelta.__rtruediv__
numpy.core._exceptions.UFuncTypeError: ufunc 'true_divide' cannot use operands with types dtype('float64') and dtype('<m8[ns]')
The substraction of two datetime objects results in a timedelta object. In order to retrieve hours from timedelta objects you can use :
import numpy as np
hours = timedelta_object / np.timedelta64(1, "h")
Note: it could also be (more pandas-only style)
hours = timedelta_object / pd.Timedelta(hours=1)
So in your case, you would use it as :
appointments['Hours'] = (appointments['end'] - appointments['start']) / pd.Timedelta(hours=1)
Related
Here is my code that I am using:
import warnings
import datetime
import numpy as np
import pandas as pd
import pandas_datareader.data as pdr
import matplotlib.pyplot as plt, mpld3
import matplotlib.ticker as mtick
date_from = datetime.date(2020, 1, 1)
date_to = datetime.date(2022, 12, 30)
tickerL = 'BTC-USD'
print("Comparing " + tickerL +" to...")
\#tickerL2 = \['AAPL'\]
tickerL2 = input('Now enter your comparison ticker:\\n')
tickerList = \[tickerL, tickerL2\]
print(tickerList)
\#tickerList = \['BTC-USD', 'AMZN', 'AAPL', 'CL=F', '^GSPC', '^DJI', 'GC=F'\]
\#fetch multiple asset data
def getMultiAssetData(tickerList, date_from, date_to):
def getData(ticker):
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
return data
datas = map(getData, tickerList)
return pd.concat(datas, keys=tickerList, names=['Ticker', 'Date'])
sort=False
multiData = getMultiAssetData(tickerList, date_from, date_to)
df = multiData.copy()
\#print(df)
df = df.loc\[tickerL, :\]
df.tail()
Now I keep getting this error and I don't know how to move forward:
Traceback (most recent call last):
File "main.py", line 51, in \<module\>
multiData = getMultiAssetData(tickerList, date_from, date_to)
File "main.py", line 45, in getMultiAssetData
datas = list(map(getData, tickerList))
File "main.py", line 42, in getData
data = pdr.DataReader(ticker, "yahoo", date_from, date_to)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/util/\_decorators.py", line 207, in wrapper
return func(\*args, \*\*kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/data.py", line 370, in DataReader
return YahooDailyReader(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/base.py", line 253, in read
df = self.\_read_one_data(self.url, params=self.\_get_params(self.symbols))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas_datareader/yahoo/daily.py", line 153, in \_read_one_data
data = j\["context"\]\["dispatcher"\]\["stores"\]\["HistoricalPriceStore"\]
TypeError: string indices must be integers
This script worked just fine a couple of months ago but I assume some of the packages got updated and now require different format.
If I make a call for only one cryptocurrency it works, but for multiple it fails.
import pandas_datareader as pdr
...
crypto_df = pdr.DataReader('BTC-USD', data_source = 'yahoo', start = '2015-01-01')
works fine
crypto_df = pdr.DataReader('ETH-USD', data_source = 'yahoo', start = '2015-01-01')
also works fine
crypto_df = pdr.DataReader(['BTC-USD', 'ETH-USD'], data_source = 'yahoo', start = '2015-01-01')
fails with the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/alex/.local/lib/python3.8/site-packages/pandas/util/_decorators.py", line 199, in wrapper
return func(*args, **kwargs)
File "/home/alex/.local/lib/python3.8/site-packages/pandas_datareader/data.py", line 376, in DataReader
return YahooDailyReader(
File "/home/alex/.local/lib/python3.8/site-packages/pandas_datareader/base.py", line 258, in read
df = self._dl_mult_symbols(self.symbols)
File "/home/alex/.local/lib/python3.8/site-packages/pandas_datareader/base.py", line 285, in _dl_mult_symbols
result = concat(stocks, sort=True).unstack(level=0)
File "/home/alex/.local/lib/python3.8/site-packages/pandas/core/frame.py", line 7349, in unstack
result = unstack(self, level, fill_value)
File "/home/alex/.local/lib/python3.8/site-packages/pandas/core/reshape/reshape.py", line 417, in unstack
return _unstack_frame(obj, level, fill_value=fill_value)
File "/home/alex/.local/lib/python3.8/site-packages/pandas/core/reshape/reshape.py", line 444, in _unstack_frame
return _Unstacker(
File "/home/alex/.local/lib/python3.8/site-packages/pandas/core/reshape/reshape.py", line 118, in __init__
self._make_selectors()
File "/home/alex/.local/lib/python3.8/site-packages/pandas/core/reshape/reshape.py", line 167, in _make_selectors
raise ValueError("Index contains duplicate entries, cannot reshape")
This works as expected with stocks, but fails with cryptocurrency.
I'm confident this is not an issue on my side, but I am hoping someone can confirm. I will open a ticket with the developers if this is an unknown bug.
You need to define the index you want to fetch.
#Trying to fetch crypto data from yahoo
from pandas_datareader import data as wb
tickers = ['BTC-USD', 'ETH-USD']
crypto_data = pd.DataFrame()
for t in tickers:
crypto_data[t] = wb.DataReader(t, data_source ='yahoo', start= '2020-12-01')['Adj Close']
You are missing ['Adj Close'] in this case.
I have a problem where two almost identical html files create different behavior on the code. If i choose the HTML file in the first picture, pandasGUI will load the dataframe just fine. However if i choose second HTML file, it throws a typeerror as stated in the title. I have tried to fix this on and off for three weeks and i am completely lost. Can anyone help? Code below.
import pandas as pd
from scipy.interpolate import interp1d
from pandasgui import show
pd.set_option('display.max_columns', 100)
pd.set_option('precision', 3)
file = ''
def choose_file():
global file
i = input("Please choose an option below: \n"
"1: Own Team \n"
"2: Shortlist \n")
if (i == '1'):
file = './own_team.html'
elif (i == '2'):
file = './shortlist.html'
return file
file = choose_file()
attribute_view = pd.read_html(file)
map = interp1d([1, 7000], [1, 100])
df = attribute_view[0]
if(file == './shortlist.html'):
for column in ['Inf', 'Name', 'Age', 'Best Pos', 'Personality', 'Acc', 'Wor', 'Vis', 'Thr', 'Tec', 'Tea', 'Tck', 'Str', 'Sta', 'TRO', 'Ref', 'Pun', 'Pos', 'Pen', 'Pas', 'Pac', '1v1', 'OtB', 'Nat', 'Mar', 'L Th', 'Lon', 'Ldr', 'Kic', 'Jum', 'Hea', 'Han', 'Fre', 'Fla', 'Fir', 'Fin', 'Ecc', 'Dri', 'Det', 'Dec', 'Cro', 'Cor', 'Cnt', 'Cmp', 'Com', 'Cmd', 'Bra', 'Bal', 'Ant', 'Agi', 'Agg', 'Aer']:
df[column] = df[column].replace('-', 0)
print(df)
df['Team_dna'] = (df['Agg'] + df['Ant'] + df['Det'] + df['Tea'] + df['Wor'] + df['Acc'] + df['Sta'])
# Sweeper Keeper - Attack
df['sk_at'] = map((df['Aer'] + df['Com'] + df['Fir'] + df['Han'] + df['Pas'] + df['Ref'] + df['TRO'] + df['Thr'] + df['Cmp'] + df['Dec'] + df['Vis'] + df['Acc']) * 40)
EDIT:
Full traceback:
Please choose an option below:
1: Own Team
2: Shortlist
2
Traceback (most recent call last):
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 149, in na_arithmetic_op
result = expressions.evaluate(op, str_rep, left, right)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\computation\expressions.py", line 208, in evaluate
return _evaluate(op, op_str, a, b)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\computation\expressions.py", line 70, in _evaluate_standard
return op(a, b)
TypeError: can only concatenate str (not "int") to str
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Github/FM20-Analysis/FM.py", line 36, in <module>
df['sk_at'] = map((df['Aer'] + df['Com'] + df['Fir'] + df['Han'] + df['Pas'] + df['Ref'] + df['TRO'] + df['Thr'] + df['Cmp'] + df['Dec'] + df['Vis'] + df['Acc']) * 40)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\common.py", line 64, in new_method
return method(self, other)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\__init__.py", line 503, in wrapper
result = arithmetic_op(lvalues, rvalues, op, str_rep)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 197, in arithmetic_op
res_values = na_arithmetic_op(lvalues, rvalues, op, str_rep)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 151, in na_arithmetic_op
result = masked_arith_op(left, right, op)
File "C:\Users\Pottemuld\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\ops\array_ops.py", line 94, in masked_arith_op
result[mask] = op(xrav[mask], yrav[mask])
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
the second image has values '-' in some columns. This will cast the entire column to a string and you won't be able to run arithmetic operations. This should do!
df = df.replace('-', 0)
everybody,
I'm trying to automate the allocation of inventory. Since I am not an experienced programmer, I have difficulties in creating the logic.
The goal is to combine two Excel files and add a column containing the responsible persons/departments. What I have managed so far is to combine the Excel files and add the column "Reviser". Now this column must be filled with the right persons/departments.
The logic behind this is not very difficult, but I don't really know how to do this with Python/Pandas etc.
I already tried to fix this problem with np.where but that doesn´t fix the problem completely.
Here you can see the logic behind the assignment of the revisor:
[Logic behind assignment][1]
Thanks for your help!
My current code:
import pandas as pd
import numpy as np
from openpyxl import Workbook
Q_Stock = pd.read_excel("C:\\Users\\Lucas\\Desktop\\Excel_Test\\Q Bestand.xlsx",usecols=["Bestandsqualifikation", "Inhalt", "Benutzerfeld 1", "Benutzerfeld 2","Material", "Externer Barcode 2", "Handling Unit"])
""" Q_Bestand["Bearbeiter"] = "" """
Q_Stocknew = Q_Stock[0:-1]
S_Stock = pd.read_excel("C:\\Users\\Lucas\\Desktop\\Excel_Test\\S Bestand.xlsx",usecols=["Bestandsqualifikation", "Inhalt", "Benutzerfeld 1", "Benutzerfeld 2","Material", "Externer Barcode 2", "Handling Unit" ])
""" S_Bestand["Bearbeiter"] = "" """
S_Stocknew = S_Stock[0:-1]
complete_list = [S_Stocknew, Q_Stocknew]
Combined = pd.concat(complete_list)
df = pd.DataFrame
def bar(df):
if Combined['Inhalt'] ==np.nan:
return np.nan
elif str(Combined['Inhalt']).contains("QV"):
return "Distribution"
elif str(Combined['Inhalt']).contains("QP"):
return "Production"
elif (Combined['Benutzerfeld 2'] == "ruckschnitt") and (str(Combined['Material']).contains("^09")):
return "Person 1"
df["Reviser"] = Combined.apply(bar, axis = 1)
Combined.to_excel(r'C:\\Users\Lucas\\Desktop\\Excel_Test\\Test.xlsx', index = True)
Which throws out this error now:
C:\Python\Code\venv\Scripts\python.exe C:/Python/Code/SAP_Automatisieren.py
Traceback (most recent call last):
File "C:/Python/Code/SAP_Automatisieren.py", line 29, in
df["Reviser"] = Combined.apply(bar, axis = 1)
File "C:\Python\Code\venv\lib\site-packages\pandas\core\frame.py", line 6878, in apply
return op.get_result()
File "C:\Python\Code\venv\lib\site-packages\pandas\core\apply.py", line 186, in get_result
return self.apply_standard()
File "C:\Python\Code\venv\lib\site-packages\pandas\core\apply.py", line 295, in apply_standard
result = libreduction.compute_reduction(
File "pandas_libs\reduction.pyx", line 620, in pandas._libs.reduction.compute_reduction
File "pandas_libs\reduction.pyx", line 128, in pandas._libs.reduction.Reducer.get_result
File "C:/Python/Code/SAP_Automatisieren.py", line 19, in bar
if Combined['Inhalt'] ==np.nan:
File "C:\Python\Code\venv\lib\site-packages\pandas\core\generic.py", line 1478, in nonzero
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
import numpy as np
from openpyxl import Workbook
Q_Stock = pd.read_excel("C:\\Users\\Lucas\\Desktop\\Excel_Test\\Q Bestand.xlsx",usecols=["Bestandsqualifikation", "Inhalt", "Benutzerfeld 1", "Benutzerfeld 2","Material", "Externer Barcode 2", "Handling Unit"])
""" Q_Bestand["Bearbeiter"] = "" """
Q_Stocknew = Q_Stock[0:-1]
S_Stock = pd.read_excel("C:\\Users\\Lucas\\Desktop\\Excel_Test\\S Bestand.xlsx",usecols=["Bestandsqualifikation", "Inhalt", "Benutzerfeld 1", "Benutzerfeld 2","Material", "Externer Barcode 2", "Handling Unit" ])
""" S_Bestand["Bearbeiter"] = "" """
S_Stocknew = S_Stock[0:-1]
complete_list = [S_Stocknew, Q_Stocknew]
Combined = pd.concat(complete_list)
df = pd.DataFrame
def bar(Combined):
if Combined['Inhalt'] ==np.nan:
return np.nan
elif str(Combined['Inhalt']).contains("QV"):
return "Distribution"
elif str(Combined['Inhalt']).contains("QP"):
return "Production"
elif (Combined['Benutzerfeld 2'] == "ruckschnitt") and (str(Combined['Material']).contains("^09")):
return "Person 1"
df["Reviser"] = Combined.apply(bar, axis = 1)
Error:
C:\Python\Code\venv\Scripts\python.exe C:/Python/Code/SAP_Automatisieren.py
Traceback (most recent call last):
File "C:/Python/Code/SAP_Automatisieren.py", line 28, in
df["Reviser"] = Combined.apply(bar, axis = 1)
File "C:\Python\Code\venv\lib\site-packages\pandas\core\frame.py", line 6878, in apply
return op.get_result()
File "C:\Python\Code\venv\lib\site-packages\pandas\core\apply.py", line 186, in get_result
return self.apply_standard()
File "C:\Python\Code\venv\lib\site-packages\pandas\core\apply.py", line 295, in apply_standard
result = libreduction.compute_reduction(
File "pandas_libs\reduction.pyx", line 620, in pandas._libs.reduction.compute_reduction
File "pandas_libs\reduction.pyx", line 128, in pandas._libs.reduction.Reducer.get_result
File "C:/Python/Code/SAP_Automatisieren.py", line 21, in bar
elif str(Combined['Inhalt']).contains("QV"):
AttributeError: 'str' object has no attribute 'contains'
You can write a function like below and apply this to your dataframe. You can also write a nested np.where but below function will be more readable for you coming from Excel world
def bar(df):
if df['Inventory Qualifikation'] ==np.nan:
return np.nan
elif str(df['Inventory Qualifikation']).contains("QV"):
return "Distribution"
elif str(df['Inventory Qualifikation']).contains("QP"):
return "Production"
elif (df['Userfield 2'] == "ruckschnitt") and (str(df['material']).contains("^09")):
return "Person 1"
df['reviser'] = df.apply(bar, axis = 1)
I'm trying to write various predicates on simple candle stick structures. For example one component of a '3 green candles in a row' predicate would require a look back of -4
To start off simple I try an test it with a 'higher_highs' predicate. If the close of the previous candle is below the current candles close the function returns true. Below is my code:
from pyalgotrade import eventprofiler
from pyalgotrade.barfeed import csvfeed
class single_event_strat( eventprofiler.Predicate ):
def __init__(self,feed):
pass
def higher_highs(self, instrument, bards):
#prev_three = bards[-4]
#prev_two = bards[-3]
prev = bards[-2]
curr = bards[-1]
if prev.getOpen() < curr.getOpen():
return True
return False
def eventOccurred(self, instrument, bards):
if self.higher_highs(instrument, bards):
return True
else:
return False
def main(plot):
feed = csvfeed.GenericBarFeed(0)
feed.addBarsFromCSV('FCT', "FCT_daily_converted.csv")
predicate = single_event_strat(feed)
eventProfiler = eventprofiler.Profiler( predicate, 20, 20)
eventProfiler.run(feed, True)
results = eventProfiler.getResults()
print "%d events found" % (results.getEventCount())
if plot:
eventprofiler.plot(results)
if __name__ == "__main__":
main(True)
However I get an IndexError :
Traceback (most recent call last):
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 44, in <module>
main(True)
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 36, in main
eventProfiler.run(feed, True)
File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 215, in run
disp.run()
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 102, in run
eof, eventsDispatched = self.__dispatch()
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 90, in __dispatch
if self.__dispatchSubject(subject, smallestDateTime):
File "C:\Python27\lib\site-packages\pyalgotrade\dispatcher.py", line 68, in __dispatchSubject
ret = subject.dispatch() is True
File "C:\Python27\lib\site-packages\pyalgotrade\feed\__init__.py", line 105, in dispatch
self.__event.emit(dateTime, values)
File "C:\Python27\lib\site-packages\pyalgotrade\observer.py", line 59, in emit
handler(*args, **kwargs)
File "C:\Python27\lib\site-packages\pyalgotrade\eventprofiler.py", line 172, in __onBars
eventOccurred = self.__predicate.eventOccurred(instrument, self.__feed[instrument])
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 20, in eventOccurred
if self.higher_highs(instrument, bards):
File "C:\Users\David\Desktop\Python\Coursera\Computational Finance\Week2\PyAlgoTrade\Bitfinex\FCT\FCT_single_event_test.py", line 11, in higher_highs
prev = bards[-2]
File "C:\Python27\lib\site-packages\pyalgotrade\dataseries\__init__.py", line 90, in __getitem__
return self.__values[key]
File "C:\Python27\lib\site-packages\pyalgotrade\utils\collections.py", line 141, in __getitem__
return self.__values[key]
IndexError: list index out of range
I'm still trying to figure out how the EP works. It's interesting because in the buyongap example there is a look back period of bards[-2],
def __gappedDown(self, instrument, bards):
ret = False
if self.__stdDev[instrument][-1] is not None:
prevBar = bards[-2]
currBar = bards[-1]
low2OpenRet = (currBar.getOpen(True) - prevBar.getLow(True)) / float(prevBar.getLow(True))
if low2OpenRet < (self.__returns[instrument][-1] - self.__stdDev[instrument][-1]):
ret = True
return ret
however it's nestled in if self.__stdDev[instrument][-1] is not None: statement, my predicate requires no TA indicators, so how could I access the previous bards?
The problem is that on the first call to eventOccurred bards only has one item, so trying to do bards[-2] will fail. Check the length of bards first.