Skip to content

Instantly share code, notes, and snippets.

@ruzo-ruzo
Last active September 24, 2025 08:15
Show Gist options
  • Select an option

  • Save ruzo-ruzo/17a2e56e24e823271cb0c5b1c5bd88fc to your computer and use it in GitHub Desktop.

Select an option

Save ruzo-ruzo/17a2e56e24e823271cb0c5b1c5bd88fc to your computer and use it in GitHub Desktop.
This script accesses WebDriver directly using Nushell. It has been tested with Nuspell version 0.107.0. It requires 7-Zip. Auto Downloading currently only supports Chrome and Firefox. There are not many usable endpoints.
# 一部 https://github.com/SeleniumHQ/selenium のデータを利用しています。
export def run [args: list<string> = [], browser = "chrome", driver = ""] {
let call = $in
let settings = start $args $browser $driver
try { { session: $settings.session, element: "" } | do $call } catch {
$settings | end
$in
}
$settings | end
}
export def start [args: list<string> = [], browser = "chrome", driver = ""] {
let webdriver_setting = setup $browser $driver
if $webdriver_setting.browser_path == "" {
error make { msg: "No appropriate browser exists." }
}
if $webdriver_setting.driver_path == "" {
error make { msg: "No appropriate webdriver exists." }
}
$webdriver_setting | start session $args
}
export def end [] {
let settings = $in
sleep 1sec
let _ = $settings | close
sleep 1sec
let _ = job kill $settings.job_id
$settings | cleanup
}
#----------- Receive a session and return a session
export def go [url: string] {
let session = $in.session
let _ = {url: ($url)} | to json | http post $"($session)/url"
{ session: $session, element: "" }
}
export def "open" [type = "window"] {
let session = $in.session
let request = {
type: $type
}
$request | to json| http post $"($session)/window/new"
{ session: $session, element: "" }
}
export def "close" [] {
let session = $in.session
http delete $"($session)"
{ session: $session, element: "" }
}
export def "back" [] {
let session = $in.session
{} | to json| http post $"($session)/back"
{ session: $session, element: "" }
}
export def "forward" [] {
let session = $in.session
{} | to json| http post $"($session)/forward"
{ session: $session, element: "" }
}
export def "refresh" [] {
let session = $in.session
{} | to json| http post $"($session)/refresh"
{ session: $session, element: "" }
}
export def "accept alert" [] {
let session = $in.session
{} | to json| http post $"($session)/alert/accept"
{ session: $session, element: "" }
}
export def "dismiss alert" [] {
let session = $in.session
{} | to json| http post $"($session)/alert/dismiss"
{ session: $session, element: "" }
}
export def "set alert text" [text = ""] {
let session = $in.session
{ text: $text } | to json| http post $"($session)/alert/text"
{ session: $session, element: "" }
}
export def "switch window" [handle: string] {
let session = $in.session
let request = {
handle: $handle
}
$request | to json | http post $"($session)/window"
{ session: $session, element: "" }
}
export def "set window rect" [x: int, y: int, width: int, height: int] {
let session = $in.session
let request = {
x: $x,
y: $y,
widht: $width,
heght: $height,
}
$request | to json | http post $"($session)/window/rect"
{ session: $session, element: "" }
}
export def "windows maximize" [] {
let session = $in.session
{} | to json| http post $"($session)/window/maximize"
{ session: $session, element: "" }
}
export def "windows minimize" [] {
let session = $in.session
{} | to json| http post $"($session)/window/minimize"
{ session: $session, element: "" }
}
export def "run script" [script: string, args: list<string> = []] {
let session = $in.session
let request = {
script: $script
args: $args
}
$request | to json | http post $"($session)/execute/sync"
{ session: $session, element: "" }
}
export def "run async script" [script: string, args: list<string> = []] {
let session = $in.session
let request = {
script: $script
args: $args
}
$request | to json | http post $"($session)/execute/async"
{ session: $session, element: "" }
}
export def "add cookie" [cookie: string] {
let session = $in.session
{ cookie: $cookie } | to json| http post $"($session)/cookie"
{ session: $session, element: "" }
}
export def "delete cookie" [name: string] {
let session = $in.session
http delete $"($session)/cookie/($name)"
{ session: $session, element: "" }
}
export def "delete all cookies" [] {
let session = $in.session
http delete $"($session)/cookie"
{ session: $session, element: "" }
}
export def "switch frame" [id: int] {
let session = $in.session
{ id: $id } | to json| http post $"($session)/frame"
{ session: $session, element: "" }
}
export def "switch parent frame" [] {
let session = $in.session
{} | to json| http post $"($session)/frame/parent"
{ session: $session, element: "" }
}
export def submit [] {
$in | select by type "submit" | set clicked
}
#----------- Receive a session and return it with element
export def "select by css" [field: string, value: string] {
let url = $in | get element url
let request = {
using:"css selector"
value:$"[($field)=($value)]"
}
let response = $request | to json | http post $"($url)/element" | get value
let element_id = $response | get "element-6066-11e4-a52e-4f735466cecf"
{ session: $in.session, element: $element_id }
}
export def "select by xpath" [path: string] {
let url = $in | get element url
let request = {
using:"xpath"
value:$path
}
let response = $request | to json | http post $"($url)/element" | get value
let element_id = $response | get ($response | columns | first)
{ session: $in.session, element: $element_id }
}
export def "select by tag" [name: string] {
let url = $in | get element url
let request = {
using:"tag name"
value:$name
}
let response = $request | to json | http post $"($url)/element" | get value
let element_id = $response | get ($response | columns | first)
{ session: $in.session, element: $element_id }
}
export def "select by link" [text: string] {
let url = $in | get element url
let request = {
using:"link text"
value:$text
}
let response = $request | to json | http post $"($url)/element" | get value
let element_id = $response | get ($response | columns | first)
{ session: $in.session, element: $element_id }
}
export def "select by partial link" [text: string] {
let url = $in | get element url
let request = {
using:"partial link text"
value:$text
}
let response = $request | to json | http post $"($url)/element" | get value
let element_id = $response | get ($response | columns | first)
{ session: $in.session, element: $element_id }
}
export def "select by id" [id: string] {
select by xpath $"//*[@id='($id)']"
}
export def "select by name" [name: string] {
select by xpath $"//*[@name='($name)']"
}
export def "select by type" [name: string] {
select by xpath $"//*[@type='($name)']"
}
#----------- Receive a session with element and return a session only
export def "set text" [value: string] {
$in | clear | add text $value
$in | reset element
}
export def "set checkbox" [value: bool] {
let ids = $in
let current = $ids | get property "checked"
if $value != $current { $ids | set clicked } else { $ids | reset element }
}
export def "set clicked" [] {
$in | click | reset element
}
export def "set selected" [value: string] {
$in | get children | where { ( $in | get property "value") == $value } | first | set clicked
}
export def "reset element" [] {
{ session: $in.session, element: "" }
}
#----------- Receive a session with element and return it
export def "add text" [value: string] {
let url = $in | get element url
for text in $value {
let request = {
type:"keyDown"
text:$text
}
$request | to json | http post $"($url)/value"
}
$in
}
export def "click at" [x: int, y: int, button = 1] {
let session = $in.session
let element = $in.element
let origin_elem = {
ELEMENT: ($element) ,
element-6066-11e4-a52e-4f735466cecf: ($element),
}
let origin = if element == "" { "pointer" } else { $origin_elem }
let request = {
actions: [
{
type: "pointer",
id: "mouse 01"
parameters: { pointerType: "mouse" },
actions: [
{
duration: 0,
x: $x,
y: $y,
type: "pointerMove",
origin: ($origin),
},
{ button: $button, type: "pointerDown" },
{ button: $button, type: "pointerUp" },
],
},
],
}
$request | to json | http post -f $"($session)/actions"
$in
}
export def "set file" [path: string] {
let url = $in | get element url
let request = {
text:$path
}
$request | to json | http post $"($url)/value"
$in
}
export def clear [] {
let url = $"($in.session)/element/($in.element)"
{} | to json| http post $"($url)/clear"
$in
}
export def click [] {
let url = $"($in.session)/element/($in.element)"
let request_up = {
type:"pointerUp"
duration:0
}
$request_up | to json| http post $"($url)/click"
$in
}
#----------- Receive a session and return a value
export def "get text" [] {
http get $"($in.session)/element/($in.element)/text" | get value
}
export def "get tag" [] {
http get $"($in.session)/element/($in.element)/name" | get value
}
export def "get html" [] {
http get $"($in)/source" | get value
}
export def "get title" [] {
http get $"($in.session)/title" | get value
}
export def "get window rect" [] {
http get $"($in.session)/window/rect" | get value
}
export def "get window handle" [] {
http get $"($in.session)/window/handle" | get value
}
export def "get window handles" [] {
http get $"($in.session)/window/handles" | get value
}
export def "get children" [] {
let session = $in.session
let response = $in | get property "children"
let element_ids = $response | get ($response | columns | first)
$element_ids | each {|id| {session: $session, element: $id}}
}
export def "get property" [name: string] {
let url = $"($in.session)/element/($in.element)"
http get $"($url)/property/($name)" | get value
}
export def "get attribute" [name: string] {
let url = $"($in.session)/element/($in.element)"
http get $"($url)/attribute/($name)" | get value
}
export def "get alert text" [] {
http get $"($in)/alert/text" | get value
}
export def "get screenshot" [] {
let session = if ($in | describe) == string {$in} else {$"($in.session)/element/($in.element)"}
http get $"($session)/screenshot" | get value | decode base64
}
export def "get all cookies" [] {
http get $"($in)/cookie" | get value
}
export def "get cookie" [name: string] {
http get $"($in)/cookie/($name)" | get value
}
#-----------setup browser and driver
def setup [ browser: string, driver: string ] {
let webdriver_setting = get setting $browser $driver
if $webdriver_setting.temp_driver_root != "" {
http get $webdriver_setting.urls.driver | save -f webdriver.zip
7z x webdriver.zip
rm webdriver.zip
}
if $webdriver_setting.temp_browser_root != "" {
http get $webdriver_setting.urls.browser | save -f browser.zip
7z x browser.zip
rm browser.zip
}
$webdriver_setting
}
def "start session" [args: list<string>] {
let webdriver_setting = $in
let port = port
let job_id = job spawn { run-external $webdriver_setting.driver_path $"--port=($port)" }
job tag $job_id $"webdriver port ($port)"
let browser_options = {
$webdriver_setting.options_name: { args: $args, binary: $webdriver_setting.browser_path }
}
let capabilities = {capabilities:{alwaysMatch:($browser_options)}}
let connection = ($capabilities | to json | http post $"http://localhost:($port)/session")
let session_id = $connection.value.sessionId
let session = $"http://localhost:($port)/session/($session_id)"
{ job_id: $job_id, session: $session, setting: $webdriver_setting }
}
def cleanup [] {
sleep 1sec
let setting = $in.setting
if $setting.temp_driver_root != "" { rm -r $setting.temp_driver_root }
if $setting.temp_browser_root != "" { rm -r ( $setting.temp_browser_root ) }
}
def "get setting" [ browser: string, driver: string ] {
let browser_name_list = ["chrome", "firefox", "edge"]
| where {|x| $browser | str contains $x }
let machine = uname | get machine
let target = uname | get kernel-name | match $in {
"Windows_NT" => { match $machine {"i686" => "win32", "x86_64" => "win64", _ => "arm64" } },
"Linux" => { if $machine == "i686" { "linux32" } else {"linux64"} },
"Darwin" => { if $machine == "arm64" { "mac-arm64" } else {"mac-x64"} },
}
if ( $browser_name_list | is-not-empty ) {
let browser_name = $browser_name_list | get 0
let browser_paths = if ( which $browser | is-empty ) {
make brawser paths $browser_name $target
} else {
if ( ["chrome", "firefox"] | any { $in == $browser_name } ) {
{ browser_path: ( which $browser | get path.0 ), temp_browser_root:"" }
} else {
{ browser_path: "", temp_browser_root:"" }
}
}
let driver_paths = if ( which $driver | is-empty ) {
make driver paths $browser_name $target
} else {
{ driver_path: ( which $driver | get path.0 ), temp_driver_root:"" }
}
{
options_name: ( get option name $browser_name ),
urls: (get urls $browser_name $target $machine),
driver_path: $driver_paths.driver_path,
temp_driver_root: $driver_paths.temp_driver_root,
browser_path: $browser_paths.browser_path,
temp_browser_root: $browser_paths.temp_browser_root,
}
} else {
{
options_name: "",
urls: "",
driver_path: $driver,
temp_driver_root: "",
browser_path: $browser,
temp_browser_root: "",
}
}
}
def "make brawser paths" [browser_name: string, target: string] {
let expand = if ( $target | str starts-with 'win' ) { '.exe' } else { '' }
let browser_path = {
"firefox": ([(pwd), $"firefox", $"firefox($expand)"] | path join),
"chrome": ([(pwd), $"chrome-($target)", $"chrome($expand)"] | path join),
}
let temp_browser_root = {
"firefox": ( $browser_path."firefox" | path dirname ),
"chrome": ( $browser_path."chrome" | path dirname ),
}
{
browser_path: ( $browser_path | get $browser_name ),
temp_browser_root: ( $temp_browser_root | get $browser_name ),
}
}
def "make driver paths" [browser_name: string, target: string] {
let expand = if ( $target | str starts-with 'win' ) { '.exe' } else { '' }
let driver_path = {
"firefox": ([(pwd), $"geckodriver($expand)" ] | path join),
"chrome": ([(pwd), $"chromedriver-($target)", $"chromedriver($expand)" ] | path join),
}
let temp_driver_root = {
"firefox": $driver_path."firefox",
"chrome": ( $driver_path."chrome" | path dirname ),
}
{
driver_path: ( $driver_path | get $browser_name ),
temp_driver_root: ( $temp_driver_root | get $browser_name ),
}
}
def "get option name" [browser_name: string] {
let browser_options_name = {
"firefox": "moz:firefoxOptions",
"chrome": "goog:chromeOptions",
"edge": "ms:edgeOptions",
}
$browser_options_name | get $browser_name
}
def "get urls" [ browser_name: string, target: string, machine: string ] {
match $browser_name {
"chrome" => (make chrome urls $target),
"firefox" => (make firefox urls $target $machine),
}
}
def "make chrome urls" [target: string] {
let version = http get https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json
| get channels | get Stable | get version | into string
let dl_driver = $"https://storage.googleapis.com/chrome-for-testing-public/($version)/($target)/chromedriver-($target).zip"
let dl_browser = $"https://storage.googleapis.com/chrome-for-testing-public/($version)/($target)/chrome-($target).zip"
{ driver: $dl_driver, browser: $dl_browser }
}
def "make firefox urls" [target: string, machine: string] {
let versions = http get https://raw.githubusercontent.com/SeleniumHQ/selenium/trunk/common/geckodriver/geckodriver-support.json
| get geckodriver-releases.0
let version = $versions.min-firefox-version
let dl_driver = http get https://raw.githubusercontent.com/bonigarcia/webdrivermanager/master/docs/mirror/geckodriver
| from json | where tag_name == $"v($versions.geckodriver-version)"
| get assets.0.browser_download_url
| where { str contains $target } | get 0
let browser_ftp_base = $"https://ftp.mozilla.org/pub/firefox/candidates/($version).0esr-candidates/build1/"
let file_name_base = $"firefox-($version).0esr"
let dl_browser = match $target {
"win32" | "win64" => $"($browser_ftp_base)($target)/ja/($file_name_base).zip",
"linux32" | "linux64" => $"($browser_ftp_base)linux-($machine)/ja/($file_name_base).tar.bz2",
"mac-x64" => $"($browser_ftp_base)mac/ja/($file_name_base).dmg",
}
{ driver: $dl_driver, browser: $dl_browser }
}
def "get element url" [] {
if ( $in.element == "" ) {
$in.session
} else {
$"($in.session)/element/($in.element)"
}
}
# webdriverを使ってchrome経由でYahoo Finance APIを叩くデモです。
# Yahoo Finance APIは現状どういうわけかChrome等のクライアントを使わないと弾かれるのでWebDriverを使う合理性があります。
# 一部コードは https://ranaroussi.github.io/yfinance/ から拝借しています。
def main [symbol = "NQ=F"] {
use webdriver.nu
let start = (date now) - 100day
let end = date now
{ get info $symbol | to json | save $"information_($symbol).json" } | webdriver run ["--headless"]
{ get history $symbol $start $end | to json | save $"history_($symbol).json" }
| webdriver run ["--headless"]
get timeseries $symbol | save $"timeseries_($symbol).json"
}
def "get crumb" [] {
use webdriver.nu
let session = $in
$session | webdriver go https://query2.finance.yahoo.com/v1/test/getcrumb
let crumb = $session | webdriver select by tag pre | webdriver get text
$crumb
}
def "get result" [] {
use webdriver.nu
let session = $in
let result = $session | webdriver select by tag pre | webdriver get text | from json
$result
}
# intervalが取り得る値は 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo です。
# ただし 30m は何故かAPI側がバグってて 60m が返って来るようです。
export def "get history" [symbol: string, start: datetime, end: datetime, interval = "1d"] {
use webdriver.nu
let session = $in
let crumb = $session | get crumb
let st = $start | into int
let ed = $end | into int
let events = "div,splits,capitalGains"
let params = {period1: $st, period2: $ed, interval: $interval, includePrePost: False, events: $events, symbol: ($symbol) , crumb: ($crumb)}
let query = $params | url build-query
$session | webdriver go $"https://query2.finance.yahoo.com/v8/finance/chart/($symbol)?($query)"
$session | get result
}
export def "get info" [symbol: string] {
use webdriver.nu
let session = $in
let crumb = $session | get crumb
let modules = ['financialData', 'quoteType', 'defaultKeyStatistics', 'assetProfile', 'summaryDetail']
let params = { modules: ($modules | str join ','), corsDomain: 'finance.yahoo.com', formatted: false, symbol: ($symbol), crumb: ($crumb)}
let query = $params | url build-query
$session | webdriver go $"https://query2.finance.yahoo.com/v10/finance/quoteSummary/($symbol)?($query)"
$session | get result
}
# timescaleが取り得る値は annual,quarterly, trailing です。
export def "get timeseries" [symbol: string, name = 'financials', timescale = 'quarterly'] {
let keys = {
'financials': ["TaxEffectOfUnusualItems", "TaxRateForCalcs", "NormalizedEBITDA", "NormalizedDilutedEPS",
"NormalizedBasicEPS", "TotalUnusualItems", "TotalUnusualItemsExcludingGoodwill",
"NetIncomeFromContinuingOperationNetMinorityInterest", "ReconciledDepreciation",
"ReconciledCostOfRevenue", "EBITDA", "EBIT", "NetInterestIncome", "InterestExpense",
"InterestIncome", "ContinuingAndDiscontinuedDilutedEPS", "ContinuingAndDiscontinuedBasicEPS",
"NormalizedIncome", "NetIncomeFromContinuingAndDiscontinuedOperation", "TotalExpenses",
"RentExpenseSupplemental", "ReportedNormalizedDilutedEPS", "ReportedNormalizedBasicEPS",
"TotalOperatingIncomeAsReported", "DividendPerShare", "DilutedAverageShares", "BasicAverageShares",
"DilutedEPS", "DilutedEPSOtherGainsLosses", "TaxLossCarryforwardDilutedEPS",
"DilutedAccountingChange", "DilutedExtraordinary", "DilutedDiscontinuousOperations",
"DilutedContinuousOperations", "BasicEPS", "BasicEPSOtherGainsLosses", "TaxLossCarryforwardBasicEPS",
"BasicAccountingChange", "BasicExtraordinary", "BasicDiscontinuousOperations",
"BasicContinuousOperations", "DilutedNIAvailtoComStockholders", "AverageDilutionEarnings",
"NetIncomeCommonStockholders", "OtherunderPreferredStockDividend", "PreferredStockDividends",
"NetIncome", "MinorityInterests", "NetIncomeIncludingNoncontrollingInterests",
"NetIncomeFromTaxLossCarryforward", "NetIncomeExtraordinary", "NetIncomeDiscontinuousOperations",
"NetIncomeContinuousOperations", "EarningsFromEquityInterestNetOfTax", "TaxProvision",
"PretaxIncome", "OtherIncomeExpense", "OtherNonOperatingIncomeExpenses", "SpecialIncomeCharges",
"GainOnSaleOfPPE", "GainOnSaleOfBusiness", "OtherSpecialCharges", "WriteOff",
"ImpairmentOfCapitalAssets", "RestructuringAndMergernAcquisition", "SecuritiesAmortization",
"EarningsFromEquityInterest", "GainOnSaleOfSecurity", "NetNonOperatingInterestIncomeExpense",
"TotalOtherFinanceCost", "InterestExpenseNonOperating", "InterestIncomeNonOperating",
"OperatingIncome", "OperatingExpense", "OtherOperatingExpenses", "OtherTaxes",
"ProvisionForDoubtfulAccounts", "DepreciationAmortizationDepletionIncomeStatement",
"DepletionIncomeStatement", "DepreciationAndAmortizationInIncomeStatement", "Amortization",
"AmortizationOfIntangiblesIncomeStatement", "DepreciationIncomeStatement", "ResearchAndDevelopment",
"SellingGeneralAndAdministration", "SellingAndMarketingExpense", "GeneralAndAdministrativeExpense",
"OtherGandA", "InsuranceAndClaims", "RentAndLandingFees", "SalariesAndWages", "GrossProfit",
"CostOfRevenue", "TotalRevenue", "ExciseTaxes", "OperatingRevenue", "LossAdjustmentExpense",
"NetPolicyholderBenefitsAndClaims", "PolicyholderBenefitsGross", "PolicyholderBenefitsCeded",
"OccupancyAndEquipment", "ProfessionalExpenseAndContractServicesExpense", "OtherNonInterestExpense"],
'balance-sheet': ["TreasurySharesNumber", "PreferredSharesNumber", "OrdinarySharesNumber", "ShareIssued", "NetDebt",
"TotalDebt", "TangibleBookValue", "InvestedCapital", "WorkingCapital", "NetTangibleAssets",
"CapitalLeaseObligations", "CommonStockEquity", "PreferredStockEquity", "TotalCapitalization",
"TotalEquityGrossMinorityInterest", "MinorityInterest", "StockholdersEquity",
"OtherEquityInterest", "GainsLossesNotAffectingRetainedEarnings", "OtherEquityAdjustments",
"FixedAssetsRevaluationReserve", "ForeignCurrencyTranslationAdjustments",
"MinimumPensionLiabilities", "UnrealizedGainLoss", "TreasuryStock", "RetainedEarnings",
"AdditionalPaidInCapital", "CapitalStock", "OtherCapitalStock", "CommonStock", "PreferredStock",
"TotalPartnershipCapital", "GeneralPartnershipCapital", "LimitedPartnershipCapital",
"TotalLiabilitiesNetMinorityInterest", "TotalNonCurrentLiabilitiesNetMinorityInterest",
"OtherNonCurrentLiabilities", "LiabilitiesHeldforSaleNonCurrent", "RestrictedCommonStock",
"PreferredSecuritiesOutsideStockEquity", "DerivativeProductLiabilities", "EmployeeBenefits",
"NonCurrentPensionAndOtherPostretirementBenefitPlans", "NonCurrentAccruedExpenses",
"DuetoRelatedPartiesNonCurrent", "TradeandOtherPayablesNonCurrent",
"NonCurrentDeferredLiabilities", "NonCurrentDeferredRevenue",
"NonCurrentDeferredTaxesLiabilities", "LongTermDebtAndCapitalLeaseObligation",
"LongTermCapitalLeaseObligation", "LongTermDebt", "LongTermProvisions", "CurrentLiabilities",
"OtherCurrentLiabilities", "CurrentDeferredLiabilities", "CurrentDeferredRevenue",
"CurrentDeferredTaxesLiabilities", "CurrentDebtAndCapitalLeaseObligation",
"CurrentCapitalLeaseObligation", "CurrentDebt", "OtherCurrentBorrowings", "LineOfCredit",
"CommercialPaper", "CurrentNotesPayable", "PensionandOtherPostRetirementBenefitPlansCurrent",
"CurrentProvisions", "PayablesAndAccruedExpenses", "CurrentAccruedExpenses", "InterestPayable",
"Payables", "OtherPayable", "DuetoRelatedPartiesCurrent", "DividendsPayable", "TotalTaxPayable",
"IncomeTaxPayable", "AccountsPayable", "TotalAssets", "TotalNonCurrentAssets",
"OtherNonCurrentAssets", "DefinedPensionBenefit", "NonCurrentPrepaidAssets",
"NonCurrentDeferredAssets", "NonCurrentDeferredTaxesAssets", "DuefromRelatedPartiesNonCurrent",
"NonCurrentNoteReceivables", "NonCurrentAccountsReceivable", "FinancialAssets",
"InvestmentsAndAdvances", "OtherInvestments", "InvestmentinFinancialAssets",
"HeldToMaturitySecurities", "AvailableForSaleSecurities",
"FinancialAssetsDesignatedasFairValueThroughProfitorLossTotal", "TradingSecurities",
"LongTermEquityInvestment", "InvestmentsinJointVenturesatCost",
"InvestmentsInOtherVenturesUnderEquityMethod", "InvestmentsinAssociatesatCost",
"InvestmentsinSubsidiariesatCost", "InvestmentProperties", "GoodwillAndOtherIntangibleAssets",
"OtherIntangibleAssets", "Goodwill", "NetPPE", "AccumulatedDepreciation", "GrossPPE", "Leases",
"ConstructionInProgress", "OtherProperties", "MachineryFurnitureEquipment",
"BuildingsAndImprovements", "LandAndImprovements", "Properties", "CurrentAssets",
"OtherCurrentAssets", "HedgingAssetsCurrent", "AssetsHeldForSaleCurrent", "CurrentDeferredAssets",
"CurrentDeferredTaxesAssets", "RestrictedCash", "PrepaidAssets", "Inventory",
"InventoriesAdjustmentsAllowances", "OtherInventories", "FinishedGoods", "WorkInProcess",
"RawMaterials", "Receivables", "ReceivablesAdjustmentsAllowances", "OtherReceivables",
"DuefromRelatedPartiesCurrent", "TaxesReceivable", "AccruedInterestReceivable", "NotesReceivable",
"LoansReceivable", "AccountsReceivable", "AllowanceForDoubtfulAccountsReceivable",
"GrossAccountsReceivable", "CashCashEquivalentsAndShortTermInvestments",
"OtherShortTermInvestments", "CashAndCashEquivalents", "CashEquivalents", "CashFinancial",
"CashCashEquivalentsAndFederalFundsSold"],
'cash-flow': ["ForeignSales", "DomesticSales", "AdjustedGeographySegmentData", "FreeCashFlow",
"RepurchaseOfCapitalStock", "RepaymentOfDebt", "IssuanceOfDebt", "IssuanceOfCapitalStock",
"CapitalExpenditure", "InterestPaidSupplementalData", "IncomeTaxPaidSupplementalData",
"EndCashPosition", "OtherCashAdjustmentOutsideChangeinCash", "BeginningCashPosition",
"EffectOfExchangeRateChanges", "ChangesInCash", "OtherCashAdjustmentInsideChangeinCash",
"CashFlowFromDiscontinuedOperation", "FinancingCashFlow", "CashFromDiscontinuedFinancingActivities",
"CashFlowFromContinuingFinancingActivities", "NetOtherFinancingCharges", "InterestPaidCFF",
"ProceedsFromStockOptionExercised", "CashDividendsPaid", "PreferredStockDividendPaid",
"CommonStockDividendPaid", "NetPreferredStockIssuance", "PreferredStockPayments",
"PreferredStockIssuance", "NetCommonStockIssuance", "CommonStockPayments", "CommonStockIssuance",
"NetIssuancePaymentsOfDebt", "NetShortTermDebtIssuance", "ShortTermDebtPayments",
"ShortTermDebtIssuance", "NetLongTermDebtIssuance", "LongTermDebtPayments", "LongTermDebtIssuance",
"InvestingCashFlow", "CashFromDiscontinuedInvestingActivities",
"CashFlowFromContinuingInvestingActivities", "NetOtherInvestingChanges", "InterestReceivedCFI",
"DividendsReceivedCFI", "NetInvestmentPurchaseAndSale", "SaleOfInvestment", "PurchaseOfInvestment",
"NetInvestmentPropertiesPurchaseAndSale", "SaleOfInvestmentProperties",
"PurchaseOfInvestmentProperties", "NetBusinessPurchaseAndSale", "SaleOfBusiness",
"PurchaseOfBusiness", "NetIntangiblesPurchaseAndSale", "SaleOfIntangibles", "PurchaseOfIntangibles",
"NetPPEPurchaseAndSale", "SaleOfPPE", "PurchaseOfPPE", "CapitalExpenditureReported",
"OperatingCashFlow", "CashFromDiscontinuedOperatingActivities",
"CashFlowFromContinuingOperatingActivities", "TaxesRefundPaid", "InterestReceivedCFO",
"InterestPaidCFO", "DividendReceivedCFO", "DividendPaidCFO", "ChangeInWorkingCapital",
"ChangeInOtherWorkingCapital", "ChangeInOtherCurrentLiabilities", "ChangeInOtherCurrentAssets",
"ChangeInPayablesAndAccruedExpense", "ChangeInAccruedExpense", "ChangeInInterestPayable",
"ChangeInPayable", "ChangeInDividendPayable", "ChangeInAccountPayable", "ChangeInTaxPayable",
"ChangeInIncomeTaxPayable", "ChangeInPrepaidAssets", "ChangeInInventory", "ChangeInReceivables",
"ChangesInAccountReceivables", "OtherNonCashItems", "ExcessTaxBenefitFromStockBasedCompensation",
"StockBasedCompensation", "UnrealizedGainLossOnInvestmentSecurities", "ProvisionandWriteOffofAssets",
"AssetImpairmentCharge", "AmortizationOfSecurities", "DeferredTax", "DeferredIncomeTax",
"DepreciationAmortizationDepletion", "Depletion", "DepreciationAndAmortization",
"AmortizationCashFlow", "AmortizationOfIntangibles", "Depreciation", "OperatingGainsLosses",
"PensionAndEmployeeBenefitExpense", "EarningsLossesFromEquityInvestments",
"GainLossOnInvestmentSecurities", "NetForeignCurrencyExchangeGainLoss", "GainLossOnSaleOfPPE",
"GainLossOnSaleOfBusiness", "NetIncomeFromContinuingOperations",
"CashFlowsfromusedinOperatingActivitiesDirect", "TaxesRefundPaidDirect", "InterestReceivedDirect",
"InterestPaidDirect", "DividendsReceivedDirect", "DividendsPaidDirect", "ClassesofCashPayments",
"OtherCashPaymentsfromOperatingActivities", "PaymentsonBehalfofEmployees",
"PaymentstoSuppliersforGoodsandServices", "ClassesofCashReceiptsfromOperatingActivities",
"OtherCashReceiptsfromOperatingActivities", "ReceiptsfromGovernmentGrants", "ReceiptsfromCustomers"]
}
let coefficient = 1000000000
let start = 2016-12-31 | into int | $in // $coefficient
let end = date now | into int | $in // $coefficient
let types = ($keys | get $name | each {|s| $"($timescale)($s)"} | str join ',')
let params = { type: ($types), period1: ($start), period2: ($end), symbol: ($symbol)}
let query = $params | url build-query
let result = http get $"https://query2.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/($symbol)?($query)"
$result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment