I'm new to Python and API and am trying to start with some basics like making a list/plot of old BTC prices. I imported the Coinbase Wallet Client and used client.get_historic_prices(), which gave me a list of the price at midnight UTC for 365 days.
How can I adjust the parameters to get different date ranges and data resolution, for example each minute for two years? Is there a way to search the historic values of buy, sell, and spot separately?
from coinbase.wallet.client import Client
hist_price = client.get_historic_prices()
xx=[]
yy=[]
for ii in range(365):
xx.append(ii*-1) # x coordinate being "days ago"
yy.append(float(hist_price['prices'][ii]['price']))
Returns (this is just from a print statement of print(hist_price['prices'][0:3]). So it's midnight once a day.
prices
length = 365
{
"price": "974.39",
"time": "2017-02-01T00:00:00Z"
}
{
"price": "944.29",
"time": "2017-01-31T00:00:00Z"
}
{
"price": "920.47",
"time": "2017-01-30T00:00:00Z"
}
Get_historic_prices is not clearly documented anywhere. This is a mini guide of what I have managed to discover about it and its usage. It's not much but it should be somewhere.
get_historic_prices supports one argument called period which can take the following values:
hour
day
week
month
year
all
Each of them except all returns approximately a list of 360 price points distributed more or less uniformly in the previous hour (day, week, month, year respectively).
all returns a list of price points one for each day at 00:00:00 UTC (i think).
get_historic_prices should also support a currency_pair argument as do the get_buy_price, get_sell_price, and get_spot_price do. Unfortunately, although I have submitted a PR, it has not been merged yet.
Related
I am a beginner to SPARQL and I managed to implement a query that returns the historical time period (P2348) for when an item was created, examples of this are 'Bronze age', 'Mesolithic', 'Nguyen dynasty' etc. I also have other items that return a specific year for when they were created. I was wondering if there is any way to convert the historical periods into an approximate year instead of the name of a period. It obviously doesn't have to be accurate at all just a year in that time period.
If you have an age you can query its start and end time. Here is an example:
select ?age ?age_name ?start_time ?end_time {
?age wdt:P31 wd:Q15401699. # age is archeological age.
?age rdfs:label ?age_name. filter(lang(?age_name)='en').
?age wdt:P580 ?start_time.
?age wdt:P582 ?end_time.
}
I am playing with python code for looking at my work rota.
I have made a nice script which reads the rota document sent to me and extracts all of my shifts into datetimes for shift start and end, it can also reformat them into google calendar events which is great for automating my calendar.
I now want to look at my rota and compare it against the contractual rules for my rota pattern.
The rule I am looking at presently is:
"no more than 72 hours of work in any 7 day period"
Now, this is very easy to look at each week and calculate how many hours are worked. I have made this work as below:
def hours_per_week(df):
df["Week Start"] = pd.to_datetime(df["Start Date"]) - pd.to_timedelta(7, unit="d")
df = (
df.groupby([pd.Grouper(key="Week Start", freq="W-MON")])["Shift Length"]
.sum()
.reset_index()
.sort_values("Week Start")
)
df = df.rename(columns={"Shift Length": "Hours"})
df["Hours"] = df["Hours"] / np.timedelta64(1, "h")
return df
However, this method calculates the hours in the 7 day period from 0000 every Monday. The rule applies to ANY 7 day period so from 0500 on a Wednesday would be equally relevant as from 0000 on Monday.
The only way I can think of doing this is by iterating through EVERY possible hour working out the hours worked in the 7 day period from that hour. This would be easy enough but seems hugely inefficient. Before I go about writing this ugly piece of code, does anyone have an idea of a better approach to this problem?
This is for Python:
I need a library that is able to do arithmetic operations on dates while taking into account the duration of a month and or year.
For example, say I add a value of "1 day" to 3/31/2020, the result of should return:
1 + 3/31/2020 = 4/1/2020.
I also would need to be able to convert this to datetime format, and extract day, year and month.
Does a library like this exist?
import datetime
tday = datetime.date.today() # create today
print("Today:", tday)
""" create one week time duration """
oneWeek = datetime.timedelta(days=7)
""" create 1 day and 1440 minutes of time duraiton """
eightDays = datetime.timedelta(days=7, minutes=1440)
print("A week later than today:", tday + oneWeek) # print today +7 days
And the output to this code snippet is:
Today: 2020-03-25
A week later than today: 2020-04-01
>>>
As you see, it takes month overflows into account and turns March to April. datetime module has lots of things, I don't know all its attributes well and haven't used for a long time. However, I believe you can find nice documentation or tutorials on the web.
You definitely can create any specific date(there should be some constraints though) instead of today by supplying day, month and year info. I just don't remember how to do it.
I'm trying to program a salary calculator that tells you what your salary is during sick leave. In Costa Rica, where I live, salaries are paid bi-monthly (the 15th and 30th of each month), and each sick day you get paid 80% of your salary. So, the program asks you what your monthly salary is and then asks you what was the start date and finish date of your sick leave. Finally, it's meant to print out what you got paid each payday between your sick leave. This is what I have so far:
import datetime
salario = float(input("What is your monthly salary? "))
fecha1 = datetime.strptime(input('Start date of sick leave m/d/y: '), '%m/%d/%Y')
fecha2 = datetime.strptime(input('End date of sick leave m/d/y: '), '%m/%d/%Y')
diasinc = ((fecha2 - fecha1).days)
print ("Number of days in sick leave: ")
print (diasinc)
def daterange(fecha1, fecha2):
for n in range(int ((fecha2 - fecha1).days)):
yield fecha1 + timedelta(n)
for single_date in daterange(fecha1, fecha2):
print (single_date.strftime("%Y-%m-%d")) #This prints out each individual day between those dates.
I know for the salary I just multiply it by .8 to get 80% but how do I get the program to print it out for each pay day?
Thank you in advance.
Here's an old answer to a similar question from about eight years ago: python count days ignoring weekends ...
... read up on the Python: datetime module and adjust Dave Webb's generator expression to count each time the date is on the 15th or the 30th. Here's another example for counting the number of occurrences of Friday on the 13th of any month.
There are fancier ways to shortcut this calculation using modulo arithmetic. But they won't matter unless you're processing millions of these at a time on lower powered hardware and for date ranges spanning months at a time. There may even be a module somewhere that does this sort of thing, more efficiently, for you. But it might be hard for you to validate (test for correctness) as well as being hard to find.
Note that one approach which might be better in the long run would be to use Python: SQLite3 which should be included with the standard libraries of your Python distribution. Use that to generate a reference table of all dates over a broad range (from the founding of your organization until a century from now). You can add a column to that table to note all paydays and use SQL to query that table and select the dates WHERE payday==True AND date BETWEEN .... etc.
There's an example of how to SQLite: Get all dates between dates.
That approach invests some minor coding effort and some storage space into a reference table which can be used efficiently for the foreseeable future.
I am trying to determine if its a day or night based on list of timestamps. Will it be correct if I just check the hour between 7:00AM to 6:00PM to classify it as "day", otherwise "night"? Like I have done in below code. I am not sure of this because sometimes its day even after 6pm so whats the accurate way to differentiate between day or night using python?
sample data: (timezone= utc/zulutime)
timestamps = ['2015-03-25 21:15:00', '2015-06-27 18:24:00', '2015-06-27 18:22:00', '2015-06-27 18:21:00', '2015-07-07 07:53:00']
Code:
for timestamp in timestamps:
time = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
hr, mi = (time.hour, time.minute)
if hr>=7 and hr<18: print ("daylight")
else: print ("evening or night")
sample output:
evening or night
evening or night
evening or night
evening or night
daylight
You could use pyephem for this task. It's a
Python package for performing high-precision astronomy computations.
You could set the desired location and get the sun altitude. There are multiple definitions for night, depending if it's for civil (-6°), nautical (-12°) or astronomical (-18°) purposes. Just pick a treshold : if the sun is below, it's nighttime!
#encoding: utf8
import ephem
import math
import datetime
sun = ephem.Sun()
observer = ephem.Observer()
# ↓ Define your coordinates here ↓
observer.lat, observer.lon, observer.elevation = '48.730302', '9.149483', 400
# ↓ Set the time (UTC) here ↓
observer.date = datetime.datetime.utcnow()
sun.compute(observer)
current_sun_alt = sun.alt
print(current_sun_alt*180/math.pi)
# -16.8798870431°
As a workaround, there is a free api for adhan times for muslims. It includes sunset and sunrise times exactly. However you still need location coordinates to obtain the data. It is free at the moment.
Unfortunately python's timestamp cannot determine whether it's day or night. This is also because it depends on where you are located and how exactly you define day and night. I'm afraid you will have to get auxiliary data for that.
You need to know both latitude and longitude. In fact, if a place is in a deep valley the sunrise there will be later and the sunset earlier. You can pay for this service if you need to obtain it many times per day or simply scrape pages like the one at https://www.timeanddate.com/worldclock/uk/london.