How to get historical data from yahoo finance with base currency - yahoo

I am trying to get historical data from yahoo finance but it gives me only for current date how can i get data with base currency on a specific date.
http://query.yahooapis.com/v1/public/yql?q=select+*+from+yahoo.finance.xchange+where+pair+in%28%22PKRUSD%22%2C%22PKRGBP%22%2C%22PKRKWD%22%2C%22PKRSAR%22%29&format=json&env=store://datatables.org/alltableswithkeys

There seems to be no way to get historical exchange rates of two currencies of your choice, however, you can get historical exchange rates from USD to any currency in the world. Here is how you get that:
SELECT * FROM yahoo.finance.historicaldata WHERE symbol = "CCC=X" AND startDate = "YYYY-MM-DD" AND endDate = "YYY-MM-DD"
There you choose your currency(CCC) and dates in YYYY-MM-DD format. Example, this will give you the exchange rates from USD to SEK for 2014-10-01 until 2014-10-03:
SELECT * FROM yahoo.finance.historicaldata WHERE symbol = "SEK=X" AND startDate = "2014-10-02" AND endDate = "2014-10-03"
This query will produce the following response:
{
query: {
count: 3,
created: "2016-09-10T12:53:42Z",
lang: "sv-SE",
results: {
quote: [
{
Symbol: "SEK%3dX",
Date: "2014-10-03",
Open: "7.182",
High: "7.29607",
Low: "7.182",
Close: "7.1817",
Volume: "000",
Adj_Close: "7.1817"
},
{
Symbol: "SEK%3dX",
Date: "2014-10-02",
Open: "7.2151",
High: "7.2174",
Low: "7.1723",
Close: "7.217",
Volume: "000",
Adj_Close: "7.217"
}
]
}
}
}
You can always make this twice for two currencies and divide them to get the exhange rates between the two. Example:
USD/SEK: 8.5
USD/EUR: 0.85
SEK/EUR = 8.5/0.85 = 10.
Hope this answer will be to help.

Related

Time Conversion from str to float (00:54:50) -> (54.8) for example

I am trying to convert my time watched in a Netflix show to a float so I can total it up. I cannot figure out how to convert it. I have tried many ways, including:
temp['Minutes'] = temp['Duration'].apply(lambda x: float(x))
Error: ValueError: could not convert string to float: '00:54:45'
''' 2022-05-18 05:21:42 00:54:45 NaN Ozark: Season 4: Mud (Episode 13)
NaN Amazon FTVET31DOVI2020 Smart TV 00:54:50 00:54:50 US (United
States) Wednesday 2022-05-18
'''
I have pulled the day of week and Day out but I would like to plot it just for fun and think the minutes would be the best to add up over time.
Do it like this:
var = '00:54:45'
var_array = var.split(':')
float = float(var_array[1]) + (float(var_array[2])/60)
print(float)
Output: 54.75 (from here u can round the second part, since it's a plus it wouldn't affect the first term)

Can GA4-API fetch the data from requests made with a combination of minute and region and sessions?

Problem
With UA, I was able to get the number of sessions per region per minute (a combination of minute, region, and sessions), but is this not possible with GA4?
If not, is there any plan to support this in the future?
Detail
I ran GA4 Query Explorer with date, hour, minute, region in Dimensions and sessions in Metrics.
But I got an incompatibility error.
What I tried
I have checked with GA4 Dimensions & Metrics Explorer and confirmed that the combination of minute and region is not possible. (see image below).
(updated 2022/05/16 15:35)Checked by Code Execution
I ran it with ruby.
require "google/analytics/data/v1beta/analytics_data"
require 'pp'
require 'json'
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = '' # service acount file path
client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new
LIMIT_SIZE = 1000
offset = 0
loop do
request = Google::Analytics::Data::V1beta::RunReportRequest.new(
property: "properties/xxxxxxxxx",
date_ranges: [
{ start_date: '2022-04-01', end_date: '2022-04-30'}
],
dimensions: %w(date hour minute region).map { |d| { name: d } },
metrics: %w(sessions).map { |m| { name: m } },
keep_empty_rows: false,
offset: offset,
limit: LIMIT_SIZE
)
ret = client.run_report(request)
dimension_headers = ret.dimension_headers.map(&:name)
metric_headers = ret.metric_headers.map(&:name)
puts (dimension_headers + metric_headers).join(',')
ret.rows.each do |row|
puts (row.dimension_values.map(&:value) + row.metric_values.map(&:value)).join(',')
end
offset += LIMIT_SIZE
break if ret.row_count <= offset
end
The result was an error.
3:The dimensions and metrics are incompatible.. debug_error_string:{"created":"#1652681913.393028000","description":"Error received from peer ipv4:172.217.175.234:443","file":"src/core/lib/surface/call.cc","file_line":953,"grpc_message":"The dimensions and metrics are incompatible.","grpc_status":3}
Error in your code, Make sure you use the actual dimension name and not the UI name. The correct name of that dimension is dateHourMinute not Date hour and minute
dimensions: %w(dateHourMinute).map { |d| { name: d } },
The query explore returns this request just fine
results
Limited use for region dimension
The as for region. As the error message states the dimensions and metrics are incompatible. The issue being that dateHourMinute can not be used with region. Switch to date or datehour
at the time of writing this is a beta api. I have sent a message off to google to find out if this is working as intended or if it may be changed.

