ImportError from using the trading strategy in PyAlgoTrade tutorial - python

I got an import error while I am running a simple python written trading strategy in Pyalgotrade.
from pyalgotrade.tools import yahoofinance
yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed)
# We want a 15 period SMA over the closing prices.
self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15)
self.__instrument = instrument
def onBars(self, bars):
bar = bars[self.__instrument]
self.info("%s %s" % (bar.getClose(), self.__sma[-1]))
# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()
And the error is showed as below.
>>>Traceback (most recent call last):
File "/Users/johnhenry/Desktop/pyalgotrade2.py", line 1, in <module>
from pyalgotrade import strategy
File "/Users/johnhenry/Desktop/pyalgotrade.py", line 1, in <module>
from pyalgotrade import strategy
ImportError: cannot import name strategy
I am sure I have this library called pyalgotrade.

You named your own program pyalgotrade.py:
File "/Users/johnhenry/Desktop/pyalgotrade.py"
so Python thinks that's the one you mean. Rename your program to something else, delete any pyalgotrade.pyc or pyalgotrade.pyo files you may have, and restart your interpreter.

Related

Getting NameError: name 'video' is not defined in Vapoursynth/Python

Trying to make a gif in vapoursynth, followed tutorials yet keep getting name error. If anyone could help explain what's wrong with it and how to fix it, I would appreciate it.
Failed to initialize script.
Failed to evaluate the script:
Python exception: name 'video' is not defined
Traceback (most recent call last):
File "src\cython\vapoursynth.pyx", line 1927, in
vapoursynth.vpy_evaluateScript
File "src\cython\vapoursynth.pyx", line 1928, in
vapoursynth.vpy_evaluateScript
File "C:/Users/caitl/Pictures/bbh.vpy", line 12, in
core.max_cache_size = 1000 #Use this command to limit the RAM usage. 1000 or 2000 is fine.
NameError: name 'video' is not defined
Code
import os
import vapoursynth as vs
import havsfunc as haf
import mvsfunc as mvs
import descale as descale
import muvsfunc as muvs
import resamplehq as rhq
import CSMOD as cs
import Dither as dither
core = vs.get_core()
video = core.std.Trim(video, a, b)
video = haf.QTGMC(video, Preset="Slower", TFF=True)
video = core.fmtc.resample(video, css="444")
video = descale.Debilinear(video, 629,354)
video = mvs.BM3D(video, sigma=8.84, radius1=1, profile1="fast", matrix="709")
video = hnw.FineSharp(video, sstr=1.13)
video = core.std.CropRel(video, left=72, top=52, right=107, bottom=52)
video = core.fmtc.bitdepth(video, bits=8)
video.set_output()
You didn't define video before the call to Trim which takes it as a parameter.
The example script in the documentation says you need to create a video object, for example, by loading a file:
from vapoursynth import core
video = core.ffms2.Source(source='Rule6.mkv')
This loads a video file Rule6.mkv using the ffms2 plugin, which it assumes is installed correctly.

Poloniex Api Trouble

