IBpy - getting my market position - python-3.5

Lets assume i have only one position in my IB account.
To retrieve it, I run the below:
from time import sleep
from ib.opt import Connection, message, ibConnection
from ib.ext.Contract import Contract
def acc_update(msg):
global acc, expiry, exch, pExch, secType, symbol
acc = msg.account
exch = msg.contract.m_exchange
pExch = msg.contract.m_primaryExch
secType = msg.contract.m_secType
expiry = msg.contract.m_expiry
symbol = msg.contract.m_symbol
return acc, expiry, exch, pExch, secType, symbol
tws = ibConnection(port= 7497)
tws.register(acc_update, message.position)
tws.connect()
tws.reqPositions()
sleep(0.5)
tws.disconnect()
print( [symbol, acc, expiry, exch, pExch, secType])
this gives me:
['BAC', 'DUC00074', '20170519', None, '', 'OPT']
Why aren't the exchange and the primary_exchange data showing ?

Related

loop efficiency and performance impact calling api in python

Team:
My concern is on redundancy, efficient use of loops and best approach to get the desired result.
Usecase: get on call user name and create jira ticket with it.
below is my entire code and it runs fine for me. This is my very first OOP project.
Flow: I am calling two APIS (jira and pager api).
First calling pager api and getting who is oncall currently. Here am getting a list of nested dicts as response that am looping on.
Then calling jira api to create ticket with that above oncall user.
i want to learn to calculate Big0 and improve.
since this is my very first time can I get to see if there any problems or inefficiency or divergence from standard practices?
import requests
import json
import os
from jira import JIRA
from pdpyras import APISession
from collections import OrderedDict
JIRA_DICT_KEY = "JIRA"
JIRA_CONFIG = {'server': "https://jirasw.tom.com"}
JIRA_USER = os.environ['JIRA_USER']
JIRA_PW = os.environ['JIRA_PW']
PD_API_KEY = os.environ['PD_API_KEY']
USER_EMAIL = os.environ['USER_EMAIL']
class ZidFinder(object):
def __init__(self):
self.active_zid_errors = dict()
self.team_oncall_dict = dict()
self.onCall = self.duty_oncall()
self.jira = self.init_jira()
def init_jira(self):
jira = JIRA(options=JIRA_CONFIG, auth=(JIRA_USER, JIRA_PW))
return jira
def duty_oncall(self, *args):
session = APISession(PD_API_KEY, default_from=USER_EMAIL)
total = 1 #true or false
limit = 100 # this var is to pull limit records at a time.
teamnm = "Product SRE Team"
team_esp_name = "Product SRE Escalation Policy"
teamid = ""
teamesplcyid = ""
if args:
offset = args[0]
total_teams = args[1]
if offset <= total_teams:
print("\nfunc with args with new offset {} called\n".format(offset))
teams = session.get('/teams?limit={0}&total={1}&offset={2}'.format(limit,total,offset))
else:
print("Reached max teams, no more team records to pull")
return
else:
print("\nPull first set of {} teams as defined by limit var and loop more if team not found..\n".format(limit))
teams = session.get('/teams?limit={0}&total={1}'.format(limit,total))
if not teams.ok:
return
else:
tj = teams.json()
tjd = tj['teams']
print("\n")
for adict in tjd:
if not adict['name'] == teamnm:
continue
elif adict['name'] == teamnm:
teamid = adict['id']
print("Found team..\n",adict['name'], "id: {0}".format(teamid))
esclp = session.get('/escalation_policies?total={0}&team_ids%5B%5D={1}'.format(total,teamid))
if not esclp.ok:
print("Failed pulling Escalation polices for team '{}'".format(teamnm))
return
else:
ep = esclp.json()
epj = esclp.json()['escalation_policies']
if not epj:
print("Escalation polices for team '{}' not defined".format(teamnm))
return
else:
for adict in epj:
if not adict['summary'] == team_esp_name:
continue
else:
teamesplcyid = adict['id']
print("{} id: {}\n".format(team_esp_name, teamesplcyid))
oncalls = session.get('/oncalls?total={0}&escalation_policy_ids%5B%5D={1}'.format(total,teamesplcyid))
if not oncalls.ok:
print("Issue in getting oncalls")
return
else:
ocj = oncalls.json()['oncalls']
for adict in ocj:
if adict['escalation_level'] == 1 or adict['escalation_level'] == 2:
self.team_oncall_dict[adict['schedule']['summary']] = adict['user']['summary']
continue
if self.team_oncall_dict:
if len(self.team_oncall_dict) == 1:
print("\nOnly Primary onCall is defined")
print("\n",self.team_oncall_dict)
else:
print(" Primary and other calls defined")
print("\n",OrderedDict(self.team_oncall_dict),"\n")
return
else:
print("Calling with next offset as team was not found in the records pulled under limit..")
if tj['offset'] <= tj['total'] or tj['more'] == True:
setoffset = limit + tj['offset']
self.onCall(setoffset, tj['total'])
def create_jiras(self):
node = ["node1", "node2"]
zid_label = ["id90"]
labels = [node, zid_label]
print("Creating a ticket for node {} with description: {}".format(node, str(self.active_zid_errors[node])))
if self.msre_oncall_dict:
print("Current onCalls pulled from Duty, use them as assignee in creating jira tickets..")
new_issue = self.jira.create_issue(project='TEST', summary='ZID error on node {}'.format(node),
description=str(self.active_zid_errors[node]), issuetype={'name': 'Bug'}, assignee={'name': self.msre_oncall_dict['Product SRE Primary']},labels=labels)
print("Created a new ticket: ", new_issue.key, new_issue.fields.summary)
self.active_zid_errors[node][JIRA_DICT_KEY] = new_issue.key
else:
print("Current onCalls were not pulled from Duty, create jira with defautl assignee..")
new_issue = self.jira.create_issue(project='TEST', summary='ZID error on node {}'.format(node),
description=str(self.active_zid_errors[node]), issuetype={'name': 'Bug'},labels=labels)
print("Created a new ticket: ", new_issue.key, new_issue.fields.summary)
self.active_zid_errors[node][JIRA_DICT_KEY] = new_issue.key
if __name__== "__main__":
o = ZidFinder()