RUBY - Currency Exchange Rate Calculator

I'm trying to create a currency converter in Ruby which will calculate the exchange rate between two currencies on a given date.
I have a data file containing test data (date, currency from, currency to). The test data is in EUR, so all rates are converted to EUR and then to the target currency.
So far I have 3 files (Exchange.rb, Test_Exchange.rb, rates.json):
Exchange.rb:
require 'json'
require 'date'
module Exchange
# Return the exchange rate between from_currency and to_currency on date as a float.
# Raises an exception if unable to calculate requested rate.
# Raises an exception if there is no rate for the date provided.
#rates = JSON.parse(File.read('rates.json'))
def self.rate(date, from_currency, to_currency)
# TODO: calculate and return rate
rates = u/rates[date] # get rates of given day
from_to_eur = 1.0 / rates[from_currency] # convert to EUR
from_to_eur * rates[to_currency] # convert to target currency
end
end
Test_Exchange.rb:
require_relative 'Exchange.rb'
require 'date'
target_date = Date.new(2018,12,10).to_s
puts "USD to GBP: #{Exchange.rate(target_date, 'USD', 'GBP')}"
puts "USD to JPY: #{Exchange.rate(target_date, 'PLN', 'CHF')}"
puts "DKK to CAD: #{Exchange.rate(target_date, 'PLN', 'CHF')}"
rates.json:
{
"2018-12-11": {
"USD": 1.1379,
"JPY": 128.75,
"BGN": 1.9558,
"CZK": 25.845,
"DKK": 7.4641,
"GBP": 0.90228,
"HUF": 323.4,
"CHF": 1.1248,
"PLN": 4.2983
},
"2018-12-10": {
"USD": 1.1425,
"JPY": 128.79,
"BGN": 1.9558,
"CZK": 25.866,
"DKK": 7.4639,
"CAD": 1.5218,
"GBP": 0.90245,
"HUF": 323.15,
"PLN": 4.2921,
"CHF": 1.1295,
"ISK": 140.0,
"HRK": 7.387,
"RUB": 75.8985
},
"2018-12-05": {
"USD": 1.1354,
"JPY": 128.31,
"BGN": 1.9558,
"CZK": 25.886,
"DKK": 7.463,
"GBP": 0.88885,
"HUF": 323.49,
"PLN": 4.2826,
"RON": 4.6528,
"SEK": 10.1753,
"CHF": 1.1328,
"HRK": 7.399,
"RUB": 75.8385,
"CAD": 1.5076
}
}
I'm not sure what to add in the Exchange.rb file to allow the user to input a date and the two currencies to compare exchange rates.
Running Exchange.rb does nothing. I'm guessing it wants a date and currency parameters input?
Running Test_Exchange.rb works because the date and currencies are bootstrapped in.
I found almost the same question posted here a couple years ago, but the thread is now closed, and the solution was incomplete. Hoping someone can help me!
RUNNING EDIT:
Exchange.rb:
require 'json'
require 'date'
module Exchange
# Return the exchange rate between from_currency and to_currency on date as a float.
# Raises an exception if unable to calculate requested rate.
# Raises an exception if there is no rate for the date provided.
#rates = JSON.parse(File.read('rates.json'))
#Grab Date and Currencies from User
puts "Please enter a Date (YYYY-MM-DD)"
input_date = gets.chomp
puts "The Date you entered is: #{input_date}"
puts "Please enter a 3-letter Currency Code (ABC):"
input_curr_1 = gets.chomp
puts "The 1st Currency you entered is: #{input_curr_1}"
puts "Please enter a 2nd 3-letter Currency Code (XYZ):"
input_curr_2 = gets.chomp
puts "The 2nd Currency you entered is: #{input_curr_2}"
def self.rate(input_date, input_curr_1, input_curr_2)
# TODO: calculate and return rate
rates = #rates[input_date] # get rates of given day
from_to_eur = 1.0 / rates[input_curr_1] # convert to EUR
from_to_eur * rates[input_curr_2] # convert to target currency
end
end
I think I have to use a put and a get to capture the user date input? Then the same for each of the two currencies? Of course, my syntax for the date stuff is all wrong..
So I managed to use the gets and put functions. Now all that's left is somehow calling the rates.json file and comparing the user inputs to the existing data..

