Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

08/11/2024

[Google Sheets] Import data from Investing.com

DISCLAIMER: This is not a stock picking recommendation, the tickers shown are used as example and not provided as financial or investment advice.

DISCLAIMER2: Web scraping can go against usage policies so read them, understand them and abide by them. Also web scraping is notoriously flaky as small changes in the retrieved page can affect the location of the desired element(s).

We have already seen how to import data from Yahoo Finance and Coingecko, now we try to add Investing.com as source which unfortunately does not provide API, so we have to do some HTML scraping instead.

We would like to retrieve the current price of an ETF called JPNA. By looking at that page we can luckily identify a specific locator, which then allows us to do a couple string manipulation operations before getting the desired value:

function getInvestingData(path) {
  var result = UrlFetchApp.fetch("https://www.investing.com/etfs/" + path.toLowerCase());
  var response = result.getContentText();
  var start = response.indexOf(' data-test="instrument-price-last">') + 35;
  var end = response.indexOf('</div>', start)
  var out = response.substring(start, end);
  var strip = out.replace(",", "");
  return Number(strip);
}

19/10/2024

[Google Sheets] Import crypto data from Coingecko

DISCLAIMER: I do not recommend investing in crypto, all tokens you will see are used as sample and not provided as financial or investment advice.

We've already seen how to add custom functions to our Google Sheets projects, importing Yahoo Finance data. Now we expand this to import cryptocurrency data from Coingecko.

I could have picked any of the million sources, but this one has a simple free plan which for light usage works well.

After registering and getting your API key, RTFM to find that they provide a lot of stuff, what we care about is the pricing data in this example, you will need to find the ID of the currency you want (NOT the token) by querying the list and then you can get the data you want by calling (add your API key at the end):

"https://api.coingecko.com/api/v3/simple/price?ids=" + token + "&vs_currencies=usd&x_cg_demo_api_key="

You can put this in a Google Sheet function as well (you can extend input parameters to get quote in different currencies as well):

function getCoingeckoData(path) {
  var result = UrlFetchApp.fetch("https://api.coingecko.com/api/v3/simple/price?ids=" + path + "&vs_currencies=usd&x_cg_demo_api_key=YOUR_API_KEY");
  var response = result.getContentText();
  var json = JSON.parse(response);
  return json[path]['usd'];
}

22/12/2023

[Google Sheets] Import data from Yahoo Finance

DISCLAIMER: This is not a stock picking recommendation, the tickers shown are used as example and not provided as financial or investment advice.

Google Sheets offers the GOOGLEFINANCE function which can be used to import market data.

Usage is simple, for example to get the price of a stock, first search for it on Google Finance, then look at the quote URL it generates and copy the exchange:ticker value into the function.

In this example we try to get the quote for A200 ETF traded on the Australian ASX exchange. The URL shows ASX:A200 after the quote part, therefore we should use:

=GOOGLEFINANCE("ASX:A200")

So far, so good. Sometimes however Google does not show data for a particular ticker, or it shows data only in another currency or from another exchange. 
For example, another ETF XESC shows quotes from many exchanges but is also traded on the German XETRA (XESC.DE), which is not sourced by Google. Or the CHSPI ETF traded on the Swiss Six exchange (CHSPI.SW) is simply not found at all.

06/11/2023

[Tampermonkey] Disable Bing Chat search integrations

When using Bing search there are multiple places that integrate the Chat functionality with the ChatGPT AI. Some of these integrations are annoying and can be easily disabled by installing the Tampermonkey browser extension then adding a couple scripts to modify the displayed webpage and its behavior.

 // ==UserScript==  
 // @name    Disable Bing Search Engine Scroll  
 // @namespace  your-namespace  
 // @description Disables scrolling on the Bing search engine page to prevent accidental scrolling into the Bing chat feature.  
 // @match   https://www.bing.com/*  
 // @version   1  
 // @grant    none  
 // ==/UserScript==  
   
 window.addEventListener("wheel", e=>{  
 if(e.target.className.includes("cib-serp-main")) e.stopPropagation();  
 });  

  • Disable sidebar Chat autosearch functionality when disaplying search results:
 // ==UserScript==  
 // @name    Disable Bing Chat autosearch  
 // @namespace  your-namespace  
 // @description Disables the Bing Chat autosearch functionality on the right side of results when doing a search.  
 // @match   https://www.bing.com/*  
 // @version   1  
 // @grant    none  
 // ==/UserScript==  
   
 const element = document.getElementById("sydwrap_wrapper");  
 element.remove();  
 const element1 = document.getElementById("b_sydTigerCont");
 element1.remove();

Remember that of course these scripts might stop working one day if Microsoft decides to change something on their side, when that happens they will simply need to be updated.

29/11/2014

[TIBCO Spotfire] Run script at startup from a Web Player mashup

If you created a mashup page that includes a Spotfire analysis served via Web Player using JavaScript, you can easily trigger the embedded IronPython scripts to run as soon as the report is opened.

This also works if the report is accessed directly via an URL that uses Configuration Blocks.

  • Create a Document Property as a boolean and set it to false.
  • Tie your script to that Document Property; every time its value changes, the script is triggered
If using the JS mashup page, have a JS script run when the onOpened event is fired and set that property. Make sure that the mashup page runs under the same site as the Web Player on the IIS server, eg: "Add application" under the Spotfire Web Player site.

Mashup page:

 <html>  
   <head>  
     <title>MySamplePage</title>  
     <script type="text/javascript" src="PATH_TO/SpotfireWeb/GetJavaScriptApi.ashx?Version=3.1"></script>  
     <script type="text/javascript" src="PATH_TO/myScript.js"></script>  
   </head>  
   <body>  
           <!-- Whatever -->  
           <div id="webPlayerDiv"/>  
   </body>  
 </html>  


Script:

 var webPlayer;  
 var webPlayerRelativePath = "PATH_TO/SpotfireWeb/";  
 var analysisPath = "PATH_TO/myAnalysis";  
   
 <!-- when the page is accessed, include the Web Player analysis via JS -->  
 window.onload = function()  
 {                 
   openWebPlayer();       
 };  
   
 var openWebPlayer = function()  
 {  
   var webPlayerCustomization = new spotfire.webPlayer.Customization();  
      <!-- enable/disable toolbar buttons -->  
   webPlayerCustomization.showCustomizableHeader = true;  
   webPlayerCustomization.showTopHeader = true;  
   webPlayerCustomization.showClose = true;  
   webPlayerCustomization.showAnalysisInfo = true;  
   webPlayerCustomization.showToolBar = true;  
   webPlayerCustomization.showExportFile = true;  
   webPlayerCustomization.showExportVisualization = true;  
   webPlayerCustomization.showUndoRedo = true;  
   webPlayerCustomization.showDodPanel = true;  
   webPlayerCustomization.showFilterPanel = true;  
   webPlayerCustomization.showPageNavigation = true;  
   webPlayerCustomization.showStatusBar = true;  
   
      webPlayer = new spotfire.webPlayer.Application(webPlayerRelativePath, webPlayerCustomization);  
   
   var onError = function(errorCode, description)  
   {  
     log('<span style="color: red;">[' + errorCode + "]: " + description + "</span>");  
   };  
   
      <!-- when the report is loaded, set our Document Property to true to trigger the script -->  
   var onOpened = function(analysisDocument)  
   {       
           webPlayer.analysisDocument.setDocumentProperty(  
                     "myProperty",  
                     "true");  
   };  
        
   webPlayer.onError(onError);  
   webPlayer.onOpened(onOpened);  
   webPlayer.open(analysisPath, "webPlayerDiv", "");  
 };  

If using the configuration block in the URL instead, add:

 &configurationBlock=PROPERTY_NAME=VALUE;  


So you'll have something like:

 http://myServer:PORT/SpotfireWeb/ViewAnalysis.aspx?file=/PATH_TO/MyAnalysis&configurationBlock=MyDocumentProperty=VALUE;  


31/03/2011

[PHP, JavaScript] Twitter, Google Maps, YouTube API mashup

Where you followin' me?

English:

A mashup with Twitter, Google Maps and YouTube APIs.

We grab some Twitter user's followers, show them on Google Maps and include YouTube videos about the city where most followers live.

Italiano:

