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
Related
I am running the following script:
# STEP 1: import packages, declare tindexes
import pandas as pd
import yfinance as yf
import datetime as dt
bnpl_tindex = ["APT.AX","Z1P.AX","LFS.AX","SZL.AX","HUM.AX","SPT.AX","OPY.AX","IOU.AX","LBY.AX","DOU.AX"]
target_dates = pd.date_range(start=dt.date.today() - dt.timedelta(days=365), end=dt.date.today(), freq="M").strftime('%Y-%m-%d')
target_dates = target_dates.append(pd.Index([dt.date.today().strftime('%Y-%m-%d')]))
target_dates.sort_values()
#STEP 2: source functions
from collect_index_data import collect_index_data
#DELETE LATER... TESTING!
collect_index_data(bnpl_tindex, target_dates)
#
collect_index_data is as follows:
def collect_index_data(ticker_list,date_list):
if (bool(ticker_list) and all(isinstance(elem, str) for elem in ticker_list) )==False:
sys.exit('Input should be a list or a single string.')
else:
print("Components of Index: ")
#initialise dictionary
d = {}
#loop through ticker list
for x in ticker_list:
d["DF.{0}".format(x)] = yf.Ticker(x)
#testing
print(x)
#testing
print(d)
and I get the following error message
Components of Index:
Traceback (most recent call last):
File "C:\Users\thoma\Desktop\Files\Programming\Python\run_tindex_data.py", line 27, in <module>
collect_index_data(bnpl_tindex, target_dates)
File "C:\Users\thoma\Desktop\Files\Programming\Python\collect_index_data.py", line 12, in collect_index_data
d["DF.{0}".format(x)] = yf.Ticker("MSFT")
NameError: name 'yf' is not defined
My question is why is yfinance package not being recognised in my function?
I could import it inside the function, but I plan to run the function multiple times in a script - so this would be computationally wasteful.
thanks!
I am trying to batch run workspaces from a standalone python script and it fails. I am particularly wondering if I am passing the parameters correctly. I was using an exception catch with a message but it actually provided less information:
'code' Traceback (most recent call last):
File "C:\Users\YouDoWellItDoesGood\Downloads \SixtyFourTest.py", line 89, in <module>
wrkRunner.runWithParameters(qcWorkspace,parameters)
FMEException: FMEException: 1: Failure running workspace 'C:\Users\YouDoWellItDoesGood\Downloads\Anadarko_QC_Tool.fmwt' 'code'
The code:
# Note:
# The path to fmeobjects must by in your python
# path so you may need something like this:
import sys
sys.path.append(r"C:\Program Files\FME\fmeobjects\python27")
import fmeobjects
import fnmatch
import xlrd
import arcpy
import datetime
import os
##dictionary to hold the day of week value generated by the statusRunDateNum
##variable. the first
##number in the dictionary entery is the day of the week as a number. The other
##two numbers are the column numbers where we will find our project status values
datColumnDict={1:[2,3],2:[5,6],3:[8,9],4:[11,12],5:[14,15]}
qcWorkspace=r"C:\Users\YouDoWellItDoesGood\Downloads\Anadarko_QC_Tool.fmwt"
#will return a number depending what day it is.
statusRunDateNum=datetime.datetime.today().isoweekday()
# location of the status report/ will be turned into a variable.
PSL=r"C:\Users\YouDoWellItDoesGood\Downloads\Project%20Status%20Worksheet%203_20%20to%203_24.xlsx"
pjStatus=xlrd.open_workbook(PSL)
pjSheet=pjStatus.sheet_by_index(0)
pjList=[]
for row_index in range(1,pjSheet.nrows):
statusColumn=str(pjSheet.cell(row_index,datColumnDict[statusRunDateNum][1]))
statusColumnNoColon=statusColumn.split(":")[1]
projColumn=str(pjSheet.cell(row_index,datColumnDict[statusRunDateNum][0]))
projColumnNoDec=projColumn.split(".")[0]
projColumnNoColon=projColumnNoDec.split(":")[1]
if "QC" in str(statusColumn):
pjList.append(projColumnNoColon)
print statusColumnNoColon
print pjList
pjDir=r"F:\Projects\ANADARKO-DELAWARE BASIN"
pjDirList=os.listdir(pjDir)
wrkspc=[]
for x in range(len(pjList)):
#create string from TGS proj number
match=str(pjList[x])+"*"
#declare feature list
for f in pjDirList:
if fnmatch.fnmatch(f,match):
## print match[:-1]
gisPath=os.path.join(pjDir,f,"GIS")
for gf in os.listdir(gisPath):
if gf.startswith("DB_") or gf.startswith("ID") and gf.endswith(".gdb"):
wrkspc.append(os.path.join(gisPath,gf))
print wrkspc
for w in wrkspc:
parameters={}
parameters['_gdbpath']=w
parameters['_user']="test"
parameters['_with_corrections']='False'
#parameters['FEATURE_TYPES']="WE_PT WE_PATH_LN WE_PAD_POLY WD_PT WD_POLY WD_LN VG_PT VG_POLY VG_LN VG_BUFFER_POLY TR_TRANS_OTHER_PT TR_TRANS_OTHER_POLY TR_TRANS_OTHER_LN TR_RUNWAY_POLY TR_ROAD_LOW_WATER_PT TR_ROAD_CENTER_LN TR_RAILROAD_PT TR_RAILROAD_POLY TR_RAILROAD_LN TR_LANDING_ZONE_PT TR_LANDING_ZONE_POLY TR_EDGE_OF_PAVEMENT_LN ST_OTHER_PT ST_OTHER_POLY ST_OTHER_LN SI_FACILITY_PERIMETER_POLY SI_FACILITY_OTHER_POLY RC_WETLANDS_POLY RC_SOILBED_PREPARATION_POLY RC_SOIL_SAMPLE_PT RC_SOIL_AMENDMENT_POLY RC_SEEDBED_PREPARATION_POLY RC_RECLAMATION_OTHER_PT RC_RECLAMATION_OTHER_POLY RC_RECLAMATION_OTHER_LN RC_MULCH_POLY RC_HYDROMULCH_POLY RC_BORROW_PIT_POLY PL_VENT_PIPE_PT PL_TRENCH_BREAKER_LN PL_TEST_LEAD_PT PL_TEE_PT PL_TAP_PT PL_SLEEVE_LN PL_ROUTING_NOTE_PT PL_ROCK_SHIELD_LN PL_REDUCER_PT PL_PUMP_STATION_PT PL_PIPELINE_LN PL_PIPE_BEND_LN PL_PIG_SIGNAL_PT PL_PI_EXCAVATION_PT PL_NAT_GROUND_PT PL_METER_STATION_PT PL_JOIN_PT PL_INJECTOR_PT PL_GIRTH_WELD_PT PL_FLANGE_PT PL_ELBOW_PT PL_DRIP_PT PL_DEPTH_OF_COVER_PT PL_COMPRESSOR_STATION_PT"
wrkRunner=fmeobjects.FMEWorkspaceRunner()
wrkRunner.runWithParameters(qcWorkspace,parameters)
print w
print parameters
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
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 have been trying to add different images to nodes in a phylogenetic tree using the ete2 software in Python, but have no success.
from ete2 import Tree, TreeStyle, NodeStyle, TextFace, faces, add_face_to_node, AttrFace
ts.show_leaf_name = True
ts.show_branch_support = True
nw = """
(((Dre:0.008339,Dme:0.300613)1.000000:0.596401,
(Cfa:0.640858,Hsa:0.753230)1.000000:0.182035)1.000000:0.106234,
((Dre:0.271621,Cfa:0.046042)1.000000:0.953250,
(Hsa:0.061813,Mms:0.110769)1.000000:0.204419)1.000000:0.973467);
"""
t = Tree(nw)
img_path = "/home/leonard/Desktop/img_faces/"
humanFace = faces.ImgFace(img_path+"human.png")
mouseFace = faces.ImgFace(img_path+"mouse.png")
def my_layout(node):
if name.startswith("Dre"):
faces.add_face_to_node(humanface, node, column=1)
t.show(my_layout)
ts = TreeStyle()
t.render("img_faces.png", w=600, tree_style = ts)
These are error messages that I have been getting:
File "abc1.py", line 34, in <module>
t.show(my_layout)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/coretype/tree.py", line 1283, in show
drawer.show_tree(self, layout=layout, tree_style=tree_style)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/drawer.py", line 84, in show_tree
tree_item, n2i, n2f = render(t, img)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/qt4_render.py", line 258, in render
set_style(n, layout_fn)
File "/usr/local/lib/python2.7/dist-packages/ete2-2.1rev544-py2.7.egg/ete2/treeview/qt4_render.py", line 746, in set_style
layout_func(n)
File "abc1.py", line 29, in my_layout
if name.startswith("Dre"):
NameError: global name 'name' is not defined
Any help is much appreciated!
This is the solution from Jaime Huerta Cepas in google group, and I quote:
"There is a general Python programming error in your script ("name" variable does not exist). I guess that what you meant is "node.name.startswith()" instead of "name.startswith()""
It worked.
According to the documentation (ete2) you need to create a faces ready to read the name attribute of nodes.
Try to add the following to your code:
#nameFace = faces.TextFace(open("text").readline().strip(), fsize=20, fgcolor="#009000")
nameFace = faces.AttrFace("name", fsize=20, fgcolor="#009000")