I am working with the minimum field width of conversion specifiers for a class, I have tried deleting and rewriting my last section in this the 'TD' and 'INT' but I keep getting an error on line td = float(quaterback_stats[qb]['TD']) the error message reads:
Traceback (most recent call last): File "main.py", line 24, in
td = float(quaterback_stats[qb]['TD']) NameError: name 'quaterback_stats' is not defined
I am struggling to understand how this is wrongly written to produce my outcome, when I have been using quaterback_stats as my defining variable for the rest of the code. The outcome of this code is supposed to create list attaching the quarterback to their stats. Any assistance on clarification would be appreciated, hope I posted this in the proper format:
quarterback_stats = {
'Aaron Rodgers': {'COMP': 371, 'YDS': 4925, 'TD': 39, 'INT': 8},
'Peyton Manning': {'COMP': 400, 'YDS': 4659, 'TD': 37, 'INT': 11},
'Greg McElroy': {'COMP': 19, 'YDS': 214, 'TD': 1, 'INT': 1},
'Matt Leinart': {'COMP': 16, 'YDS': 115, 'TD': 0, 'INT': 1}
}
print('2012 quarterback statistics:')
print(' Passes completed:')
for qb in quarterback_stats:
comp = quarterback_stats[qb]['COMP']
print(' %s : %d' % (qb, comp))
#print(' %?: %?' % (qb, comp)) # Replace conversion specifiers
# Hint: Use the conversion flag '-' to left-justify names
print(' Passing yards:')
for qb in quarterback_stats:
yds = quarterback_stats[qb]['YDS']
print(' %s : %d' % (qb,yds))
print(' Touchdown / interception ratio:')
for qb in quarterback_stats:
td = float(quaterback_stats[qb]['TD'])
int = float(quaterback_stats[qb]['INT'])
print(' %s : %.2f ' % (qb,td/int))
I'm learning to use backtrader and I've come across a problem when trying to print out the datafeed. It correctly prints the day, open, high, low, close and volume but the hour and minutes data seems to default to 23:59:59.999989 on every line.
Here is a sample of the data source:
datetime,open,high,low,close,volume,,
11/2/2020 9:30,330.187,330.188,329.947,330.038,4.79,,
11/2/2020 9:31,330.038,330.438,329.538,329.677,5.49,,
11/2/2020 9:32,329.667,330.248,329.577,330.117,5.8,,
11/2/2020 9:33,330.128,330.328,329.847,329.948,5.59,,
11/2/2020 9:34,329.967,330.308,329.647,329.698,6.24,,
and the code I use to add the data to backtrader is:
data = bt.feeds.GenericCSVData(
dataname = 'SPY_11_2020_1M.txt',
name= 'SPY',
datetime = 0,
dtformat = ('%m/%d/%Y %H:%M'),
period = bt.TimeFrame.Ticks,
compression = 1,
fromdate = params['fromdate'],
todate = params['todate'],
open = 1,
high = 2,
low = 3,
close = 4,
volume = 5,
openinterest = -1,
)
cerebro.adddata(data)
my code for the trategy, which is a simple buy and hold strategy, is:
import backtrader as bt
from datetime import datetime as dt
class BuyHold(bt.Strategy):
def __init__(self):
# self.time = self.datas[0].datetime.datetime(0),
self.open = self.datas[0].open
self.high = self.datas[0].high
self.low = self.datas[0].low
self.close = self.datas[0].close
self.volume = self.datas[0].volume
def next(self):
print('{0} {1}\t{2}\t{3}\t{4}\t{5}\t{6}'.format(
self.datas[0].datetime.date(0),
self.datas[0].datetime.time(0),
self.open[0],
self.high[0],
self.low[0],
self.close[0],
self.volume[0]
))
# print('{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(
# self.time,
# self.open[0],
# self.high[0],
# self.low[0],
# self.close[0],
# self.volume[0]
# ))
if self.position.size == 0:
size = int(self.broker.getcash() / self.data)
self.buy(size = size)
The printout I get is as:
2020-11-02 23:59:59.999989 330.187 330.188 329.947 330.038 4.79
2020-11-02 23:59:59.999989 330.038 330.438 329.538 329.677 5.49
2020-11-02 23:59:59.999989 329.667 330.248 329.577 330.117 5.8
2020-11-02 23:59:59.999989 330.128 330.328 329.847 329.948 5.59
2020-11-02 23:59:59.999989 329.967 330.308 329.647 329.698 6.24
I also tried it with the commented out self.time with the commented out print line which provides similar result in a slightly different format as:
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 330.187 330.188 329.947 330.038 4.79
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 330.038 330.438 329.538 329.677 5.49
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 329.667 330.248 329.577 330.117 5.8
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 330.128 330.328 329.847 329.948 5.59
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 329.967 330.308 329.647 329.698 6.24
(datetime.datetime(2020, 11, 2, 23, 59, 59, 999989),) 329.698 330.198 329.568 329.948 6.51
I don't know what I'm missing here.
struggle with the problem some days,i use isoformat to read the time and date
strategy
class my_strategy1(bt.Strategy):
def log(self, txt, dt=None):
''' Logging function for this strategy'''
# dt = dt or self.datas[0].datetime.date(0)
#the fellowing will print date ,that is,2021-08-06
print(self.datas[0].datetime.date(0).isoformat())
#the fellowing will print time,that is,08:09:01
print(self.datas[0].datetime.time(0).isoformat())
print(txt)
def __int__(self):
pass
def next(self):
self.log('Close, %.2f' % self.dataclose[0])
print("trend is", self.datas[0].lines.trend[0])
pass
data class
class My_CSVData(bt.feeds.GenericCSVData):
"""
如何添加格外的数据列在excel中进行处理
how to append the other data to csv
"""
lines = ('trend',)
params = (
('trend', -1),
)
def get_data_via_excel(path):
datatest=My_CSVData(
dataname=path,
timeframe=bt.TimeFrame.Minutes,
compression=60,
dtformat='%Y-%m-%d %H:%M:%S',
tmformat = '%H:%M:%S',
fromdate = datetime(2021,4,16),
todate = datetime(2021,7,30),
datetime = 0,
high=2,
open =1,
close=4,
low =3,
volume=5,
openinterest =6,
trend = 7 ,#not use -1
)
return datatest
data source
datetime,open,high,low,close,volume,openinterest,trend
2021-04-16 09:59:00,5138,5144,5109,5117,200,0,-2
2021-04-16 11:00:00,5117,5122,5089,5102,200,0,-2
2021-04-16 11:29:00,5103,5118,5096,5105,200,0,-1
2021-04-16 14:00:00,5105,5152,5105,5142,200,0,0
2021-04-16 15:00:00,5141,5142,5111,5116,200,0,1
2021-04-16 21:59:00,5122,5141,5116,5129,200,0,0
2021-04-16 23:00:00,5128,5136,5108,5120,200,0,0
This problem also took me few hours. And I find the solution from another web.
Here.
For minute data tell cerebro that you are using minute data (timeframe) and how many minutes per bar (compression).
data = bt.feeds.GenericCSVData(
dataname = 'SPY_11_2020_1M.txt',
name= 'SPY',
datetime = 0,
dtformat = ('%m/%d/%Y %H:%M'),
**timeframe=bt.TimeFrame.Minutes,**
period = bt.TimeFrame.Ticks,
compression = 1,
fromdate = params['fromdate'],
todate = params['todate'],
open = 1,
high = 2,
low = 3,
close = 4,
volume = 5,
openinterest = -1,
)
I am trying to insert 'NULL' values in a table depending on the date.
If the date is between todays date and 3 months backward (which will be february).
Then I want to update the 'NULL' values into each selected columns.
The Traceback is as following:
Traceback (most recent call last):
File "C:\projects\docs\script.py", line 41, in <module>
if dt < date_sql < dr3:
TypeError: '<' not supported between instances of 'datetime.datetime' and 'pyodbc.Row'
Been strugling for a long time, so really appreciate your guidance as I have tried to find a solution.
Python code is:
import pyodbc
from datetime import date, datetime
import dateutil.relativedelta
conn = pyodbc.connect(
r'DRIVER={SQL Server};'
r'SERVER=server;'
r'DATABASE=db;'
)
dt = datetime.today()
dr3 = dt - dateutil.relativedelta.relativedelta(months=3)
print(dr3)
cursor = conn.cursor()
sent_date = cursor.execute("""SELECT TOP 30 sent_date, id
FROM Department.Customer""")
def fetch_date():
for row in sent_date:
r = row
print(r)
return r
date_sql = fetch_date()
if dt < date_sql < dr3:
try:
value = None
cursor.execute("""UPDATE Department.Customer SET name=?, address=?, email=?,
phone=?""", (value, value, value, value))
cursor.commit()
except pyodbc.Error as ex:
print(str(ex))
cursor.rollback()
cursor.close()
Output from print(dr3) is:
2018-02-28 17:19:50.452290
Output from print(r) in fetch_date() function is:
(datetime.datetime(2018, 5, 22, 10, 21, 36), 1)
(datetime.datetime(2018, 5, 22, 10, 21, 36), 2)
(datetime.datetime(2018, 5, 22, 10, 21, 36), 3)
...
I am trying to load OHLC-data form Kraken with the API krakenex for my research project. But I can't figure out my mistake.
I am using a modified version of https://github.com/veox/python3-krakenex/blob/master/examples/trades-history.py in python for fetching the historical OHLC-Data:
import krakenex
import datetime
import calendar
import pandas as pd
import time
# takes date and returns nix time
def date_nix(str_date):
return calendar.timegm(str_date.timetuple())
# takes nix time and returns date
def date_str(nix_time):
return datetime.datetime.fromtimestamp(nix_time).strftime('%m, %d, %Y')
#return formated request data
def req(start, end, ofs):
req_data = {'type': 'all',
'trades': 'true',
'start': str(date_nix(start)),
'end': str(date_nix(end)),
'ofs': str(ofs)
}
return req_data
k = krakenex.API()
k.load_key('kraken.key.txt')
#k.set_connection({'pair':'GNOETH'})
#headers={"headers":'XXBTZUSD'}
#pairs = ['XETHZEUR','XXBTZEUR', 'XZECZEUR', 'XXRPZEUR']
datum_ende=[[31,28,31,30,31,30,31,31,30,31,30,31],[31,29,31,30,31,30,31,31,30,31,30,31]]
data = []
count = 0
jahre =[2015,2016,2017]
for j in jahre:
for i in range(0,11):
start_date = datetime.datetime(j, i+1, 1)
if j==2016:
end_date = datetime.datetime(2016, i+1, datum_ende[1][i])
else:
end_date = datetime.datetime(j, (i+1),datum_ende[0][i])
th = k.query_private('TradesHistory', req(start_date,end_date,1))
time.sleep(.25)
print(th)
th_error = th['error']
if int(th['result']['count'])>0:
count += th['result']['count']
data.append(pd.DataFrame.from_dict(th['result']
So my problem is now that I receive the lines:
{'error': [], 'result': {'trades': {}, 'count': 0}}
I guess the problem is that I haven't defined a ticker pair. But I can't figure out how I am supposed to do this.
Can you help me out?
Why don't you try dedicated OHCL method?
Here is a simple usage example:
import krakenex
from pprint import pprint
k = krakenex.API()
pprint(k.query_public('OHLC', {'pair':'XXBTZUSD', 'interval':1440, 'since':1214011560}))