Un mashup con le API di Twitter, Google Maps e YouTube.

Si recuperano i follower di un certo utente Twitter, si mostra la loro concentrazione su Google Maps e si includono dei video riguardanti la cittá in cui risiede la maggior parte dei follower.


23/06/2009

[Source code] Creare una rete sociale con php usando LAMP/XAMPP

Una descrizione di cosa andava implementato:

Parte relativa agli utenti

  1. Registrazione
    Gli utenti devono registrarsi alla rete sociale grazie ad un opportuno modulo di registrazione. Si dovranno richiedere informazioni quali: nome*, cognome*, e-mail*, password*, data di nascita, luogo di nascita*, titolo di studio, hobby, avatar ecc. Potete decidere di richiedere anche un nickname da usare come username dell'utente oppure usare il suo indirizzo e-mail.
    Nota: le informazioni con * sono obbligatorie.

    Controllo dell'input: usate le espressioni regolari o altre tecniche per verificare la correttezza sintattica dell'input. In alcuni casi si può anche usare Ajax come abbiamo visto a lezione.
    Ogni utente potrà decidere se rendere visibili le proprie informazioni a tutti gli altri utenti, solo ai suoi amici, a nessuno. Nome e cognome non possono essere nascosti.
  2. Login/Logout
    Si devono realizzare le funzioni di Login/Logout gestendole in modo opportuno mediante uso delle variabili di sessione.
    Nota: nella vita reale le credenziali per l'autenticazione non devono essere passate in chiaro.
  3. Modifica del profilo
    I dati richiesti al momento della registrazione possono essere modificati in qualunque momento grazie alla funzione di modifica del profilo.
  4. Amici (Friends)
    Dopo il login, un utente entra in una pagina dove il sistema gli propone un paio di altri utenti (al massimo 3) che potrebbero essere suoi amici. La relazione di amicizia viene calcolata considerando il luogo di nascita (che è un dato obbligatorio, anche se può essere nascosto agli altri utenti del sistema). Se ci sono più di 3 amici potenziali, il sistema ogni volta deve selezionarne 3 a caso. Se non esistono amici potenziali, il sistema dovrà restituire un messaggio opportuno.
    Nota: non devono essere visualizzati quegli utenti che sono già in relazione di amicizia con l'utente appena autenticato.
  5. Vicini (Neighbours)
    Dopo il login, un utente può richiedere di visualizzare l'elenco dei suoi vicini premendo un link o un pulsante opportuno. Per vicino si intende un altro utente registrato al sistema che ha un hobby in comune con l'utente appena autenticato. La relazione di vicinanza viene quindi calcolata considerando gli hobby. Se non esistono vicini potenziali, il sistema dovrà restituire un messaggio opportuno. Nel caso in cui l'utente non abbia specificato i propri hobby al momento della registrazione, il sistema dovrà restituire un messaggio opportuno e invitare l'utente ad aggiornare il suo profilo se vuole usare questa funzione.
    Nota: non devono essere visualizzati quegli utenti che sono già in relazione di amicizia con l'utente appena autenticato.
  6. Altri utenti (Others)
    Un motore di ricerca interno deve permettere la ricerca di altri utenti. I criteri da impostare per la ricerca devono essere definiti durante la fase di progettazione dell'applicazione. Qui potete usare Ajax per l'autocompletamento delle stringhe nella ricerca. Nel risultato della ricerca devono essere ben distinti gli utenti già in relazione di amicizia marcandoli in modo evidente.
  7. Inoltrare una richiesta di amicizia
    Dopo il login, un utente A può inviare una richiesta di amicizia ad altri utenti B (Friends, Neighbours, Others). Questa richiesta verrà visualizzata nella pagina di ingresso al sistema dell'utente B che ha ricevuto la richiesta (e anche notificata via e-mail).
  8. Accettare una richiesta di amicizia
    Dopo il login, un utente B con richieste di amicizia pendenti le vedrà visualizzate nella sua pagina di accesso alla rete sociale e dovrà decidere se accettarle oppure no.
    In entrambi i casi, all'utente A che ha fatto la richiesta di amicizia dovrà essere notificata la scelta dell'utente B.
  9. Grafo degli amici
    Dopo il login, un utente può richiedere la visualizzazione del grafo delle sue amicizie. Nel grafo delle amicizie gli utenti sono i nodi e gli archi rappresentano la relazione di amicizia tra gli utenti. Si tratta di un grafo non orientato poiché se A è amico di B, anche B è amico di A (almeno si spera!).
    Il grafo deve essere costruito a partire dal nodo che rappresenta l'utente stesso e poi si devono calcolare (1) i suoi amici (2) gli amici dei suoi amici (3) ecc. fino a quando non si potranno più aggiungere nuovi nodi/archi (cioè dovete calcolare la componente fortemente connessa del grafo a partire dal nodo che rappresenta l'utente).
    Il grafo deve essere visualizzato all'interno del browser. Per fare questo si usa neato che, dato un grafo descritto mediante il linguaggio DOT, creano un file SVG che descrive i nodi e gli archi del grafo. Il browser è in grado di visualizzare i file SVG. Sono accettate anche altre soluzioni che non usano gli script forniti sul server.
    Per maggiori informazioni potete anche vedere http://www.graphviz.org/.
