Ephem not updating real time - python-3.x

I have a program with a map on a canvas. When I scroll over the map it displays on the screen the longitude and latitude of where the mouse pointer is located, updated realtime. As well, when I move the mouse it show the sunrise, sunset, moonrise, moonset, and moon phase for where I am at on the screen. Everything is working fine except ephem obviously doesn't update real time.
This is the ephem specific part of the code that is run everytime the mouse is moved.
self.maploc.lat, self.maploc.lon = str(py), str(px)
sr = str(self.maploc.next_rising(ephem.Sun()
ss = str(self.maploc.next_setting(ephem.Sun()))
snr = sr.split(' ')
sns = ss.split(' ')
self.maploc.lat, self.maploc.lon = str(py), str(px)
mr = str(self.maploc.next_rising(ephem.Moon()))
ms = str(self.maploc.next_setting(ephem.Moon()))
mn = ephem.Moon()
mn.compute(self.maploc)
mnr = mr.split(' ')
mns = ms.split(' ')
I would think running the mn.compute(self.maploc) would do a complete update of the map coordinates but it doesn't. Granted yesterday as I started tinkering with this idea I noticed it didn't seem to be doing live updating with the sunrise times either.
How do I get real time updating or can I with ephem.
If I run the program the moon phase will always stay the same until I close out the program and restart the program.

You might need to reset the maploc’s date, otherwise its routines like next_rising() will probably just compute times based on the date it got when you created it.
from ephem import now
...
self.maploc.date = now()
That is how you can update the maploc to start thinking about calculations from a new date and time. Good luck!

Related

Binance, ccxt futures, problem about amount in order

I got an interest about ccxt these days, especially futures trade
i tried to make a logic and it was fun
but I've got a problem to "Setting amount"
def binance_long():
order = binance.create_market_buy_order(
symbol = symbol,
amount=0.001
)
def binance_short():
order = binance.create_market_sell_order(
symbol=symbol,
amount=0.001
)
this is my buy/sell function
In that codes, I want to put my whole usdt dollars
but i don't know how to change amount
because that 0.001 position is based on btc not usdt
how can i put my whole usdt dollars in my position?
ex)729.8 usdt -> put that whole thing
also using leverage too (1~50)
and also how can i close my position with my whole usdt?
because In order, I understood that I had to write this function and then use this function.
binance_long() <- buy long position
binance_short() <- close long position
like this
schedule.every().monday.at("00:00:00").do(binance_long)
schedule.every().monday.at("00:00:30").do(binance_short)
To Open position and Close position in Long position

How to show ad banner depends on datetime?

I am trying to make a small algorithm to show an ad inside a container that contains a three banners but not to show all of them at once, I want to show just one every day.
Lets say each banner have to appear at a certain date time as showing bellow in the list:
ads = [
{
'banner': f'{ads_path}/1/ad_1917_175.gif',
'dtime': datetime.now() + timedelta(minutes=1)
},
{
'banner': f'{ads_path}/2/ad_1917x175.gif',
'dtime': datetime.now() + timedelta(minutes=2)
},
{
'banner': f'{ads_path}/3/ad_1917x175_2.gif',
'dtime': datetime.now() + timedelta(minutes=3)
}
]
all banners are saved inside database where I can filter each one by it offset, also I've created a datetime.now() variable to compare it with the dtime in my query, something like this:
dtime_now = datetime.now()
get_banner = Ads.query.filter(Ads.dtime < dtime_now).offset(1).limit(1)
From here I want to start, and the iteration will go to first banner if all dates inside database are smaller than the current time.
dtimes = [datetime.strptime(str(item.dtime), '%Y-%m-%d %H:%M:%S.%f') for item in get_ads]`
I've tried to combine the list of all dtimes to get them all in one datetime object, then to look if the result is smaller than the current time, that means go to first banner change it dtime and show it and so on.
But Python won't let you do that, because it just combines timedelta.
Any suggestions how to make that work? what is the best way to do that?
Not sure I'm following your logic, but you don't need a database to do this. How about:
ad_change_times = [datetime_1, datetime_2, datetime_3]
for i in range(len(ad_change_times)): # or range(1, len(ad_change_times)+1) if you insist on counting from 1
if datetime.now() > ad_change_times[i]:
banner = f'{ads_path}/{i}/ad_1917_175.gif',
break
Then, send that to your template.

PyEphem: How to test if an object is above the horizon?

I am writing a Python script that gives basic data for all the planets, the Sun and the Moon. My first function divides the planets between those that are above the horizon, and those that are not risen yet:
planets = {
'mercury': ephem.Mercury(),
'venus': ephem.Venus(),
'mars': ephem.Mars(),
'jupiter': ephem.Jupiter(),
'saturn': ephem.Saturn(),
'uranus': ephem.Uranus(),
'neptune': ephem.Neptune()
}
def findVisiblePlanets(obs):
visiblePlanets = dict()
notVisiblePlanets = dict()
for obj in planets:
planets[obj].compute(obs)
if planets[obj].alt > 0:
visiblePlanets[obj] = planets[obj]
else:
notVisiblePlanets[obj] = planets[obj]
return (visiblePlanets, notVisiblePlanets)
This works alright, the tuple I receive from findVisiblePlanets corresponds corresponds to the actual sky for the given 'obs'.
But in another function, I need to test the altitude of each planet. If it's above 0, the script displays 'setting at xxx', and if it's under 0, the script displays 'rising at xxx'. Here is the code:
if bodies[obj].alt > 0:
print(' Sets at', setTime.strftime('%H:%M:%S'), deltaSet)
else:
print(' Rises at', riseTime.strftime('%H:%M:%S'), deltaRise)
So I'm using the exact same condition, except that this time it doesn't work. I am sure I have the correct object behind bodies[obj], as the script displays name, magnitude, distance, etc. But for some reason, the altitude (.alt) is always below 0, so the script only displays the rising time.
I tried print(bodies[obj].alt), and I receive a negative figure in the form of '-0:00:07.8' (example). I tried using int(bodies[obj].alt) for the comparison but this ends up being a 0. How can I test if the altitude is negative? Am I missing something obvious here?
Thanks for your help.
I thinkk I had a similar problem once. How I understand it pyephem forwards the time of your observer, when you call nextrising() or nextsetting() on a object. It somehow looks, at which timepoint the object is above/below the horizont for the first time. if you then call the bodie.alt it will always be this little bit below/above horizon.
You have to store your observer time somehow and set it again after calculating setting/rising times.

How to increment counters based on a column value being fixed in a Window?

I have a dataset that, over time, indicates the region where certain users were located. From this dataset I want to calculate the number of nights that they spent at each location. By "spending the night" I mean: take the last location seen of a user until 23h59 of a certain day; if all observed locations from that user until 05:00 the next day, or the first one after that if there is none yet, match the last of the previous day, that's a night spent at that location.
| Timestamp| User| Location|
|1462838468|49B4361512443A4DA...|1|
|1462838512|49B4361512443A4DA...|1|
|1462838389|49B4361512443A4DA...|2|
|1462838497|49B4361512443A4DA...|3|
|1465975885|6E9E0581E2A032FD8...|1|
|1457723815|405C238E25FE0B9E7...|1|
|1457897289|405C238E25FE0B9E7...|2|
|1457899229|405C238E25FE0B9E7...|11|
|1457972626|405C238E25FE0B9E7...|9|
|1458062553|405C238E25FE0B9E7...|9|
|1458241825|405C238E25FE0B9E7...|9|
|1458244457|405C238E25FE0B9E7...|9|
|1458412513|405C238E25FE0B9E7...|6|
|1458412292|405C238E25FE0B9E7...|6|
|1465197963|6E9E0581E2A032FD8...|6|
|1465202192|6E9E0581E2A032FD8...|6|
|1465923817|6E9E0581E2A032FD8...|5|
|1465923766|6E9E0581E2A032FD8...|2|
|1465923748|6E9E0581E2A032FD8...|2|
|1465923922|6E9E0581E2A032FD8...|2|
I'm guessing I need to use Window functions here, and I've used PySpark for other things in the past, but I'm a bit at a loss as to where to start here.
I think in the end you do need to have a function that takes a series of events and outputs nights spent... something like (example just to get the idea):
def nights_spent(location_events):
# location_events is a list of events that have time and location
location_events = sort_by_time(location_events)
nights = []
prev_event = None
for event in location_events[1:]:
if prev_location is not None:
if next_day(prev_event.time, event.time) \
and same_location(prev_event.location, event.location):
# TODO: How do you handle when prev_event
# and event are more than 1 day apart?
nights.append(prev_location)
prev_location = location
return nights
Then, I think that a good first approach is to first group by user so that you get all events (with location and time) for a given user.
Then you can feed that list of events to the function above, and you'll have all the (user, nights_spent) rows in an RDD.
So, in general, the RDD would look something like:
nights_spent_per_user = all_events.map(lambda x => (x.user, [(x.time, x.location)])).reduce(lambda a, b: a + b).map(x => (x[0], nights_spent(x[1])))
Hope that helps to get you started.

how to predict with gaussianhmm sklearn

I'm trying to predict stock prices using sklearn. I'm new to prediction. I tried the example from sklearn for stock prediction with gaussian hmm. But predict gives states sequence which overlay on the price and it also takes points from given input close price. My question is how to generate next 10 prices?
You will always use the last state to predict the next state, so let's add 10 days worth of inputs by changing the end date to the 23rd:
date2 = datetime.date(2012, 1, 23)
You can double check the rest of the code to make sure I am not actually using future data for the prediction. The rest of these lines can be added to the bottom of the file. First we want to find out what the expected return is for a given state. The model.means_ array has returns, both those were the returns that got us to this state, not the future returns which is what you want. To get the future returns, we consider the probability of going to any one of the 5 states, and what the return of those states is. We get the probability of going to any particular state from the model.transmat_ matrix, the for the return of each state we use the model.means_ values. We take the dot product to get the expected return for a particular state. Then we remove the volume data (you can leave it in if you want, but you seemed to be most interested in future prices).
expected_returns_and_volumes = np.dot(model.transmat_, model.means_)
returns_and_volumes_columnwise = zip(*expected_returns_and_volumes)
returns = returns_and_volumes_columnwise[0]
If you print the value for returns[0], you'll see the expected return in dollars for state 0, returns[1] for state 1 etc. Now, given a day and a state, we want to predict the price for tomorrow. You said 10 days so let's use that for lastN.
predicted_prices = []
lastN = 10
for idx in xrange(lastN):
state = hidden_states[-lastN+idx]
current_price = quotes[-lastN+idx][2]
current_date = datetime.date.fromordinal(dates[-lastN+idx])
predicted_date = current_date + datetime.timedelta(days=1)
predicted_prices.append((predicted_date, current_price + returns[state]))
print(predicted_prices)
If you were running this in "production" you would set date2 to the last date you have and then lastN would be 1. Note that I don't take into account weekends for the predicted_date.
This is a fun exercise but you probably wouldn't run this in production, hence the quotes. First, the time series is the raw price; this should really be percentage returns or log returns. Plus there is no justification for picking 5 states for the HMM, or that a HMM is even good for this kinda problem, which I doubt. They probably just picked it as an example. I think the other sklearn example using PCA is much more interesting.

Resources