Pyalgotrade Tutorial Attribute Error - python

I have been googling for a while now, but am still unable to find a solution, or even determine the problem, honestly.
My installation of Python and Pyalgotrade is correct, as verified by the successful imports.
Nonetheless, I can't manage to run the example code in the tutorial, it always throws:
AttributeError: MyStrategy instance has no attribute 'info'
Here's the example code:
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed)
self.__instrument = instrument
def onBars(self, bars):
bar = bars[self.__instrument]
self.info(bar.getClose())
# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()
And the iPython Notebook output:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-1-f786d1b471f7> in <module>()
18 # Evaluate the strategy with the feed's bars.
19 myStrategy = MyStrategy(feed, "orcl")
---> 20 myStrategy.run()
/usr/local/lib/python2.7/site-packages/pyalgotrade/strategy/__init__.pyc in run(self)
398 self.onStart()
399
--> 400 self.__dispatcher.run()
401
402 if self.__feed.getCurrentBars() != None:
/usr/local/lib/python2.7/site-packages/pyalgotrade/observer.pyc in run(self)
139 subject.start()
140
--> 141 while not self.__stopped and self.__dispatch():
142 pass
143 finally:
/usr/local/lib/python2.7/site-packages/pyalgotrade/observer.pyc in __dispatch(self)
131 nextDateTime = subject.peekDateTime()
132 if nextDateTime == None or nextDateTime == smallestDateTime:
--> 133 subject.dispatch()
134 return ret
135
/usr/local/lib/python2.7/site-packages/pyalgotrade/feed/__init__.pyc in dispatch(self)
95 dateTime, values = self.getNextValuesAndUpdateDS()
96 if dateTime != None:
---> 97 self.__event.emit(dateTime, values)
98
99 def getKeys(self):
/usr/local/lib/python2.7/site-packages/pyalgotrade/observer.pyc in emit(self, *parameters)
51 self.__emitting = True
52 for handler in self.__handlers:
---> 53 handler(*parameters)
54 self.__emitting = False
55 self.__applyChanges()
/usr/local/lib/python2.7/site-packages/pyalgotrade/strategy/__init__.pyc in __onBars(self, dateTime, bars)
386
387 # 1: Let the strategy process current bars and place orders.
--> 388 self.onBars(bars)
389
390 # 2: Place the necessary orders for positions marked to exit on session close.
<ipython-input-1-f786d1b471f7> in onBars(self, bars)
10 def onBars(self, bars):
11 bar = bars[self.__instrument]
---> 12 self.info(bar.getClose())
13
14 # Load the yahoo feed from the CSV file
AttributeError: MyStrategy instance has no attribute 'info'
Has anyone at least a hint on what the problem could be?

Which version of PyAlgoTrade are you using ?
import pyalgotrade
print pyalgotrade.__version__

Copied from question:
So, I updated PyAlgoTrade to 0.15, and now the sample code works. I did not investigate the cause of the error yet, but can safely say that 0.15 works as expected.

Related

create_collection() got an unexpected keyword argument 'embedding_fn'