So I'm accessing the poloniex API with python and this is my code:
from poloniex import Poloniex
import krakenex
import threading
import pprint
import urllib.request
import json
####POLONIEX####
#FUNCTIONS
polo = Poloniex()
def BTC_USDT_LAST_POLONIEX():
polo = Poloniex()
threading.Timer(1.0, BTC_USDT_LAST_POLONIEX).start() # called every minute
print("BTC Last Price = " + (polo('returnTicker')['USDT_BTC']['last']))
def POLONIEX_ASSET_LIST():
pprint.pprint(sorted(list(polo('returnTicker'))))
Everything is working so far and I want to avoid using urllib as its a pain to turn a http request into a list. I'm trying to access the order book but get the following error:
>>> polo('returnOrderBook')
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
polo('returnOrderBook')
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/poloniex/retry.py", line 15, in wrapped
return function(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/poloniex/__init__.py", line 183, in __call__
return self.parseJson(ret.text)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/poloniex/__init__.py", line 197, in parseJson
raise PoloniexError(jsonout['error'])
poloniex.PoloniexError: Please specify a currency pair.
I've tried specifying the currency pair but have no idea how to plug it in.
Rewrite your code and use requests module instead of urllib:
import requests
ret = requests.get('http://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_BCN').json()
print ret
>>> {u'bids': [[u'0.00000034', 20629605.566027], [u'0.00000033', 43382683.465305], [u'0.00000032', 70007976.087993], [u'0.00000031', 49571221.248027], [u'0.00000030', 77520227.415484], [u'0.00000029', 46037827.046996], [u'0.00000028', 26267440.401662], [u'0.00000027', 22511987.85933], [u'0.00000026', 18885378.040015], [u'0.00000025', 13313109.292994], [u'0.00000024', 6243527.5236432], [u'0.00000023', 7504850.7832509], [u'0.00000022', 8443683.7997507], [u'0.00000021', 8996262.9826951], [u'0.00000020', 24601532.006268], [u'0.00000019', 26853346.478659], [u'0.00000018', 6027262.24889 etc....

How to download photos from Flickr by Flickr API in Python 3

noob question series...
I am a new learner of python, recently want to create a small python application that can collect photos from flickr based on different search input. (eg: if i input "dog", it will download all dog images from flickr)
I did some research online and notice that flickr API might be the best way and the method flickr.photos.getSizes should be the one I need to use.
However, I have few stupid questions when coding:
I have applied my key and secret for flickr API, I just don't know what to do next with flickr.photos.getSizes in python to download photos. Like, how to call this method in python? (and I noticed required arguments for this method are keys and photo_id, how to get photo_ids based on search input "dog")
Then I followed a tutorial from https://github.com/alexis-mignon/python-flickr-api/wiki/Tutorial but when I imported flickr_api I got error message:
Could not load all modules
<class 'ImportError'> No module named 'objects'
Traceback (most recent call last):
File "D:/Agfa/Projects/Image/flickr.py", line 2, in <module>
import flickr_api
File "D:\Application\Anaconda3\lib\site-packages\flickr_api\__init__.py", line 32, in <module>
from auth import set_auth_handler
ImportError: cannot import name 'set_auth_handler'
Then I took a look at the _ init _.py:
try:
from objects import *
import objects
import upload as Upload
from upload import upload, replace
except Exception as e:
print "Could not load all modules"
print type(e), e
from auth import set_auth_handler
from method_call import enable_cache, disable_cache
from keys import set_keys
from _version import __version__
Seems like this library does not support python 3 but I don't know what to do. (I cannot install methond_call, keys, _version on my python 3) guess I will use flickrapi
Thank you so much for your time and again thanks in advance.
I think I finally got the proper way to use FlickrAPI:
there are many ways but I figured out 2:
def flickr_walk(keyward):
count = 0
photos = flickr.walk(text=keyward,
tag_mode='all',
tags=keyward,
extras='url_c',
per_page=100)
for photo in photos:
try:
url=photo.get('url_c')
urllib.request.urlretrieve(url, path+'\\' + str(count) +".jpg")
except Exception as e:
print('failed to download image')
flickr.walk uses Photos.search API, I can use the API directly as well:
def flickr_search(keyward):
obj = flickr.photos.search(text=keyward,
tags=keyward,
extras='url_c',
per_page=5)
for photo in obj:
url=photo.get('url_c')
photos = ET.dump(obj)
print (photos)
Remember to get the key and secret first:
api_key = 'xxxxxxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxx'
flickr=flickrapi.FlickrAPI(api_key,api_secret,cache=True)
I dont have any clue on the why/how. If you want to use the flickr_api module with python3.5+, you need to fix the Imports, like I did below:
try:
from objects import *
import objects
import upload as Upload
from upload import upload, replace
except Exception as e:
#print "Could not load all modules"
print( type(e), e)
from .auth import set_auth_handler
from .method_call import enable_cache, disable_cache
from .keys import set_keys
from ._version import __version__
After this edit, it fails with another Import Error on:
>>> import flickr_api
<class 'SyntaxError'> invalid syntax (method_call.py, line 50)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/krysopath/.local/lib/python3.5/site-packages/flickr_api/__init__.py", line 32, in <module>
from .auth import set_auth_handler
File "/home/krysopath/.local/lib/python3.5/site-packages/flickr_api/auth.py", line 43, in <module>
import urlparse
ImportError: No module named 'urlparse'
So you can fix this by yourself, if you want to, by just walking along the Import Errors and adding a dot to convert them into absolute Imports, that dont fail.
I guess, if you want to use this modul you have to fix it first... and have an unknown return. So if you didnt already invested heavily, it might be more effective to use that other module.

Django views ImportError

I don't know if this logic is correct,
I'm trying to import a Django view in 2 different views.
I have an import chain like this:
the
a.views import b.views
b.views import c.views
c.views import d.views
and
d.views import b.views
but when I reach the last step I get an ImportError.
If I put a comment in d.views avoiding the import of b.views, it works.
I'm new with Django, can somebody help me?
If I use in a.views and in d.views the syntax
from b.views import *
it works, but.. the code is not so readable.
If I use
from b.views import my_func
it doesn't work!
This is the error from django shell:
>>> import maps.views
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/save/sites/myblog/maps/views.py", line 19, in <module>
from places.views import *
File "/Users/save/sites/myblog/places/views.py", line 22, in <module>
from posts.views import *
File "/Users/save/sites/myblog/posts/views.py", line 31, in <module>
from maps.views import render_map_geoloc
ImportError: cannot import name render_map_geoloc
Its because of cyclic dependency or circular reference.
b depends on c
c depends on d
d depends on b #which depends on c
Not sure for what purpose you are using. But you do explicit import to that function, and right above where its been used.
Looking at the error you are getting, it might be because of some dependency expected for d is coming from b so if you from b.views import *, it gets you that dependency. But if you import specific view (my_func), its missing that dependency.
Some more details you can find on SO answer thread - Django App Dependency Cycle

AttributeError: 'module' object has no attribute

I've been scouring the internet for a solution and everything i've come across hasn't helped. So now i turn to you.
Traceback (most recent call last):
File "cardreader.py", line 9, in <module>
import ATRdb as ATR
File "/home/pi/Desktop/CardReader/ATRdb.py", line 4, in <module>
import cardreader
File "/home/pi/Desktop/CardReader/cardreader.py", line 113, in <module>
main()
File "/home/pi/Desktop/CardReader/cardreader.py", line 40, in main
getData(db)
File "/home/pi/Desktop/CardReader/cardreader.py", line 98, in getData
if ATR.checkPerms(db,track1):
AttributeError: 'module' object has no attribute 'checkPerms'
I have two files cardreader.py & ATRdb.py
---ATRdb.py has this setup
import sys
import MYSQLdb
import datetime
import cardreader
def checkPerms(db, securitycode):
try:
cursor = db.cursor()
cursor.execute("""SELECT permissions FROM atrsecurity.employee WHERE securitycode = %s""", (securitycode))
r = cursor.fetchone()
Permissions = r
if '3' in Permissions[0]:
return True
else:
return False
except Exception:
cardreader.main()
return False
---cardreader.py has this setup
import sys
import usb.core
import usb.util
import MYSQLdb
import ATRdb as ATR
def main():
db = MYSQLdb.connect(HOST,USER, PASS, DB)
print("Please swipe your card...")
getData(db)
main()
db.close()
def getData(db):
#
#lots of code to get card data
#
if ATR.checkPerms(db, track1):
print ("User has permission")
unlockDoor()
i get the error at the "If ATR.checkPerms():" part. Any help would be appreciated
(first python project)
Your problem is circular imports.
In cardreader, you do this:
import ATRdb as ATR
That starts importing ATRdb, but a few lines into the code, it hits this:
import cardreader
The exact sequence from here depends on whether cardreader.py is your main script or not, and on whether your top-level code that calls main is protected by an if __name__ == '__main__' guard (and assuming that top-level code is in cardreader rather than elsewhere). Rather than try to explain all the possibilities in detail (or wait for you to tell us which one matches your actual code), let's look at what we know is true based on the behavior:
In some way, you're calling main before finishing the import of ATRdb.
This means that, at this point, ATRdb has nothing in it but sys, MYSQLdb, and datetime (and a handful of special attributes that every module gets automatically). In particular, it hasn't gotten to the definition of checkPerms yet, so no such attribute exists in the module yet.
Of course eventually it's going to finish importing the rest of ATRdb, but at that point it's too late; you've already called main and it tried to call ATR.checkPerms and that failed.
While there are various complicated ways to make circular imports work (see the official FAQ for some), the easiest and cleanest solution is to just not do it. If ATRdb needs some functions that are in cardreader, you should probably factor those out into a third module, like cardutils, that both ATRdb and cardreader can import.

Categories