How to call the closing price of other stocks in Pine Script? - trading

I want to include in the indicator code the closing prices of several different stocks in a comparison, but I don't know how to refer to the closing prices of these other stocks. what function would allow me to do that?

The function you are looking for is called security. Here is the reference.
For an example:
If you want to retrieve the close price of BTC/USD on biance you use the security function like
btc_close = nz(security("binance:BTCUSDT", timeframe.period, close))
The function nz replaces NaN values with zeros.

Related

GOOGLEFINANCE Formulas in arrays for Google Sheets

I have a product with In-App Purchases in several markets in which transactions happen in their local currency. Created a Google Sheet for the purpose of reporting revenues in our base currency (USD). I tried several things to create the most effective method to automatically read the currency pair for each transaction, but the formula isn't working.
I am attempting to accomplish 3 things here:
Create an array that will automatically convert different currencies to USD by using the GOOGLEFINANCE formula (see "G1" on the embedded spreadsheet).
Eliminating error when conversion finds a value having the same ISO codes (see "F12" on the embedded spreadsheet).
Calculating the transaction using the exchange rate of the day of the transaction instead of TODAY's exchange rate (no clue on how to do this without breaking the GOOGLEFINANCE formula).
Here is the formula I am using on Col "G" is:
={"CONVERSION ARRAY";ARRAYFORMULA(E2:E*GOOGLEFINANCE("CURRENCY:"&D2:D))}
The problem with this approach is that it replicates the value of cell "D2" down the whole array, instead of consecutive values from D2,3,4, etc, accordingly. Removing the "&" from the array breaks the formula.
While the formula used on Col "F" =E2*GOOGLEFINANCE("CURRENCY:"&D2) works, the problem here is that it has to be placed manually, row by row, and this is inefficient when dealing with thousands of records. Also, you will notice on cel F12, I get an invalid value because GoogleFinance cannot convert from dollars to dollars. The formula outputs an error. Is there a way to make the formula understand that when trying to convert a value with the same currency ISO's, the value stays the same?
Even while I get the correct calculation on approach #2, the data calculated is based on TODAY's exchange rate, however, I need that calculation based on the exchange rate of the same date of the transaction. Is this even possible?
The referred spreadsheet example is here: Google Finances Conversion Formula
GOOGLEFINANCE is not supported under ARRAYFORMULA
if your D2:D range is small you can do:
={"CONVERSION ARRAY";ARRAYFORMULA(E2:E5*{
GOOGLEFINANCE("CURRENCY:"&D2);
GOOGLEFINANCE("CURRENCY:"&D3);
GOOGLEFINANCE("CURRENCY:"&D4);
GOOGLEFINANCE("CURRENCY:"&D5)})}

How to calculate currency conversion for ZARCAD for a specific date with GOOGLEFINANCE?

I have a Google sheet that I use multiple currencies in. I purchase a product on a specific date and I want to lock in the conversion for that date. However, I have not been able to do that with all the different formulas that I have tried. I keep getting an error. Here is the formula that I am using.
=J283*GOOGLEFINANCE("ZARCAD","price",date(2021,4,9),date(2021,4,11))
Column J is the column with the price in the currency of purchase. I need to convert it into Canadian dollars. It works if I want the current price of the currency, but not for the historical data.
The error is:
Error
Function MULTIPLY parameter 2 expects number values. But 'Date' is a text and cannot be coerced to a number.
How can I fix this issue?
The formula you are using creates a 2D array as below:
In order to be able to use a function that expects number values (like MULTIPLY), you have to index a part of the 2D array that is a number.
For example, to multiply the first "Close" value of 0.08575243, you have to tell the fomula to use that value for the calculation with the built-in INDEX function:
=INDEX(GOOGLEFINANCE("ZARCAD","price",date(2021,4,9),date(2021,4,11)),2,2)
If you wish to specify a different part of the array, just change the 2,2 (row, column) at the end to any numbers that point to the value in the array that you wish to use. Here, you can find the documentation for INDEX.

Dynamic Currency Conversion in Google Sheets