Parte relativa all'amministratore

L'amministratore è un utente speciale che può bannare gli utenti del sistema perché non rispettano le regole di comportamento della rete sociale.
Una volta autenticato l'amministratore dovrà vedere un link che gli permette di visualizzare l'elenco degli utenti registrati. L'amministratore può anche usare il motore di ricerca interna per cercare un particolare utente.
Una volta trovato l'utente, l'amministratore potrà bannarlo oppure cancellarlo in modo definitivo dal sistema. Un utente bannato riceverà un messaggio automatico di alert da parte dell'amministratore. Dopo 5 giorni un utente bannato torna attivo (automaticamente) e quindi può accedere nuovamente al sistema.
Se, invece, l'amministratore decide di cancellare in modo permamente un utente dalla rete sociale, questa informazione va propagata nelle relazioni di amicizia degli altri utenti del sistema. Gli utenti cancellati non possono comparire nel grafo degli amici (quelli bannati sì).


Requisiti da rispettare


  • Dovete fare uso dei fogli di stile CSS per definire il look & feel dell'interfaccia.
  • Dovete scrivere le parti comuni a tutte le pagine in file a parte che vengono condivisi da tutte le pagine del sito in modo da poter effettuare eventuali modifiche una sola volta per l'intero sito.
  • Dovete dimostrare di conoscere JavaScript che può essere usato per validazione dell'input lato client, effetti speciali tipo il roll over delle immagini, apertura di nuove finestre (solo se utili per il sito), ...
  • Dovete dimostrare di conoscere PHP ed è obbligatorio appoggiarsi ad un database in MySQL. L'accesso al database dovrà avvenire usando le librerie offerte da MDB2.
  • Dovete provare ad usare Ajax.
  • Le pagine del prototipo devono rispettare i requisiti di accessibilità visti a lezione e devono essere validate con il validatore del W3C, usando il DOCTYPE:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    Nota. Nel progetto dovete rispettare almeno i seguenti requisiti di accessibilità
    1. Non è consentito l'uso dei frame
    2. Si devono evitare oggetti e scritte lampeggianti
    3. Si devono usare i fogli di stile
    4. La presentazione e i contenuti testuali di una pagina devono potersi adattare all'interfaccia senza sovrapposizione degli oggetti presenti
    5. Le pagine dovranno essere parzialmente utilizzabili quando gli script sono disabilitati o non supportati
    6. La destinazione di ogni collegamento ipertestuale deve essere espressa con testi significativi
    7. I collegamenti principali presenti in una pagina devono essere selezionabili e attivabili tramite comandi da tastiera

Ed ora, i file:

- Documentazione, leggetela!

- Database mySQL, acceduto con MDB2, senza utilizzare transazioni, per la connessione editare db.php secondo le proprie necessità

- File del progetto, le parti di javascript e ajax si trovano in header_fuori.php

- Sarebbe opportuno rinominare i .tmp contenti codice php in .php, per sicurezza

- Il sistema è stato testato su LAMP e XAMPP con browser Firefox, Iceweasel ed Internet Explorer (7 e 8). Opera presenta problemi grafici noti.