Python: NSEpy Module: Not able to fetch Futures live data - python-3.x

I am using below code to pull live Nifty quote from NSEpy module but getting error.
Code:
from nsepy import get_quote
nifty = get_quote('NIFTY', series='EQ', instrument='FUTIDX', expiry='26SEP2019')
print(nifty)
Error:
nifty = get_quote('NIFTY', series='EQ', instrument='FUTIDX', expiry='26SEP2019')
File "C:\ProgramData\Anaconda3\lib\site-packages\nsepy\live.py", line 26, in get_quote
expiry_str = "%02d%s%d"%(expiry.day, months[expiry.month][0:3].upper(), expiry.year)
AttributeError: 'str' object has no attribute 'day'

I could to make this working :
#!/usr/bin/python
from nsepy import get_quote
from nsepy.derivatives import get_expiry_date
expiry = get_expiry_date(year=2019, month=9)
print(expiry)
data = get_quote('NIFTY', series='EQ', instrument='FUTIDX', expiry=expiry, option_type='CE', strike=300)
print(data)
Output:
building dictionary
2019-09-26
{'annualisedVolatility': 18.15, 'bestBuy': 10.5, 'totalSellQuantity': 263550, 'vwap': 11032.65, 'clientWisePositionLimits': 14074147, 'optionType': '-', 'highPrice': 11118.0, 'dailyVolatility': 0.95, 'bestSell': 11.31, 'marketLot': 75, 'sellQuantity5': 450, 'marketWidePositionLimits': '-', 'sellQuantity4': 150, 'sellQuantity3': 375, 'sellQuantity2': 150, 'underlying': 'NIFTY', 'sellQuantity1': 1275, 'pChange': 1.07, 'premiumTurnover': '-', 'totalBuyQuantity': 538425, 'turnoverinRsLakhs': 1219692.56, 'changeinOpenInterest': -377325, 'strikePrice': '-', 'openInterest': 16778250, 'buyPrice2': 11110.95, 'buyPrice1': 11111.0, 'openPrice': 10990.0, 'prevClose': 10996.45, 'expiryDate': '26SEP2019', 'lowPrice': 10962.15, 'buyPrice4': 11110.2, 'buyPrice3': 11110.45, 'buyPrice5': 11110.15, 'numberOfContractsTraded': 147404, 'instrumentType': 'FUTIDX', 'sellPrice1': 11113.7, 'sellPrice2': 11114.0, 'sellPrice3': 11114.5, 'sellPrice4': 11114.6, 'sellPrice5': 11114.7, 'change': 118.05, 'pchangeinOpenInterest': -2.2, 'ltp': 11.54, 'impliedVolatility': '-', 'underlyingValue': 11075.9, 'buyQuantity4': 1425, 'buyQuantity3': 75, 'buyQuantity2': 75, 'buyQuantity1': 1500, 'buyQuantity5': 150, 'settlementPrice': 11105.55, 'closePrice': 11105.55, 'lastPrice': 11114.5}
The documentation seems to be incorrect in the NSEpy library, which says expiry should be in (ddMMMyyyy) format and strike(strike_price) is a mandatory argument.
def get_quote(symbol, series='EQ', instrument=None, expiry=None, option_type=None, strike=None):
"""
1. Underlying security (stock symbol or index name)
2. instrument (FUTSTK, OPTSTK, FUTIDX, OPTIDX)
3. expiry (ddMMMyyyy)
4. type (CE/PE for options, - for futures
5. strike (strike price upto two decimal places
"""
https://nsepy.readthedocs.io/en/latest/#quick-hand-on

Expiry date is a list thats why you are getting error. use below code change.
from pprint import pprint
from datetime import date
from nsepy import get_quote
from nsepy.derivatives import get_expiry_date
expiry = date(2020,5,28)
print(expiry)
data = get_quote('BANKNIFTY', series='EQ', instrument='FUTIDX', expiry=expiry, option_type='CE', strike=300)
pprint(data)

Related

Date formatting issue in python

import time
import sys
import json as json
import spacy
from datetime import datetime
from dateutil.parser import parse
def format_source_date(date):
if date != None:
try:
try:
dt = parse(date)
date_formatted=dt.strftime('%m/%d/%Y')
print(date_formatted)
except:
print(date)
except ValueError:
print(date)
def has_seperator(text):
if ',' in text or '/' in text or '-' in text:
print(text)
return True
else:
return False
date = 'Sep 25,2017'
has_seperator(date)
format_source_date(date)
The required answer is 09/25/2017. Instead taking current year 2021 . Is there any solution to solve this issue
Seems your date string is not a valid format,
See the following
>>> parse('Sep 25,2017')
datetime.datetime(2021, 9, 25, 0, 0)
>>> parse('Sep 25 2017')
datetime.datetime(2017, 9, 25, 0, 0)
so already have a has_seperator function, use it remove the character or use a supported format

Advanced string formatting using conversion operators

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))

backtrader printing data feed vaues does not print hours and minues and defaults to

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,
)

Conditional statement between today date and minus 3 months in Python

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)
...

Python: How to set ticker in krakenex for fetching historical OHLC-data?

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}))

Resources