I'm using Google Sheets to organize data from my global royalty statements. Currently I'm querying several tabs (one for each country) to produce a single table with results from all countries. As you can imagine, I don't want 125 Japanese Yen showing up in my charts and graphs as $125 USD (125 Y is equivalent to about $1.09 USD).
Since I receive my royalty statements in their respective currencies, I'd like to apply average conversion rates either during the query operation or after the fact. Since the table is being generated dynamically, the values won't always be the same, so I need some way to apply the conversion by searching the list of currencies on the fly. I've got a separate table on the same tab containing all the average conversion rates for each currency. Here's a sample of how this is set up:
So basically I just don't know how to say, in coding terms, "If this line item comes from the UK, divide the royalty amount by the UK exchange rate. If it comes from Canada, divide by the Canadian rate, etc."
Anyone have any insight as to how I might pull this off (or whether it's possible)? The actual table includes over 500 line items from a dozen different countries, so doing this by hand is something I'd like to avoid.
I believe you are looking for the GoogleFinance() function. You may want to set the Country to a pick list of the valid country entries so you could create the string for the conversion. I have not looked at many, but this will take a value in CA & and apply the exchange rate to convert it to the US $ Equivalent. The exchange rate in this case is an average of, I believe, the past 30 days.
=C2 * GoogleFinance("CURRENCY:CADUSD" , "average")
For your use, you can get the country code from row M if you change it to match what the formula is after, such as CAD for Canadian Dollars."
=C2 * GoogleFinance("CURRENCY:" & M2 & "USD" , "average")
Another option would be to create a lookup table and use VLOOKUP or some other function, depending on how you set up your table.

On Google Spreadsheet how can you query 'GoogleFinance' for a past exchange rate?

I'd like to know if it is possible to query a past exchange rate on Google Spreadsheet.
For example; using formula =GoogleFinance("CURRENCY:USDEUR") will return the USD/EUR rate at this present moment. How can you retrieve a historic rate?
In order to retrieve the historical rate, you have to use the following formula:
=GoogleFinance("eurusd","price",today()-1,today())
where today()-1, today() is the desired time interval, which can be explicitly defined as the static pair of dates, or implicitly, as the dynamically calculated values, like in the example above. This expression returns a two-column array of the dates and close values. It is important to care about the suitable cell format (date/number), otherwise your data will be broken.
If you want to get the pure row with the date and currency exchange rate without column headers, wrap your formula with the INDEX() function:
=INDEX(GoogleFinance("eurusd","price",today()-1,today()),2,)
To retrieve the exchange rate value only, define the column number parameter:
=INDEX(GoogleFinance("eurusd","price",today()-1,today()),2,2)
To get today's currency exchange rates in Google Docs/Spreadsheet from Google Finance:
=GoogleFinance("eurusd","price",today())
A shorter way to get today's rates:
=GoogleFinance("currency:usdeur")
P.S. There is also the way to get live currency exchange rate in Microsoft Excel.
Try,
=GoogleFinance("usdeur","price",date(2013,12,1),date(2013,12,16))
Make sure that the dates are as per your spreadsheet settings.
Edit as comment, changed date for capturing single day data:-
Only with headers:
=INDEX(GoogleFinance("usdeur","price",date(2013,12,3),date(2013,12,4)),,2)
without headers:
=FILTER(INDEX(GoogleFinance("usdeur","price",date(2013,12,3),date(2013,12,4)),,2),INDEX(GoogleFinance("usdeur","price",date(2013,12,3),date(2013,12,4)),,2)<>"Close")
The instructions for all related to googlefinance are in here: https://support.google.com/docs/answer/3093281
Remember the actual Google Spreadsheets Formulas use semicolon (;) instead of comma (,).
Once made the replacement on some examples would look like this:
For a 30 day INDEX of USD vs EUR you should use (note that in the case of currencies they go together in the same first variable):
=INDEX(GoogleFinance(USDEUR;"price";today()-30;today());2;2)
TIP: You can get the graph over the entire size of the cell by simply changing INDEX for SPARKLINE, like this:
=SPARKLINE(GoogleFinance(USDEUR;"price";today()-30;today());2;2)
Vasim's answer is excellent, however notice if you want the exchange date on that day only, you can omit the range and just specify the day such as the following
=FILTER(INDEX(GoogleFinance("usdeur","price",today()),,2),INDEX(GoogleFinance("usdeur","price",today()),,2)<>"Close")
You may notice that GOOGLEFINANCE will return N/A for some dates, this is because the date is a day off (usually a weekend), what you can do is to get the last working from the specified date, e.g. Jun 21st 2015 is Sunday, so you should request the rate for Jun 19th (Friday), you can do this via WORKDAY function as was suggested here:
WORKDAY("6/21/2015"+1,-1)
So, the resulting formula will look something like that:
INDEX(GoogleFinance("CURRENCY:USDRUB", "price", WORKDAY("6/21/2015"+1,-1),1),2,2)
Additionally, you want to get the exchange rates for future dates you can additionally check if the date is in the future and if so, just use the today date:
WORKDAY(IF("6/21/2099">TODAY(),TODAY(),"6/21/2099")+1,-1)
For bigger spreadsheets, Google Sheets limitations usually will show randomly the following error:
Error Function INDEX parameter 2 value is 2. Valid values are between
0 and 1 inclusive.
Even modifying Index() and GoogleFinance() following the expected parameters GOOGLEFINANCE(ticker, [attribute], [start_date], [end_date|num_days], [interval]) the error will continue.
A workaround is to copy smaller parts into new spreadsheets but often it will fail.
As an alternative, I used ImportXML as web scraper for x-rates historical currency exchange data.
=index(IMPORTXML("https://www.x-rates.com/historical/?from="&N2&"&amount="&K2&"&date="&YEAR(B2)&"-"&TEXT(B2,"mm")&"-"&TEXT(B2,"dd")&"","//td[#class='rtRates']"),1)
I'm assuming column B are dates, K is for amounts and N for currencies.
Randomly it also will fail for a 2000+ rows spreadsheet but overall for my requirement, it worked too much better than GoogleFinance()
ImportXML examples
The ImportXML Guide for Google Docs from beginner to advanced
Other option is using the CurrencyConverter function from this Google Sheets add-on.
It is fast and and has simple syntax. For example,
=CurrencyConverter(100, "USD", "EUR", "2/28/2020")
returns 91.09957183

Google Spreadsheet: Query String and Numeric (Involving math formula)

Sorry about the imprecise title. Allow me to elaborate. I'm currently in the process of making 'Order' sheets for the small retailer i work for. Some items are easy to count due to low inventory while other items are abundant and difficult to count but easy to gauge whether we ought to order them.
When an employee takes a store count, the on-hand number they put down is contrasted with a minimum. The minimum is our lower threshold. The minimum is subtracted by the input quantity and a formula produces a third column, "Order". If the number in the order column is < 0 then a query function on a separate sheet will copy the entire row. To be clear, there are three columns, "On Hand", "Minimum", "Order", with the "Order" column containing the following mathematical formula:
="Minimum" - "On Hand"
[Cells are specified so that it would look more like "=B2-A2".]
However, I'd also like to include the ability for employees to put a simple 'x' in the count spot, signifying that we need to order the product without having to count every single instance of the item. I'd still like to include the ability for them to enter a number if they so choose. I'd like for them to be able either the number or the 'x' in the same column. I'm currently using the following query function:
=QUERY('String(Fail)'!A:D;"select * where A contains 'x' or C > 0")
[The above is from a sheet I'm experimenting with. I will provide a link below in case you're more hands-on.]
The issue arises when the formula in the "order" column outputs any sort of number. If the formula is functional, no row marked with an 'x' is copied to the new page via the query command. If any row produces a numeric, no 'x' rows are copied over at all. I've experimented a bit but am at a loss as to where to go next.
The sheet I'm currently experimenting with is linked below. If you'd like any additional information I'd be happy to provide it. I'm relatively new to all of this so excuse my stupidity. I do recognize that I could very likely make a script for this but am not well versed in scripting with Google Apps and enjoy the immediate benefits of the query function.
Any help is welcome. Thank you.
Experimental Spreadsheet
All the values in a column need to be of the same type in order to be evaluated by QUERY. The mix of 'x' and numbers is confusing things.
If you use the Format menu to ensure all the values in column A are Plain Text, then your Query will work. (Formatting a numeric value as plain text does not stop it from working in a numeric calculation, so your column C survives.) Here's a screenshot of your query, after doing that formatting:
Based on your specification, your query needs to have the comparison to zero reversed, like this:
=QUERY('String(Fail)'!A:D;"select * where A contains 'x' or C < 0")
^^^

Resources