I was trying to use the langchain library to create a question answering system. But when I try to search in the document using the chromadb library it gives this error:
TypeError: create_collection() got an unexpected keyword argument 'embedding_fn'
Here's the code am working on
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.document_loaders import TextLoader
from langchain.vectorstores import Chroma
loader = TextLoader('./info.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = Chroma.from_documents(texts, embeddings).
The last line generates the error.
This is the complete error message:
TypeError Traceback (most recent call last)
Input In [36], in <cell line: 1>()
----> 1 docsearch = Chroma.from_documents(texts, embeddings)
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:212, in Chroma.from_documents(cls, documents, embedding, ids, collection_name, persist_directory, **kwargs)
210 texts = [doc.page_content for doc in documents]
211 metadatas = [doc.metadata for doc in documents]
--> 212 return cls.from_texts(
213 texts=texts,
214 embedding=embedding,
215 metadatas=metadatas,
216 ids=ids,
217 collection_name=collection_name,
218 persist_directory=persist_directory,
219 )
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:178, in Chroma.from_texts(cls, texts, embedding, metadatas, ids, collection_name, persist_directory, **kwargs)
151 #classmethod
152 def from_texts(
153 cls,
(...)
160 **kwargs: Any,
161 ) -> Chroma:
162 """Create a Chroma vectorstore from a raw documents.
163
164 If a persist_directory is specified, the collection will be persisted there.
(...)
176 Chroma: Chroma vectorstore.
177 """
--> 178 chroma_collection = cls(
179 collection_name=collection_name,
180 embedding_function=embedding,
181 persist_directory=persist_directory,
182 )
183 chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)
184 return chroma_collection
File ~\anaconda3\lib\site-packages\langchain\vectorstores\chroma.py:65, in Chroma.__init__(self, collection_name, embedding_function, persist_directory)
60 logger.warning(
61 f"Collection {collection_name} already exists,"
62 " Do you have the right embedding function?"
63 )
64 else:
---> 65 self._collection = self._client.create_collection(
66 name=collection_name,
67 embedding_fn=self._embedding_function.embed_documents
68 if self._embedding_function is not None
69 else None,
70 )
TypeError: create_collection() got an unexpected keyword argument 'embedding_fn'
The create_collection method of chromadb.Client was changed 2 days ago and the embedding_fn parameter was renamed to embedding_function:
https://github.com/chroma-core/chroma/commit/6ce2388e219d47048e854be72be54617df647224
The source code for the langchain.vectorstores.chroma.Chroma class as of version 0.0.87 seems to have been updated already (3 hours before you asked the question) to match the chromadb library:
https://github.com/hwchase17/langchain/commit/34cba2da3264ccc9100f7efd16807c8d2a51734c
So you should be able to fix the problem by installing the newest version of LangChain.

NotFoundError while using pickle dump to save a model

I have created a model named 'model' but when I'm trying to save it using pickle it just gives an 'NotFoundError'.
import pickle
with open("test.pkl","wb") as file:
pickle.dump(model, file)
This is the error message I get upon running the code.
Error message
INFO:tensorflow:Assets written to: ram://471dfd58-f3fe-4d9f-9075-60a1568cc629/assets
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
<ipython-input-47-0abd122520e5> in <module>
1 import pickle
2 with open("test.pkl","wb") as file:
----> 3 pickle.dump(model, file)
~\anaconda3\lib\site-packages\keras\engine\training.py in __reduce__(self)
313 if self.built:
314 return (pickle_utils.deserialize_model_from_bytecode,
--> 315 pickle_utils.serialize_model_as_bytecode(self))
316 else:
317 # SavedModel (and hence serialize_model_as_bytecode) only support
~\anaconda3\lib\site-packages\keras\saving\pickle_utils.py in serialize_model_as_bytecode(model)
75 with tf.io.gfile.GFile(dest_path, "rb") as f:
76 info = tarfile.TarInfo(name=os.path.relpath(dest_path, temp_dir))
---> 77 info.size = f.size()
78 archive.addfile(tarinfo=info, fileobj=f)
79 tf.io.gfile.rmtree(temp_dir)
~\anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py in size(self)
97 def size(self):
98 """Returns the size of the file."""
---> 99 return stat(self.__name).length
100
101 def write(self, file_content):
~\anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py in stat(filename)
908 errors.OpError: If the operation fails.
909 """
--> 910 return stat_v2(filename)
911
912
~\anaconda3\lib\site-packages\tensorflow\python\lib\io\file_io.py in stat_v2(path)
924 errors.OpError: If the operation fails.
925 """
--> 926 return _pywrap_file_io.Stat(compat.path_to_str(path))
927
928
NotFoundError:
Any help would be massively appreciated
Not a solution but hopefully it still helps.
I had the same problem, and the same error. I ended up avoiding it by using Keras save and load methods instead of pickle. I don't know what your model is but you might want to try the same. It might be due to what is pickeleable. Maybe the answer given to this helps, they argue for saving tensorflow object separately.

File error while running the tutorial06 "Networks from OpenStreetMap" from FLOW project