How to get athleteId from first/last name using ESPN APIs?

Using ESPN's developer API's, you can query for news on a specific athlete using the 'athleteId'. See the Methods section of their docs:
http://developer.espn.com/docs/headlines#parameters
If you look up a player profile you can find the athlete id in the url of the page, but my question is how can we find this id using solely the APIs? With just the athlete's name?
If you go to a team's roster page, use inspect element, or whatever equivalent for the browser you use, and look at the table element of all the players on the team. Within the 'td' tags, you'll find a player ID. You could scrape the screen, store all of the player ids locally, and then use them as parameters in your api calls.
This is merely a suggestion, but it should work, if the id that is used on the page is the same as the id needed to get that player's information in api.
As stated, it's all available in the api:
import requests
import pandas as pd
url = 'https://sports.core.api.espn.com/v3/sports/football/nfl/athletes?limit=18000'
jsonData = requests.get(url).json()
players = pd.DataFrame(jsonData['items']).dropna(subset='firstName')
players = players[['id', 'fullName']].dropna()
Output:
print(players)
id fullName
6 14856 Isaako Aaitui
7 3058033 Manny Abad
8 16836 Jared Abbrederis
9 2576467 Mehdi Abdesmad
10 14466 Isa Abdul-Quddus
... ...
16920 16424 Mike Zupancic
16921 15462 Markus Zusevics
16922 11317 Jeremy Zuttah
16923 4294520 Brandon Zylstra
16924 4608362 Shane Zylstra
[16919 rows x 2 columns]
All NFL player ID can be found on this page
https://sports.core.api.espn.com/v3/sports/football/nfl/athletes?limit=18000
This will return all NFL players ID , name and DOB
function GetESPNIds() {
var url = 'https://sports.core.api.espn.com/v3/sports/football/nfl/athletes?limit=20000';
$.ajax({
type: "GET",
url: url,
success: function (data) {
for (var i=0;i<data.items.length;i++) {
if(data.items[i].hasOwnProperty("lastName") && data.items[i].hasOwnProperty("firstName") && data.items[i].hasOwnProperty("dateOfBirth")) {
console.log("Name: "+data.items[i].lastName+","+data.items[i].firstName +" ID: " +data.items[i].id +" DOB: " +data.items[i].dateOfBirth);
}
}
}
});
}
GetESPNIds();

In KRL How can I get the current year, month, and day?

I am working on an application in which I need to get the current year, month, and day. Is there a way to get this information in the pre block of a rule?
Can I get this data as a string or a number or both?
There are currently time functions documented on http://docs.kynetx.com/docs/Time but none of them seem to work for what I am trying to do.
Is there a way to set the timezone when getting this data?
I was able to do it using strftime which appears to be an undocumented feature so use with caution.
ruleset a60x518 {
meta {
name "date-test"
description <<
date-test
>>
author "Mike Grace"
logging on
}
rule testing {
select when pageview ".*"
pre {
retTime = time:strftime(time:now({"tz":"America/Denver"}), "%c");
month = time:strftime(time:now({"tz":"America/Denver"}), "%B");
year = time:strftime(time:now({"tz":"America/Denver"}), "%Y");
day = time:strftime(time:now({"tz":"America/Denver"}), "%d");
}
{
notify("time",retTime) with sticky = true;
notify("month",month) with sticky = true;
notify("year",year) with sticky = true;
notify("day",day) with sticky = true;
}
}
}
App run on example.com twice. Once with the timezone set to New York and onother time set to Denver
I used this site http://www.statoids.com/tus.html to get the correct strings to use for the timezone. I have no idea if they all work. I just found this site and tried a few and they worked so use with caution.
Perhaps the docs got reverted. For convenience, here is the documentation for strftime:
time:strftime()
Convert a datetime string to a different format
Usage
time:strftime(`<string>`,`<format>`)
Valid format arguments to strftime follow the POSIX strftime conventions.
Samples
time:strftime(xTime,”%F %T”) # 2010-10-06 18:15:24
time:strftime(xTime,”%F”) # 2010-10-06
time:strftime(xTime,”%T”) # 18:19:29
time:strftime(xTime,”%A %d %b %Y”) # Wednesday 06 Oct 2010
time:strftime(xTime,”%c”) # Oct 6, 2010 6:25:55 PM
The other time functions:
time:now()
Current datetime based upon user’s location data
Usage
time:now()
time:now({“tz” : <timezone>)
time:new()
Create a new RFC 3339 datetime string from a string (allows some flexibility in how the source string is formatted)
Usage
time:new() # Equivalent to time:now()
time:new(<string>)
Valid formats for the datetime source string can be found in ISO8601 (v2000).
time:add()
Add (or subtract) a specific number of time units to a source string
Usage
time:add(<string>,{<unit> : n})

Resources