I'm using pyalgotrade to write a trading algo. I got the error above and can't seem to fix it. I'm trying to use the "SLOW STOCHASTIC", any help on solving this error and getting the slow stochastic to work is greatly appreciated:
Error:
C:\Users\...\Desktop>python bobo.py
Traceback (most recent call last):
File "bobo.py", line 114, in <module>
main()
File "bobo.py", line 110, in main
run_strategy(10,inst,2,14,5,2,3)
File "bobo.py", line 102, in run_strategy
myStrategy = MyStrategy(feed, inst, smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period)
File "bobo.py", line 26, in __init__
self.__stoch = indicator.STOCH(self.__prices,fastk_period,slowk_period,slowd_period)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 803, in STOCH
ret = call_talib_with_hlc(barDs, count, talib.STOCH, fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 93, in call_talib_with_hlc
high = bar_ds_high_to_numpy(barDs, count)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 45, in bar_ds_high_to_numpy
return value_ds_to_numpy(barDs.getHighDataSeries(), count)
AttributeError: 'SequenceDataSeries' object has no attribute 'getHighDataSeries'
Code:
from pyalgotrade.tools import yahoofinance
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import stoch
from pyalgotrade import dataseries
from pyalgotrade.technical import ma
from pyalgotrade import technical
from pyalgotrade.technical import highlow
from pyalgotrade import bar
from pyalgotrade.talibext import indicator
from pyalgotrade.technical import rsi
import numpy
import talib
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed,instrument,smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period):
strategy.BacktestingStrategy.__init__(self, feed, 1000) #change portfolio amount
self.__position = None
self.__instrument = instrument
self.setUseAdjustedValues(True)
self.__prices = feed[instrument].getPriceDataSeries()
self.__sma = ma.SMA(self.__prices, smaPeriod)
self.__ema = ma.EMA(self.__prices, emaPeriod)
self.__rsi = rsi.RSI(self.__prices, rsiPeriod)
self.__stoch = indicator.STOCH(self.__prices,fastk_period,slowk_period,slowd_period)
Now I'm getting the error:
Traceback (most recent call last):
File "bobo.py", line 103, in <module>
main()
File "bobo.py", line 99, in main
run_strategy(inst,10,250,14,5,5,5)
File "bobo.py", line 90, in run_strategy
myStrategy = MyStrategy(feed, inst, smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period)
File "bobo.py", line 28, in __init__
self.__stoch = indicator.STOCH(feed[instrument],fastk_period,slowk_period,slowd_period)
File "C:\Users\JDOG\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 803, in STOCH
ret = call_talib_with_hlc(barDs, count, talib.STOCH, fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
File "C:\Users\JDOG\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 105, in call_talib_with_hlc
return talibFunc(high, low, close, *args, **kwargs)
File "talib/func.pyx", line 9388, in talib.func.STOCH (talib\func.c:87125)
Exception: inputs are all NaN
Try this:
self.__stoch = indicator.STOCH(feed[instrument],fastk_period,slowk_period,slowd_period)
The stochastic oscillator is expecting a bar dataseries, not a regular one.
Related
I am having a problem with python and pyopengl
I am just importing the modules, and getting errors, I checked and pip did install opengl and everything.
Here is my code
# ulWindow
import ulMath as ulm
import OpenGL.GL as gl
import OpenGL.GlE as gle
import glfw
def init() ->int|str:
if (not glfw.init()):
return "GLFW Failed to initialize"
return 0
And the error im getting:
Traceback (most recent call last):
File "src/ulWindow.py", line 3, in <module>
import OpenGL.GL as gl
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/GL/__init__.py", line 4, in <module>
from OpenGL.GL.VERSION.GL_1_1 import *
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/GL/VERSION/GL_1_1.py", line 14, in <module>
from OpenGL.raw.GL.VERSION.GL_1_1 import *
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/raw/GL/VERSION/GL_1_1.py", line 7, in <module>
from OpenGL.raw.GL import _errors
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/raw/GL/_errors.py", line 4, in <module>
_error_checker = _ErrorChecker( _p, _p.GL.glGetError )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/error.py", line 183, in __init__
self._isValid = platform.CurrentContextIsValid
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 356, in CurrentContextIsValid
return self.GetCurrentContext
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/egl.py", line 106, in GetCurrentContext
return self.EGL.eglGetCurrentContext
AttributeError: 'NoneType' object has no attribute 'eglGetCurrentContext'
I have absolutely no clue what is going on, can someone help me out?
We have used "Office365-REST-Python-Client 2.3.11" library to upload file on sharepoint.
Suddenly code stopped working and started giving below issue.
code:
import json
from office365.runtime.auth.user_credential import UserCredential
from office365.runtime.http.request_options import RequestOptions
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
request = RequestOptions("{0}/_api/web/".format(site_url))
response = ctx.execute_request_direct(request)
json = json.loads(response.content)
web_title = json['d']['Title']
print("Web title: {0}".format(web_title))
Error:
Traceback (most recent call last):
File "test_upload.py", line 81, in <module>
response = ctx.execute_request_direct(request)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/client_runtime_context.py", line 131, in execute_request_direct
return self.pending_request().execute_request_direct(self._normalize_request(request))
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/odata/odata_request.py", line 36, in execute_request_direct
return super(ODataRequest, self).execute_request_direct(request)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/client_request.py", line 91, in execute_request_direct
self.context.authenticate_request(request)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/sharepoint/client_context.py", line 230, in authenticate_request
self._auth_context.authenticate_request(request)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/auth/authentication_context.py", line 89, in authenticate_request
self._provider.authenticate_request(request)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/auth/providers/saml_token_provider.py", line 77, in authenticate_request
self.ensure_authentication_cookie()
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/auth/providers/saml_token_provider.py", line 84, in ensure_authentication_cookie
self._cached_auth_cookies = self.get_authentication_cookie()
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/auth/providers/saml_token_provider.py", line 97, in get_authentication_cookie
token = self._acquire_service_token_from_adfs(user_realm.STSAuthUrl)
File "/home/ubuntu/atlas/national_kpi_table/venv/lib/python3.8/site-packages/office365/runtime/auth/providers/saml_token_provider.py", line 140, in _acquire_service_token_from_adfs
assertion_node = dom.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", 'Assertion')[0].toxml()
IndexError: list index out of range
Any help appreciated.
Code:
from aiohttp import web
from aiortc.mediastreams import MediaStreamTrack
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaPlayer
import asyncio
import json
import os
from multiprocessing import Process, freeze_support
from queue import Queue
import sys
import threading
from time import sleep
import fractions
import time
class RadioServer(Process):
def __init__(self,q):
super().__init__()
self.q = q
self.ROOT = os.path.dirname(__file__)
self.pcs = []
self.channels = []
self.stream_offers = []
self.requests = []
def run(self):
self.app = web.Application()
self.app.on_shutdown.append(self.on_shutdown)
self.app.router.add_get("/", self.index)
self.app.router.add_get("/radio.js", self.javascript)
self.app.router.add_get("/jquery-3.5.1.min.js", self.jquery)
self.app.router.add_post("/offer", self.offer)
threading.Thread(target=self.fill_the_queues).start()
web.run_app(self.app, access_log=None, host="192.168.1.20", port="8080", ssl_context=None)
def fill_the_queues(self):
while(True):
frame = self.q.get()
for stream_offer in self.stream_offers:
stream_offer.q.put(frame)
async def index(self,request):
content = open(os.path.join(self.ROOT, "index.html"), encoding="utf8").read()
return web.Response(content_type="text/html", text=content)
async def javascript(self,request):
content = open(os.path.join(self.ROOT, "radio.js"), encoding="utf8").read()
return web.Response(content_type="application/javascript", text=content)
async def jquery(self,request):
content = open(os.path.join(self.ROOT, "jquery-3.5.1.min.js"), encoding="utf8").read()
return web.Response(content_type="application/javascript", text=content)
async def offer(self,request):
params = await request.json()
offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
self.pcs.append(pc)
self.requests.append(request)
# prepare epalxeis media
self.stream_offers.append(CustomRadioStream())
pc.addTrack(self.stream_offers[-1])
#pc.on("iceconnectionstatechange")
async def on_iceconnectionstatechange():
if pc.iceConnectionState == "failed":
self.pcs.remove(pc)
self.requests.remove(request)
print(str(request.remote)+" disconnected from radio server")
print("Current peer connections:"+str(len(self.pcs)))
# handle offer
await pc.setRemoteDescription(offer)
# send answer
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.Response(content_type="application/json",text=json.dumps({"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}))
async def on_shutdown(self,app):
# close peer connections
if self.pcs:
coros = [pc.close() for pc in self.pcs]
await asyncio.gather(*coros)
self.pcs = []
self.channels = []
self.stream_offers = []
"""
some other classes here such as CustomRadioStream and RadioOutputStream
"""
if __name__ == "__main__":
freeze_support()
q = Queue()
custom_server_child_process = RadioServer(q)
custom_server_child_process.start()
Error
Traceback (most recent call last):
File "123.py", line 106, in <module>
custom_server_child_process.start()
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/process.py", line 121, i
n start
self._popen = self._Popen(self)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 224, i
n _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 327, i
n _Popen
return Popen(process_obj)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/popen_spawn_win32.py", l
ine 93, in __init__
reduction.dump(process_obj, to_child)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/reduction.py", line 60,
in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_thread.lock' object
What I am doing wrong?
If I call the run function (instead of start) directly, then there is no problem, but i want to use processing for this class.
Edit: Ok with multiprocessing.Queue works fine but now with similar code there is this error:
$ python "Papinhio_player.py"
Traceback (most recent call last):
File "Papinhio_player.py", line 3078, in <module>
program = PapinhioPlayerCode()
File "Papinhio_player.py", line 250, in __init__
self.manage_decks_instance = Manage_Decks(self)
File "C:\python\scripts\Papinhio player\src\main\python_files/manage_decks.py"
, line 356, in __init__
self.custom_server_child_process.start()
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/process.py", line 121, i
n start
self._popen = self._Popen(self)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 224, i
n _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/context.py", line 327, i
n _Popen
return Popen(process_obj)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/popen_spawn_win32.py", l
ine 93, in __init__
reduction.dump(process_obj, to_child)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/reduction.py", line 60,
in dump
ForkingPickler(file, protocol).dump(obj)
File "stringsource", line 2, in av.audio.codeccontext.AudioCodecContext.__redu
ce_cython__
TypeError: self.parser,self.ptr cannot be converted to a Python object for pickl
ing
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/spawn.py", line 116, in
spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:/msys64/mingw64/lib/python3.8/multiprocessing/spawn.py", line 126, in
_main
self = reduction.pickle.load(from_parent)
EOFError: Ran out of input
Some objects cannot be serialized then unserialized.
The stack trace you posted mentions :
TypeError: cannot pickle '_thread.lock' object
a lock, which holds a state in memory and gives guarantees that no other process can own the same lock at the same moment, is typically a very bad candidate for this operation -- what should be created when you deserialize it ?
To fix this : choose a way to select the relevant fields of the object you want to serialize, and pickle/unpickle that part.
i am stuck in this error, i know the function "clock" has removed, but the problem is, i cant find the function code in the code
code:
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from skimage.transform import resize
from IPython.display import HTML
import warnings
warnings.filterwarnings("ignore")
source_image =imageio.imread(r"C:\Users\jpdyb\Documents\first-order\workspace\02.png")
reader =imageio.get_reader(r"C:\Users\jpdyb\Documents\first-order\workspace\04.mp4")
#Resize image and video to 256x256
source_image = resize(source_image, (256, 256))[..., :3]
fps = reader.get_meta_data()['fps']
driving_video = [r"C:\Users\jpdyb\Documents\first-order\workspace\04.mp4"]
try:
for im in reader:
driving_video.append(im)
except RuntimeError:
pass
reader.close()
driving_video = [resize(frame, (256, 256))[..., :3] for frame in driving_video]
def display(source, driving, generated=None):
fig = plt.figure(figsize=(8 + 4 * (generated is not None), 6))
ims = []
for i in range(len(driving)):
cols = [source]
cols.append(driving[i])
if generated is not None:
cols.append(generated[i])
im = plt.imshow(np.concatenate(cols, axis=1), animated=True)
plt.axis('off')
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, repeat_delay=1000)
plt.close()
return ani
HTML(display(source_image, driving_video).to_html5_video())
error (python):
Traceback (most recent call last):
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
import resource
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'resource'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jpdyb\Documents\first-order\python system\load images.py", line 6, in <module>
from IPython.display import HTML
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\__init__.py", line 49, in <module>
from .terminal.embed import embed
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
from IPython.terminal.ipapp import load_default_config
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
from IPython.core.magics import ScriptMagics
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
from .execution import ExecutionMagics
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
from IPython.utils.timing import clock, clock2
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'
We have a model that uses Dataportal of Pyomo to read parameter from several csv files. On a Windows laptop we are running into the following error while this is not replicable on another computer. Any ideas what might be missing in this setting?
Traceback (most recent call last):
File "", line 1, in
runfile('C:/Users/stianbac/OneDrive - NTNU/EMPIRE/EMPIRE in Pyomo/EMPIRE_Pyomo_version_4/Empire_draft4.py',
wdir='C:/Users/stianbac/OneDrive - NTNU/EMPIRE/EMPIRE in
Pyomo/EMPIRE_Pyomo_version_4')
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 710, in runfile
execfile(filename, namespace)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/stianbac/OneDrive - NTNU/EMPIRE/EMPIRE in
Pyomo/EMPIRE_Pyomo_version_4/Empire_draft4.py", line 107, in
instance = model.create_instance(data)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyomo\core\base\DataPortal.py",
line 138, in load
self.connect(**kwds)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyomo\core\base\DataPortal.py",
line 98, in connect
self._data_manager.open()
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyomo\core\plugins\data\sheet.py",
line 54, in open
self.sheet = ExcelSpreadsheet(self.filename, ctype=self.ctype)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyutilib\excel\spreadsheet.py",
line 79, in new
return ExcelSpreadsheet_win32com(*args, **kwds)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyutilib\excel\spreadsheet_win32com.py",
line 59, in init
self.open(filename, worksheets, default_worksheet)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\pyutilib\excel\spreadsheet_win32com.py",
line 80, in open
self._ws[wsid] = self.wb.Worksheets.Item(wsid)
File
"C:\Users\stianbac\AppData\Local\Continuum\anaconda3\lib\site-packages\win32com\client\dynamic.py",
line 516, in getattr
ret = self.oleobj.Invoke(retEntry.dispid,0,invoke_type,1)
com_error: (-2147418111, 'Call was rejected by callee.', None, None)
Here is the entry of the code:
from __future__ import division
from pyomo.environ import *
#from pyomo.core.expr import current as EXPR
#import numpy as np
import math
import csv
model = AbstractModel()
model.Nodes = Set()
model.Generators = Set() #g
...
data = DataPortal()
data.load(filename='Sets.xlsx',range='B1:B53',using='xlsx',format="set", set=model.Generators)
data.load(filename='Sets.xlsx',range='nodes',using='xlsx',format="set", set=model.Nodes)
...
instance = model.create_instance(data)
...