Tải bản đầy đủ - 0 (trang)
Hack 24. Build Your Own Stock Update Email

Hack 24. Build Your Own Stock Update Email

Tải bản đầy đủ - 0trang

Ifyou'dliketojustgetdowntoyourstockprices,orhaveabit

morecontroloverwhentheemailissent,you'llhavetodoabit

ofscripting.Luckily,Yahoo!Financegivesyouallofthe

informationyouneedtomakeithappen;youjustneedtotieit

togetherintoasingleemailwithabitofPerl.

Thisexamplereliesonthefactthatyoucanlookupanyticker

symbolviaaYahoo!FinanceURL.Forexample,alloftheday's

stockinformationaboutYHOO(thetickersymbolforYahoo!,

Inc.)ishere:http://finance.yahoo.com/q?s=YHOO.Oneach

stockdetailpagelikethisone,you'llfindatinyDownloadData

linkunderthequotedata.Thisgivesyouatext-onlyfilewith

therelevantinformationforthatstockinaformatsuitablefor

importingintoaspreadsheet.Therawdataitselfisaseriesof

comma-separatedvaluesthatlookslikethis:







"YHOO",31.57,"3/24/2005","3:17pm",+0.70,31.91,32.09,31.



Thoughtheintendeddestinationforthisdataisaspreadsheet,

youcanusethesamefiletobuildyourownemailcontaining

onlythestockinformationyouwanttosee.



2.3.1.TheCode

ThisexamplehasafewnonstandardPerlmodulesthatyou'll

needtohaveinstalledbeforeyoucanrunit.Thescriptuses

LWP::Simpletofetchthestockdata,Number::Formattomakethe

stockpriceslooknice,andNET::SMTPtosendtheemail.

You'llalsoneedtoreplaceafewvaluesinthescriptwithyour

owndata.Set$smtp_servertoyouremailserver,$from_emailtoan

addresswithpermissionstosendemailonthatserver,and

$to_emailtotheemailaddresswhereyou'dliketoreceivethe

stockupdate.Andmostimportantly,setthelistofstocksyou'd

liketotrackbyaddingtheirtickersymbolsonthisline:





my@stocks=qw(inserttickersymbolsseparatedbyspaces



SoifyouwanttotrackYahoo!,Amazon,eBay,andMicrosoftas

thisexamplescriptdoes,you'llwantthislinetolooklikethis:





my@stocks=qw(YHOOAMZNEBAYMSFT);



Savethefollowingcodetoafilecalledstock_update.pl:





#!/usr/bin/perl













#stock_update.pl

#AscripttodownloadYahoo!Financeinfoaboutstocks

#andsenditviaemail

#Usage:stock_update.pl













useLWP::Simple;

useNumber::Format;

useNet::SMTP;

usestrict;









#Setyourstocks

my@stocks=qw(YHOOAMZNEBAYMSFT);











#Setoutputfile

my$file="quick_stock_update.txt";

open(FILE,">$file")||die"Can'topen$file";



























#Setemailinfo

my$subject="QuickStockUpdate";

my$smtp_server="insertyourSMTPserver";

my$from_email='insertyourfromemail';

my$to_email='insertyourtoemail';



















#Definethefileheader

formatFILE_TOP=





QuickStockUpdate

-----------------------------------SymbolPriceDateChange

-----------------------------------.



#Definesomevariables

my$stock_symbol;

my$last_trade_f;

my$trade_date;

my$change;















#Definetheline-itemdetails

formatFILE=

@<<<<<@>>>>@||||||||||@>>>>>

$stock_symbol,$last_trade_f,$trade_date,$change

.















#Loopthroughstocks

foreachmy$stock(@stocks){



my$stock_request="http://finance.yahoo.com/d







"$stock&f=sl1d1t1c1ohgv&e=.csv"



my$stock_data=get($stock_request);







































my$x=newNumber::Format(-int_curr_symbol=>



$last_trade_f=$x->format_number($last_trade,2



$trade_date=~s/"//g;$trade_time=~s/"//g;



$stock_symbol=~s/"//g;



writeFILE;

}

#Closeoutputfile

close(FILE);









#Openoutputfileforreading

open(FILE,"$file")||die"Can'topen$file";























#Sendthefileinemail

my$smtp=Net::SMTP->new($smtp_server);

$smtp->mail($from_email);

$smtp->to($to_email);

$smtp->data();

$smtp->datasend("From:$from_email\n");

$smtp->datasend("To:$to_email\n");

$smtp->datasend("Subject:$subject\n");

$smtp->datasend('Content-Type:text/plain;charset="iso



($stock_symbol,my$last_trade,$trade_date,my



$change,my$open,my$high,my$low,m





=split(/,/,$stock_data);

















$smtp->datasend("\n\n");

while(){



$smtp->datasend("$_");

}

$smtp->dataend();

$smtp->quit;









#Closeoutputfile

close(FILE);



AsyoucanseeinthesectionlabeledLoopthroughstocks,there's

quiteabitmoredataintheYahoo!DownloadDatafilethanthis

scriptmakesuseoffortheemail.Theemailsentbythisscript

displaysthetickersymbol,latestprice,dateofthelasttrade,

andthechangeinpricefortheday.Butyou'llalsofindgood

tidbitsinthedatafile,suchastheopeningprice,highandlow

fortheday,andthevolumeofthestocktraded.Thisdatais

availableforuse,soifit'ssomethingyou'reinterestedit,you

cantweakthisscripttoshowmore.



Emailisnotasecurewaytocommunicate,sobecarefulaboutwhat

informationyouexposeinyouremailmessages.Thinkofemailasa

postcardthatothersmightbeabletoreadratherthanasealed

envelopethatonlyitsintendedrecipientopens.Anindividualemailcan

passthroughseveralserversonthewaytoitsdestination,andthere

areplentyofopportunitiesforotherstoeavesdrop,soemailisnotthe

placeforanysensitivefinancialinformation.



2.3.2.RunningtheHack

Torunthisscriptonce,youcanjustcallitfromthecommand



line:

perlstock_update.pl



Butthevalueofthescriptisinrunningitonascheduleyou're

comfortablewith.UsingWindowsScheduler,youcansetitto

runeveryweekdayafterthemarketcloses,onceaweek,or

onceaquarter.Ifyoureallywanttofeelthebumpsofthe

market,youcouldsetthistoruneveryhour.

Theemailitselfisplaintext,soyoushouldseesomethinglike

themessageshowninFigure2-6inyourinbox.



Figure2-6.Customstockupdateemail



Whilenotnearlyasaestheticallypleasingandpackedwith

informationasthestandardYahoo!DailyUpdate,thisquick

emailhasacertainminimalistcharm.Andthisbitofscripting

cangetyouexactlytheinformationyouwant,whenyouwant

it.



Hack25.DownloadFinancialDataUsingExcel

WebQueries



Whenawebsitedoesn'tofferadownloadablefileofthe

datayouwant,avoidmanualdataentrybyusing

MicrosoftExcel'swebqueryfeature.

Thesedays,youcanfindmostofthedatayouneedtoanalyze

investmentsontheWeb,andmuchofitforlittleornocost.

However,puttingthatdataintoaspreadsheetwhereyoucan

useitisanothermatter.Somewebsitesincludelinksto

downloadspreadsheets,textfilesofprices,orotherfinancial

datatoyourcomputer.Othersitesoffersubscriptionsto

downloadabledata.However,ifyoucanacceptwithequanimity

theinevitablewebpagechangesandthesubsequentreworkof

yourExcelspreadsheetsthatthosechangesrequire,youcan

createyourowntoolstodownloaddatafromtheWeb.Excel

webqueriesareeasytouseandcapturedatabytaking

advantageoftablesinawebpage'sHTMLsource.Youcanuse

webqueriestofeedyourfinancialformulasandproducenew

investmentstudiesorupdateportfoliomanagementtablesina

matterofseconds.



WebqueriesareavailableinExcelforWindows2000andlater,orin

ExcelXforMacintosh.



2.4.1.CreatinganExcelWebQuery



Webqueriesareprettyslick.Theonlyinformationawebquery

needsistheaddress(URL)ofthewebpageandthetableson

thatpagethatcontainthedatathatyouwant.Whenyou

specifyaURLintheNewWebQuerydialogbox,thewebpage

appearsinthedialogbox.InExcelXPand2003,arrowspoint

toeachtableonthepage.Afteryouselectthetablestoquery,

Excelextractsthelabelsandvaluesfromthosetablesandadds

themtocellsinaworksheet.Withoneshortcutcommand,you

canrefreshthedatafromtheWeb.Toillustrateawebquery,

let'suseaneasyexamplethepricequoteforastockormutual

fundfromYahoo!Finance.



Webqueriesaretailoredtotheconfigurationofaspecificwebpage.If

thewebsitechangesitsURLorreformatsdataintodifferenttables,

youmustrecreateyourwebqueries.



ToaddawebquerytoanexistingworksheetinanExcel

workbook,opentheworkbookandselectthetabforthe

worksheetyouwant.TocreateanewwebqueryinExcelXP,

followthesesteps:

1. ChooseData ImportExternalData NewWebQuery.

TheNewWebQuerydialogboxopens,displayingthehome

pageyouuseinInternetExplorer.ThetoolbarintheNew

WebQuerydialogboxincludesanAddressdrop-downlist,

whichisautomaticallypopulatedwithyourURLHistorylist

fromInternetExplorer.Thetoolbarhasotherfrequently

usedbrowsercommands,suchasBack,Forward,and

Refresh.

2. Ifyou'verecentlyaccessedthewebpageyouwantto

query,clicktheAddressarrowtodisplayyourURLHistory

listandselectthedesiredwebpage.Otherwise,youcan

typetheURLforthewebpageintheAddressboxandclick



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 24. Build Your Own Stock Update Email

Tải bản đầy đủ ngay(0 tr)

×