I'm learning the FLOW project and doing their tutorial06 "Networks from OpenStreetMap". In this tutorial, one should be able to use the .osm file to run the simulation. However, there is an error raised, that the .xml of the network config files are missing.
The code in jupyter-notebook is as following:
# the TestEnv environment is used to simply simulate the network
from flow.envs import TestEnv
# the Experiment class is used for running simulations
from flow.core.experiment import Experiment
# all other imports are standard
from flow.core.params import VehicleParams
from flow.core.params import NetParams
from flow.core.params import InitialConfig
from flow.core.params import EnvParams
from flow.core.params import SumoParams
from flow.networks import Network
net_params = NetParams(
osm_path='networks/bay_bridge.osm'
)
# create the remainding parameters
env_params = EnvParams()
sim_params = SumoParams(render=True)
initial_config = InitialConfig()
vehicles = VehicleParams()
vehicles.add('human', num_vehicles=100)
flow_params = dict(
exp_tag='bay_bridge',
env_name=TestEnv,
network=Network,
simulator='traci',
sim=sim_params,
env=env_params,
net=net_params,
veh=vehicles,
initial=initial_config,
)
# number of time steps
flow_params['env'].horizon = 1000
exp = Experiment(flow_params)
# run the sumo simulation
_ = exp.run(1)
and I got the error:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-13-4a3adf64a06c> in <module>
13 # number of time steps
14 flow_params['env'].horizon = 1000
---> 15 exp = Experiment(flow_params)
16
17 # run the sumo simulation
~/Desktop/flow/flow/core/experiment.py in __init__(self, flow_params, custom_callables)
79
80 # Create the environment.
---> 81 self.env = create_env()
82
83 logging.info(" Starting experiment {} at {}".format(
~/Desktop/flow/flow/utils/registry.py in create_env(*_)
128 })
129
--> 130 return gym.envs.make(env_name)
131
132 return create_env, env_name
~/anaconda3/envs/flow/lib/python3.6/site-packages/gym/envs/registration.py in make(id, **kwargs)
154
155 def make(id, **kwargs):
--> 156 return registry.make(id, **kwargs)
157
158 def spec(id):
~/anaconda3/envs/flow/lib/python3.6/site-packages/gym/envs/registration.py in make(self, path, **kwargs)
99 logger.info('Making new env: %s', path)
100 spec = self.spec(path)
--> 101 env = spec.make(**kwargs)
102 # We used to have people override _reset/_step rather than
103 # reset/step. Set _gym_disable_underscore_compat = True on
~/anaconda3/envs/flow/lib/python3.6/site-packages/gym/envs/registration.py in make(self, **kwargs)
71 else:
72 cls = load(self.entry_point)
---> 73 env = cls(**_kwargs)
74
75 # Make the enviroment aware of which spec it came from.
~/Desktop/flow/flow/envs/base.py in __init__(self, env_params, sim_params, network, simulator, scenario)
162 # use the network class's network parameters to generate the necessary
163 # network components within the network kernel
--> 164 self.k.network.generate_network(self.network)
165
166 # initial the vehicles kernel using the VehicleParams object
~/Desktop/flow/flow/core/kernel/network/traci.py in generate_network(self, network)
125 elif self.network.net_params.osm_path is not None:
126 self._edges, self._connections = self.generate_net_from_osm(
--> 127 self.network.net_params)
128 else:
129 # combine all connections into a list
~/Desktop/flow/flow/core/kernel/network/traci.py in generate_net_from_osm(self, net_params)
577
578 # collect data from the generated network configuration file
--> 579 edges_dict, conn_dict = self._import_edges_from_net(net_params)
580
581 return edges_dict, conn_dict
~/Desktop/flow/flow/core/kernel/network/traci.py in _import_edges_from_net(self, net_params)
841 net_path = os.path.join(self.cfg_path, self.netfn) \
842 if net_params.template is None else self.netfn
--> 843 tree = ElementTree.parse(net_path, parser=parser)
844 root = tree.getroot()
845
~/anaconda3/envs/flow/lib/python3.6/xml/etree/ElementTree.py in parse(source, parser)
1194 """
1195 tree = ElementTree()
-> 1196 tree.parse(source, parser)
1197 return tree
1198
~/anaconda3/envs/flow/lib/python3.6/xml/etree/ElementTree.py in parse(self, source, parser)
584 close_source = False
585 if not hasattr(source, "read"):
--> 586 source = open(source, "rb")
587 close_source = True
588 try:
FileNotFoundError: [Errno 2] No such file or directory: '/home/anjie/Desktop/flow/flow/core/kernel/network/debug/cfg/bay_bridge_20200623-1345091592912709.4246037.net.xml'
I guess that, the in FLOW project, they try to use the 'netconvert' from SUMO to convert .xml files to the sumoconfig files. However, it fails at this step, that the .osm cannot be converted. But still, I cannot fix the error. BTW, the previous 5 tutorials can be run correctly.
I'm the author of this question. After investigating for hours, I found that the problem is the following command:
netconvert --osm bay_bridge.os
Error: Cannot import network data without PROJ-Library. Please install packages proj before building sumo
Quitting (on error).
Therefore, the problem is that the SUMO is not built with PROJ, and then I tried to re-build the SUMO with PROJ. However, I always encounter the problem with proj_api.h, which is not found by the ./configure command, but exists in /usr/local/includes/.
Thus, I looked into the config.log file from sumo source files, and it said:
configure:12501: checking proj_api.h usability
configure:12501: g++ -c -msse2 -mfpmath=sse -std=c++11 -O2 -DNDEBUG conftest.cpp >&5
In file included from conftest.cpp:59:
/usr/local/include/proj_api.h:37:2: error: #error 'To use the proj_api.h you must define the macro ACCEPT_USE_OF_DEPRECATED_PROJ_API_H'
37 | #error 'To use the proj_api.h you must define the macro ACCEPT_USE_OF_DEPRECATED_PROJ_API_H'
So I open the proj_api.h with root and edit the line as follows:
#ifndef ACCEPT_USE_OF_DEPRECATED_PROJ_API_H
//#error 'To use the proj_api.h you must define the macro ACCEPT_USE_OF_DEPRECATED_PROJ_API_H'
#define ACCEPT_USE_OF_DEPRECATED_PROJ_API_H 1
#endif
After all this, I successfully built the SUMO with the PROJ and everything works fine!

sympy+matplotlib not plotting geometric primitives

I'm trying to plot some geometric primitives in ipython (lines, circles, ellipses), following the sympy documentation.
I am using Sympy release 1.1.1 and python 3.5, on the CoCalc system, but can reproduce identical results on my own local installation of ipython and sympy (2.7 and 0.7.6). Here is my code:
from sympy import Point, Circle
from sympy.plotting.plot import Plot
p = Plot(axes='label_axes=True')
c = Circle(Point(0,0), 1)
p[0] = c
Now, when I enter p on an input line, ipython just returns the object but doesn't plot it:
In[2] = p
Out[2] = <sympy.plotting.plot.Plot at 0x7f2e64fe62e8>
The plot command works as expected, so the matplotlib backend is functional.
When I enter p.show(), I get the following error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-02f33f5f7a8f> in <module>()
----> 1 p.show()
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in show(self)
194 self._backend.close()
195 self._backend = self.backend(self)
--> 196 self._backend.show()
197
198 def save(self, path):
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in show(self)
1027
1028 def show(self):
-> 1029 self.process_series()
1030 #TODO after fixing https://github.com/ipython/ipython/issues/1255
1031 # you can uncomment the next line and remove the pyplot.show() call
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in process_series(self)
989 starts = [s.start for s in parent._series]
990 ends = [s.end for s in parent._series]
--> 991 self.ax.set_xlim(min(starts), max(ends))
992 if parent.ylim:
993 self.ax.set_ylim(parent.ylim)
ValueError: min() arg is an empty sequence
It displays and empty set of coordinate axes (without the circle). Also, p.save("foo.png") produces a similar error.
I have also tried p = Plot(Circle((0,0),1) (although this is not what the documentation suggests to do), and again nothing is shown, with p.show() producing another long error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-f1f858abbdb7> in <module>()
1 p = Plot(Circle((0,0),1))
----> 2 p.show()
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in show(self)
193 if hasattr(self, '_backend'):
194 self._backend.close()
--> 195 self._backend = self.backend(self)
196 self._backend.show()
197
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in __new__(cls, parent)
1065 matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
1066 if matplotlib:
-> 1067 return MatplotlibBackend(parent)
1068 else:
1069 return TextBackend(parent)
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in __init__(self, parent)
872 def __init__(self, parent):
873 super(MatplotlibBackend, self).__init__(parent)
--> 874 are_3D = [s.is_3D for s in self.parent._series]
875 self.matplotlib = import_module('matplotlib',
876 __import__kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
/ext/anaconda3/lib/python3.5/site-packages/sympy/plotting/plot.py in <listcomp>(.0)
872 def __init__(self, parent):
873 super(MatplotlibBackend, self).__init__(parent)
--> 874 are_3D = [s.is_3D for s in self.parent._series]
875 self.matplotlib = import_module('matplotlib',
876 __import__kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
AttributeError: 'Circle' object has no attribute 'is_3D'
Those examples are from "pygletplot" module which basically doesn't work (certainly not under Python 3), and hasn't been tested or developed for years. What SymPy can plot:
graphs y=f(x), with plot
parametric curves, with plot_parametric
implicit curves, with plot_implicit
3D graphs z=f(x, y), with plot3d
parametric curves in 3D, with plot3d_parametric_line
parametric surface, with plot3d_parametric_surface

JPype and JayDeBeAPI: AttributeError: 'property' object has no attribute 'isBeanAccessor'

I have built JPype (JPype1-0.5.5.4) along with JayDeBeAPI 0.1.4 in my attempt to connect to a database via JDBC. This is on RHEL. I can successfully connect using the driver,
TrgtCnn = jaydebeapi.connect('com.ibm.as400.access.AS400JDBCDriver',
['jdbc:as400://<mask>','<mask>','<mask>'],
'/app/as/lib/jdbc/jt400.jar')
but I get this traceback in JPype when I execute SQL:
TrgtCrs = TrgtCnn.cursor()
TrgtCrs.execute("SELECT * FROM WA6U999S")
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-5d46ea8c382d> in <module>()
----> 1 TrgtCrs.execute("SELECT * FROM WA6U999S")
/app/as/opt/anaconda/lib/python2.7/site-packages/jaydebeapi/dbapi2.pyc in execute(self, operation, parameters)
356 parameters = ()
357 self._close_last()
--> 358 self._prep = self._connection.jconn.prepareStatement(operation)
359 self._set_stmt_parms(self._prep, parameters)
360 is_rs = self._prep.execute()
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_jclass.pyc in _getClassFor(javaClass)
66 return _CLASSES[name]
67
---> 68 pyJavaClass = _JavaClass(javaClass)
69 _CLASSES[name] = pyJavaClass
70 return pyJavaClass
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_jclass.pyc in __new__(mcs, jc)
123 elif not jc.isInterface():
124 bjc = jc.getBaseClass(jc)
--> 125 bases.append(_getClassFor(bjc))
126
127 if _JAVATHROWABLE is not None and jc.isSubclass("java.lang.Throwable"):
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_jclass.pyc in _getClassFor(javaClass)
66 return _CLASSES[name]
67
---> 68 pyJavaClass = _JavaClass(javaClass)
69 _CLASSES[name] = pyJavaClass
70 return pyJavaClass
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_jclass.pyc in __new__(mcs, jc)
166 for i in _CUSTOMIZERS:
167 if i.canCustomize(name, jc):
--> 168 i.customize(name, jc, bases, members)
169
170 # remove multiple bases that would cause a MRO problem
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_properties.pyc in customize(self, class_name, jc, bases, members)
68
69 def customize(self, class_name, jc, bases, members) :
---> 70 accessor_pairs = _extract_accessor_pairs(members)
71 for attr_name, (getter, setter) in accessor_pairs.items():
72 if attr_name in members:
/app/as/opt/anaconda/lib/python2.7/site-packages/JPype1-0.5.5.4-py2.7-linux-x86_64.egg/jpype/_properties.pyc in _extract_accessor_pairs(members)
46 if _is_java_method(members[property_name]):
47 continue
---> 48 if access == 'get' and member.isBeanAccessor():
49 try:
50 pair = accessor_pairs[property_name]
AttributeError: 'property' object has no attribute 'isBeanAccessor'
I have no idea where to start on this and can't seem to find anything mentioning anything close to this issue.
This appears to be a bug in JPype.
I don't have access to an AS/400 database, but I do have an Oracle XE database lying around and I was able to use that to reproduce the problem. The Python code I used was as follows:
#!/usr/bin/python
import jaydebeapi
conn = jaydebeapi.connect('oracle.jdbc.OracleDriver', ['jdbc:oracle:thin:#localhost:1521:XE', 'user', 'password'])
print conn
I found what I believe to be a fix for the problem, which I have posted to the JPype issue above. This fix was to edit the function _extract_accessor_pairs in jpype/_properties.py, find the following code and replace the or with an and:
for name, member in members.items():
if not (len(name) > _PROPERTY_ACCESSOR_PREFIX_LEN \
or _is_java_method(member)):
continue
# rest of loop omitted...
After making this change, the error I was getting went away. You're welcome to try this fix and see if it works for you too.

Categories

Resources