from pyalgotrade import strategy
from pyalgotrade.feed import csvfeed
from pyalgotrade.technical import ma
from pyalgotrade.bar import Frequency
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed, 1000)
# We want a 15 period SMA over the closing prices.
self.__instrument = instrument
self.__sma = ma.SMA(feed[instrument].getDataSeries(instrument), 15)
def onBars(self, bars):
bar = bars[self.__instrument]
print "%s: %s %s" % (bar.getDateTime(), self.__sma[-1])
# Load the yahoo feed from the CSV file
feed = csvfeed.Feed("Date","%Y-%m-%d %H:%M")
feed.addValuesFromCSV("test.csv")
# Evaluate the strategy with the feed's bars.
rules = MyStrategy(feed, "Open")
rules.run()
I'm getting following error:
Traceback (most recent call last):
File "algotrade.py", line 21, in <module>
rules = MyStrategy(feed, "Open")
File "algotrade.py", line 11, in __init__
self.__sma = ma.SMA(feed[instrument].getDataSeries(instrument), 15)
AttributeError: 'SequenceDataSeries' object has no attribute 'getDataSeries'
I cant figure out the problem of my code and the tutorial on pyalgotrade is not helpful for me.
The problem is that you're using a regular Feed class instead of a BarFeed. Try using this: https://github.com/gbeced/pyalgotrade/blob/master/pyalgotrade/barfeed/csvfeed.py#L190
Related
I am trying to learn how to use the backtrader module on Python. I copied the code directly from the website but receiving an error message.
Here is the website: https://www.backtrader.com/docu/quickstart/quickstart/
I downloaded S&P500 stock data from Yahoo Finance and saved it into an excel file named 'SPY'. Here is the code so far:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
# Import the backtrader platform
import backtrader as bt
if __name__ == '__main__':
# Create a cerebro entity
cerebro = bt.Cerebro()
# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, 'C:\\Users\\xboss\\Desktop\\SPY.csv')
# Create a Data Feed
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
# Do not pass values before this date
fromdate=datetime.datetime(2000, 1, 1),
# Do not pass values after this date
todate=datetime.datetime(2000, 12, 31),
reverse=False)
# Add the Data Feed to Cerebro
cerebro.adddata(data)
# Set our desired cash start
cerebro.broker.setcash(100000.0)
# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything
cerebro.run()
# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
Here is the error that I am receiving:
C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\Scripts\python.exe C:/Users/xboss/PycharmProjects/BackTraderDemo/backtrader_quickstart.py
Traceback (most recent call last):
File "C:/Users/xboss/PycharmProjects/BackTraderDemo/backtrader_quickstart.py", line 39, in <module>
cerebro.run()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\cerebro.py", line 1212, in runstrategies
data.preload()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 688, in preload
while self.load():
Starting Portfolio Value: 100000.00
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 479, in load
_loadret = self._load()
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feed.py", line 710, in _load
return self._loadline(linetokens)
File "C:\Users\xboss\PycharmProjects\BackTraderDemo\venv\lib\site-packages\backtrader\feeds\yahoo.py", line 129, in _loadline
dt = date(int(dttxt[0:4]), int(dttxt[5:7]), int(dttxt[8:10]))
ValueError: invalid literal for int() with base 10: '1/29'
Process finished with exit code 1
Does anyone have any suggestions? Any help would be greatly appreciated. Thank you so much for your time!
You get the error because of using custom csv with YahooFinanceCSVData method.
You should import them using GenericCSVData method.
data = btfeed.GenericCSVData(
dataname='SPY.csv',
fromdate=datetime.datetime(2000, 1, 1),
todate=datetime.datetime(2000, 12, 31),
nullvalue=0.0,
dtformat=('%Y-%m-%d'),
datetime=0,
high=1,
low=2,
open=3,
close=4,
volume=5,
openinterest=-1
)
For more information you can see the instruction here
I am using rpy2 to run some R commands. Dont ask why. It's necessary at this moment. So here's a part of the code.
import pandas.rpy.common as com
from rpy2.robjects import r
#Load emotionsCART decision tree. Successful.
r_dataframe = com.convert_to_r_dataframe(data)
print type(r_dataframe)
(<class 'rpy2.robjects.vectors.DataFrame'>)
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
Here what I want to do is pass this r_dataframe into the calculation. I'm using the decision tree that I'd loaded earlier to predict the values. But the last line gives me an error. It says
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 245, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
Ideas why this is happening?
I think that:
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
SHould be:
r('pred = predict(emotionsCART, newdata = %s)' % (r_dataframe) )
The %(r_dataframe) was associated with the r() part, while it should be associated with the '' (string).
But it is hard to check without a reproducible example.
I trying to write a Ultimate Oscillator in python using the list function in Pyalgotrade library.
My code is below:
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 import talibext
import numpy
import talib
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed)
self.__instrument = instrument
barDs = self.getFeed().getDataSeries("002389.SZ")
self.__ultosc = indicator.ULTOSC(barDs, 36)
bar = bars[self.__instrument]
self.info("%0.2f, %0.2f" % (bar.getClose(), self.__ultosc[-1]))
# Downdload then Load the yahoo feed from the CSV file
yahoofinance.download_daily_bars('002389.SZ', 2013, '002389.csv')
feed = yahoofeed.Feed()
feed.addBarsFromCSV("002389.SZ", "002389.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "002389.SZ")
myStrategy.run()
And I got the error like this:
File "/Users/johnhenry/Desktop/untitled.py", line 23, in onBars
self.__ultosc = indicator.ULTOSC(barDs, 36)
NameError: global name 'indicator' is not defined
The function can be found at http://gbeced.github.io/pyalgotrade/docs/v0.15/html/talib.html
Ultimate Oscillator:
pyalgotrade.talibext.indicator.ULTOSC(barDs, count, timeperiod1=-2147483648, timeperiod2=-2147483648, timeperiod3=-2147483648)
You're not importing indicator, nor are you referencing it via the module it's defined in. Change this:
self.__ultosc = indicator.ULTOSC(barDs, 36)
Into:
self.__ultosc = talibext.indicator.ULTOSC(barDs, 36)
And it should be fine.
We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.
The question is based on the thread, since I observed that Storm allows me reuse my SQL-schemas.
How can you solve the following error message in Storm?
The code is based on Jason's answer and on Storm's manual.
import os, pg, sys, re, psycopg2, storm
from storm.locals import *
from storm import *
class Courses():
subject = Unicode()
database = create_database("postgres://naa:123#localhost:5432/tk")
store = Store(database)
course = Courses()
course.subject = 'abcd'
store.add(course)
It gives you
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
File "/usr/lib/python2.6/dist-packages/storm/store.py", line 245, in add
obj_info = get_obj_info(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 40, in get_obj_info
obj_info = ObjectInfo(obj)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 162, in __init__
self.cls_info = get_cls_info(type(obj))
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 51, in get_cls_info
cls.__storm_class_info__ = ClassInfo(cls)
File "/usr/lib/python2.6/dist-packages/storm/info.py", line 69, in __init__
raise ClassInfoError("%s.__storm_table__ missing" % repr(cls))
storm.exceptions.ClassInfoError: <type 'instance'>.__storm_table__ missing
This suggests to me that some module is missing. There is no module instance in Storm.
I'll leave out the connection details because I'm not terribly familiar with Postgres.
from storm.locals import *
class Courses(object):
__storm_table__ = 'courses'
pkey = Int(primary=True)
course_nro = Unicode()
course = Courses()
course.course_nro = 'abcd'
store.add(course)
store.commit()
Of course, if you want to do the constructor and initialization on one line, you can use pysistence's expandos:
from storm.locals import *
from pysistence import Expando
class Courses(Expando):
__storm_table__ = 'courses'
pkey = Int(primary=True)
course_nro = Unicode()
course = Courses(course_nro='abcd')
store.add(course)
store.commit()