Why error: "must be real number, not RestMode"? How can fix it?

I'm using ROS, and writing some codes to do some tasks, and now I'm facing an error: TypeError: must be real number, not RestMode, for more details, I have code here:
#!/usr/bin/env python
#encoding: utf-8
import rospy
from geometry_msgs.msg import Vector3
from sensor_msgs.msg import Imu
from std_msgs.msg import Float64
import numpy as np
import geometry as geo
import transformation as tf
from IK_solver import IK
class RestMode:
def __init__(self, bodyDimensions, legDimensions):
# rospy.Subscriber('spot_keyboard/body_pose',Vector3,self.callback)
self.bodyLength = bodyDimensions[0]
self.bodyWidth = bodyDimensions[1]
self.bodyHeight = bodyDimensions[2]
self.l1 = legDimensions[0]
self.l2 = legDimensions[1]
self.l3 = legDimensions[2]
# rospy.Subscriber('spot_imu/base_link_orientation',Imu, self.get_body_pose)
self.rate = rospy.Rate(10.0) #10Hz
self.rb = IK(bodyDimensions, legDimensions)
angles_cmd = [ 'spot_controller/FL1_joint/command',
'spot_controller/FL2_joint/command',
'spot_controller/FL3_joint/command',
'spot_controller/RL1_joint/command',
'spot_controller/RL2_joint/command',
'spot_controller/RL3_joint/command',
'spot_controller/RR1_joint/command',
'spot_controller/RR2_joint/command',
'spot_controller/RR3_joint/command',
'spot_controller/FL1_joint/command',
'spot_controller/FL2_joint/command',
'spot_controller/FL3_joint/command' ]
self.joint = []
for i in range(12):
self.joint.append(rospy.Publisher(angles_cmd[i], Float64, queue_size=10))
# self.initial_pose()
def initial_pose(self,roll=0,pitch=0,yaw=0,dx=0,dy=0,dz=None):
if dz == None:
dz = self.bodyHeight
order = ['FL','RL','RR','FR']
angles = []
rospy.loginfo("Start Calculate Angles!")
for leg in order:
(q1,q2,q3,ht) = self.rb.calculateAngles(self,roll,pitch,yaw,dx,dy,dz,leg)
angles.append(q1)
angles.append(q2)
angles.append(q3)
rospy.loginfo("Done! Start publish!")
for i in range(12):
self.joint[i].publish(angles[i])
self.rate.sleep()
if __name__ == '__main__':
rospy.init_node('rest_mode', anonymous=True)
body = [0.1908, 0.080, 0.15]
legs = [0.04, 0.1, 0.094333]
rest = RestMode(body, legs)
try:
while not rospy.is_shutdown():
rest.initial_pose()
except rospy.ROSInterruptException:
pass
When method calculateAngles(self,roll,pitch,yaw,dx,dy,dz,leg) with argument leg in last, it throws: TypeError: must be real number, not RestMode.
But when I change it to first like: calculateAngles(self,leg,roll,pitch,yaw,dx,dy,dz), then error says: TypeError: must be real number, not str with input in another module, but I tested all of the others related module, and they are fine, so I think that must be an issue in codes above!
That error is so strange:
I don't push any str as input
When changing the position of argument leg, it throws a different error.
When calling instance methods, self is an implied parameter, and should never be explicitly passed. When you are using self.rb.calculateAngles(self, ..., that second self is an instance of a RestMode class, which your IK class does not accept...
Therefore, you want
(q1,q2,q3,ht) = self.rb.calculateAngles(roll,pitch,yaw,dx,dy,dz,leg)
And change other usages within the IK class as well

AttributeError: 'datetime.datetime' object has no attribute 'striftime'

I am currently writing a machine learning program for school to predict the weather. I have been using this article https://stackabuse.com/using-machine-learning-to-predict-the-weather-part-1/ as my main resource (I have had to adjust as wunderground is no longer free so I have instead been using openweathermap). I was writing the data collection and organization part of my code I received the following error 'AttributeError: 'datetime.datetime' object has no attribute 'striftime'. Sorry in advance for the massive block of code, I figured it would be the best way to troubleshoot the problem. Thank you for any the help. The parts with '** code **' are what I am struggling with
from datetime import datetime
from datetime import timedelta
import time
from collections import namedtuple
import pandas as pd
import requests
import matplotlib.pyplot as plt
#Data collection and Organization
url = 'http://history.openweathermap.org//storage/d12a3df743e650ba4035d2c6d42fb68f.json'
#res = requests.get(url)
#data = res.json()
target_date = datetime(2018, 4, 22)
features = ["date", "temperature", "pressure", "humidity", "maxtemperature", "mintemperature"]
DailySummary = namedtuple("DailySummary", features)
def extra_weather_data(url, target_date, days):
for _ in range(days):
**request = url.format(target_date.striftime('%Y%m%d'))**
respone = requests.get(request)
if response.status_code == 200:
data = response.json()
records.append(DailySummary(
date = target_date,
temperature = data['main']['temp'],
pressure = data['main']['pressure'],
humidity = data['main']['humidity'],
maxtemperature = data['main']['temp_max'],
mintemperature = data['main']['temp_min']))
time.sleep(6)
target_date += timedelta(days=1)
**records = extra_weather_data(url, target_date, 365)**
#Finished data collection now begin to clean and process data using Pandas
df = pd.DataFrame(records, columns=features).set_index('date')
tmp = df[['temperature','pressure','humidty', 'maxtemperature', 'mintemperature']].head(10)
def derive_nth_day_feature(df, feature, N):
rows =df.shape[0]
nth_prior_measurements = [None]*N + [df[feature][i-N] for i in range(N,rows)]
col_name = "{}_{}".format(feature, N)
df[col_name] = nth_prior_measurements
for feature in features:
if feature != 'date':
for N in range(1, 4):
derive_nth_day_feature(df, feature, N)
df.columns

Using python for getting data out from a tektronix oscilliscope

import visa
import numpy as np
from struct import unpack
import pylab
rm = visa.ResourceManager()
rm.list_resources()
inst = rm.open_resource('GPIB0::1::INSTR',write_termination= '\n')
print(inst.query("*IDN?"))
print(rm)
print(inst)
values = np.array(inst.query_ascii_values('CURV?', converter='s'))
#values1=inst.write_ascii_values('WLISt:WAVeform:DATA somename,', values, converter='s')
len(values)
print(values)
Hi all,
I am really new with Python and programming. I am trying to get a waveform from a Tektronix oscilloscope (TDS 460 A). I am using a GPIB (GPIB USB-HS) to transfer data. With the code written above, I am able to connect with the oscilloscope. I have some very basic questions. When I print(values), it is giving me a string. I was wondering what is that string? Is it the same as the address of the instrument? Now as I am connected with the instrument, how can I proceed further? My ultimate aim is to get the trace from multiple channels of the scope.
You could use:
from struct import unpack
import pyvisa as visa
rm = visa.ResourceManager()
print(rm)
def acquire(channel, port):
try:
scope = rm.open_resource(port)
scope.write("DATA:SOURCE " + channel)
scope.write('DATA:WIDTH 1')
scope.write('DATA:ENC RPB')
ymult = float(scope.ask('WFMPRE:YMULT?'))
yzero = float(scope.ask('WFMPRE:YZERO?'))
yoff = float(scope.ask('WFMPRE:YOFF?'))
xincr = float(scope.ask('WFMPRE:XINCR?'))
xdelay = float(scope.query('HORizontal:POSition?'))
scope.write('CURVE?')
data = scope.read_raw()
headerlen = 2 + int(data[1])
header = data[:headerlen]
ADC_wave = data[headerlen:-1]
ADC_wave = np.array(unpack('%sB' % len(ADC_wave),ADC_wave))
Volts = (ADC_wave - yoff) * ymult + yzero
Time = np.arange(0, (xincr * len(Volts)), xincr)-((xincr * len(Volts))/2-xdelay)
return Time,Volts
except IndexError:
return 0,0

Getting error "pywintypes.error: (5, 'OpenClipboard', 'Access is denied.')"

I am trying to use selenium with python to get latitude and longitude from this site. I am also using win32lipboard. But whenever I run my code, randomly it throws me this error pywintypes.error: (5, 'OpenClipboard', 'Access is denied.').
This is my code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import csv
import win32clipboard
csvreader = csv.reader(open("master_data.csv", 'r'))
csvwriter = csv.writer(open('final_master_data.csv', 'w', newline=''))
headers = next(csvreader)
headers.append("latitude")
headers.append("longitude")
csvwriter.writerow(headers)
locations = list(csvreader)
chromedriver = 'C:\\Users\\UserName\\Downloads\\chromedriver.exe'
driver = webdriver.Chrome(chromedriver)
driver.get('http://www.whatsmygps.com')
for places in locations:
place = places[6] + ", " + places[4] + ", " + places[2]
location = driver.find_element_by_id("address")
location.send_keys(Keys.CONTROL, 'a')
location.send_keys(place)
location.submit()
time.sleep(3)
lat_input = driver.find_element_by_id("latitude")
lat_input.send_keys(Keys.CONTROL, 'a')
lat_input.send_keys(Keys.CONTROL, 'c')
win32clipboard.OpenClipboard()
lat = win32clipboard.GetClipboardData()
places.append(lat)
win32clipboard.CloseClipboard()
lon_input = driver.find_element_by_id("longitude")
lon_input.send_keys(Keys.CONTROL, 'a')
lon_input.send_keys(Keys.CONTROL, 'c')
win32clipboard.OpenClipboard()
lon = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
places.append(lon)
print(places)
csvwriter.writerow(places)
driver.close()
so, whenever I run this code, it starts with no issues, it reads csv file and enter location names into this sites and starts to copy latitude and longitude from the site and insert those into another csv file. But after some time, randomly, it throws error pywintypes.error: (5, 'OpenClipboard', 'Access is denied.'). I am unable to find the solution about this since yesterday.
UPDATE: I am using Anaconda and I am running anaconda shell as an administrator, so there is no issue with the access permission.
Access denied error may occur if clipboard is locked by another process. To avoid python messages, you can use WinAPI version of clipboard as described in this SO link: https://stackoverflow.com/a/23285159/4603670
As an alternative, use BingMap which requires API key. As of this writing, you can register a developer account at https://www.bingmapsportal.com for the free API key (I am not sure about the quota).
import pythoncom
import win32com.client
import json
pythoncom.CoInitialize()
winhttp = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
def bing_find_gps(addressLine, postalCode, country):
q = 'http://dev.virtualearth.net/REST/v1/Locations?key='
q = q + 'my_api_key'
if country: q = q + '&countryRegion=' + country
if postalCode: q = q + '&postalCode=' + postalCode
if addressLine: q = q + '&addressLine=' + addressLine
try:
winhttp.Open('GET', q, False)
winhttp.Send()
if not winhttp.responseText:
return 0
list = json.loads(winhttp.responseText)
if list['statusCode'] != 200:
return 0
gps = list['resourceSets'][0]['resources'][0]['point']['coordinates']
if gps:
return (1, gps[0], gps[1])
except:
return 0
res = bing_find_gps('One Microsoft Way, Redmond, WA, 98052-6399', '0', 'United States')
if res:
print("lat/long %s, %s" % (res[1], res[2]))
res = bing_find_gps(0, '98052-6399', 'United States')
if res:
print("lat/long %s, %s" % (res[1], res[2]))
Or use openstreetmap.org:
address = "98052-6399" #Testing with Microsoft zip code
url = "https://nominatim.openstreetmap.org/search?format=json&q=" + address
winhttp.Open('GET', url, False)
winhttp.Send()
list = json.loads(winhttp.responseText)
print(list[0].get('lat'))
print(list[0].get('lon'))
Expected output:
Latitude: 47.670119
Longitude: -122.118237
Or you may also wish to avoid copying the element altogether, use get_attribute('value') to read the value in latitude and longitude. Example:
chromedriver = 'C:\\Users\\UserName\\Downloads\\chromedriver.exe'
driver = webdriver.Chrome(chromedriver)
driver.get('http://www.whatsmygps.com')
element = driver.find_element_by_id("address")
element.send_keys(Keys.CONTROL, 'a')
#enter Microsoft's zip code
element.send_keys('98052-6399')
element.submit()
time.sleep(3)
lat_input = driver.find_element_by_id("latitude")
print('latitude: ')
print(lat_input.get_attribute('value'))
lon_input = driver.find_element_by_id("longitude")
print('longitude: ')
print(lon_input.get_attribute('value'))
driver.close()

Resources