├── LICENSE.txt ├── pyfinance ├── test │ └── __init__.py ├── __init__.py └── yfinanceapi.py ├── MANIFEST.in ├── CHANGES.txt ├── README.md ├── setup.py ├── .gitattributes └── .gitignore /LICENSE.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pyfinance/test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | recursive-include docs *.txt -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | v0.0.1, August 8, 2013 -- Initial Creation (Incomplete) -------------------------------------------------------------------------------- /pyfinance/__init__.py: -------------------------------------------------------------------------------- 1 | #tradingstrategies.py 2 | #Charles J. Lai 3 | #August 10, 2013 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pyfinance 2 | ========= 3 | 4 | Pyfinance is a Python wrapper for Yahoo Finance's RESTful API for 5 | getting stock data in CSV format. 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup( 4 | name='PyStrat', 5 | version='0.0.1', 6 | author='Charles J. Lai', 7 | author_email='cjl223@cornell.edu', 8 | packages=['pystrat', 'pystrat.test'], 9 | scripts=[], 10 | url='', 11 | license='LICENSE.txt', 12 | description='A python trading strategy backtesting system.', 13 | long_description=open('README.txt').read(), 14 | install_requires=[ 15 | ], 16 | ) -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | 46 | [Dd]ebug/ 47 | [Rr]elease/ 48 | x64/ 49 | build/ 50 | [Bb]in/ 51 | [Oo]bj/ 52 | 53 | # MSTest test Results 54 | [Tt]est[Rr]esult*/ 55 | [Bb]uild[Ll]og.* 56 | 57 | *_i.c 58 | *_p.c 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.log 79 | *.scc 80 | 81 | # Visual C++ cache files 82 | ipch/ 83 | *.aps 84 | *.ncb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | 101 | # TeamCity is a build add-in 102 | _TeamCity* 103 | 104 | # DotCover is a Code Coverage Tool 105 | *.dotCover 106 | 107 | # NCrunch 108 | *.ncrunch* 109 | .*crunch*.local.xml 110 | 111 | # Installshield output folder 112 | [Ee]xpress/ 113 | 114 | # DocProject is a documentation generator add-in 115 | DocProject/buildhelp/ 116 | DocProject/Help/*.HxT 117 | DocProject/Help/*.HxC 118 | DocProject/Help/*.hhc 119 | DocProject/Help/*.hhk 120 | DocProject/Help/*.hhp 121 | DocProject/Help/Html2 122 | DocProject/Help/html 123 | 124 | # Click-Once directory 125 | publish/ 126 | 127 | # Publish Web Output 128 | *.Publish.xml 129 | *.pubxml 130 | 131 | # NuGet Packages Directory 132 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 133 | #packages/ 134 | 135 | # Windows Azure Build Output 136 | csx 137 | *.build.csdef 138 | 139 | # Windows Store app package directory 140 | AppPackages/ 141 | 142 | # Others 143 | sql/ 144 | *.Cache 145 | ClientBin/ 146 | [Ss]tyle[Cc]op.* 147 | ~$* 148 | *~ 149 | *.dbmdl 150 | *.[Pp]ublish.xml 151 | *.pfx 152 | *.publishsettings 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | App_Data/*.mdf 166 | App_Data/*.ldf 167 | 168 | ############# 169 | ## Windows detritus 170 | ############# 171 | 172 | # Windows image file caches 173 | Thumbs.db 174 | ehthumbs.db 175 | 176 | # Folder config file 177 | Desktop.ini 178 | 179 | # Recycle Bin used on file shares 180 | $RECYCLE.BIN/ 181 | 182 | # Mac crap 183 | .DS_Store 184 | 185 | 186 | ############# 187 | ## Python 188 | ############# 189 | 190 | *.py[co] 191 | 192 | # Packages 193 | *.egg 194 | *.egg-info 195 | dist/ 196 | build/ 197 | eggs/ 198 | parts/ 199 | var/ 200 | sdist/ 201 | develop-eggs/ 202 | .installed.cfg 203 | 204 | # Installer logs 205 | pip-log.txt 206 | 207 | # Unit test / coverage reports 208 | .coverage 209 | .tox 210 | 211 | #Translations 212 | *.mo 213 | 214 | #Mr Developer 215 | .mr.developer.cfg 216 | -------------------------------------------------------------------------------- /pyfinance/yfinanceapi.py: -------------------------------------------------------------------------------- 1 | #yfinanceapi.py 2 | #Charles J. Lai 3 | #September 30, 2013 4 | import urllib 5 | 6 | """ 7 | ============== 8 | yfinanceapi.py 9 | ============== 10 | 11 | The following is a module containing a Python API wrapper into Yahoo Finance RESTful 12 | API for getting stock ticker information in CSV format. It includes an umbrella 13 | function call that returns a hash table of various relevant stock information 14 | as well as individual methods that return a single integer or string of relevant 15 | information. This module does not provide support for simultaneously getting data 16 | for 2 or more stock tickers. 17 | 18 | Common Parameters 19 | ----------------- 20 | symbol = stock ticker symbol for a given security is string form (ex. 'goog') 21 | 22 | Methods 23 | ------- 24 | get_all(symbol) 25 | 26 | 27 | """ 28 | def __fetch(symbol, parameter): 29 | """ 30 | Returns: List of values parsed from the Yahoo finance csv object. 31 | 32 | First, the function reads from a Yahoo finance csv url using an 33 | http request from urllib.urlopen(). 34 | 35 | Values of the csv object are parsed and placed into a list in the 36 | order of the "f=parameter" given. For example if "f=ns" then the 37 | name of the security is placed into the list first and followed 38 | by the symbol. 39 | """ 40 | url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (symbol, parameter) 41 | #Parse the values an place into a list 42 | return urllib.urlopen(url).read().strip().strip('"') 43 | 44 | #========================================================================= 45 | # Commonly Retrieved Values Function 46 | #========================================================================= 47 | def get_all(symbol): 48 | """ 49 | Returns: A hash table/dictionary of values. 50 | 51 | Gets commonly used data for a specific security and places it into a 52 | hash table of values. Look up keys are strings such as 'symbol', 'name' 53 | or 'dividend_yield'. A full list of fetched information can be gleaned 54 | from the following source code. 55 | 56 | The string passed into the HTTP request are symbols used in Yahoo's 57 | RESTful API for financial data and map to specific values. These are 58 | extracted into the stock_data hash table. 59 | """ 60 | values = __fetch(symbol, 'snxopl1c1ghva2j1dyjkm3m4erj4').split(',') 61 | stock_data = {} 62 | stock_data['symbol'] = values[0] 63 | stock_data['name'] = values[1] 64 | stock_data['exchange'] = values[2] 65 | stock_data['open'] = values[3] 66 | stock_data['prev_close'] = values[4] 67 | stock_data['price'] = values[5] 68 | stock_data['change'] = values[6] 69 | stock_data['days_low'] = values[7] 70 | stock_data['days_high'] = values[8] 71 | stock_data['volume'] = values[9] 72 | stock_data['avg_daily_volume'] = values[10] 73 | stock_data['market_cap'] = values[11] 74 | stock_data['dividend_per_share'] = values[12] 75 | stock_data['dividend_yield'] = values[13] 76 | stock_data['52_week_low'] = values[14] 77 | stock_data['52_week_high'] = values[15] 78 | stock_data['50_day_ma'] = values[16] 79 | stock_data['200_day_ma'] = values[17] 80 | stock_data['earnings_per_share'] = values[18] 81 | stock_data['price_earnings_ratio'] = values[19] 82 | stock_data['ebitda'] = values[20] 83 | return stock_data 84 | 85 | #========================================================================= 86 | # Historical Price Function 87 | #========================================================================= 88 | def get_historical_prices(symbol, start_date, end_date): 89 | """ 90 | Returns: A list of historical prices for the given ticker symbol and 91 | range of dates. 92 | 93 | Preconditions: start_date and end_date are in 'YYYYMMDD' format. 94 | """ 95 | url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \ 96 | 'd=%s&' % str(int(end_date[4:6]) - 1) + \ 97 | 'e=%s&' % str(int(end_date[6:8])) + \ 98 | 'f=%s&' % str(int(end_date[0:4])) + \ 99 | 'g=d&' + \ 100 | 'a=%s&' % str(int(start_date[4:6]) - 1) + \ 101 | 'b=%s&' % str(int(start_date[6:8])) + \ 102 | 'c=%s&' % str(int(start_date[0:4])) + \ 103 | 'ignore=.csv' 104 | days = urllib.urlopen(url).readlines() 105 | stock_data = [day[:-2].split(',') for day in days] 106 | return stock_data 107 | 108 | #========================================================================= 109 | # Individual Data Mining Functions 110 | #========================================================================= 111 | def get_symbol(symbol): 112 | """ 113 | Returns: A one-dimensional list containing the string representation 114 | of the ticker symbol for a given security. 115 | 116 | (Kind of redundant but here in order for the Yahoo Finance API to be 117 | fairly complete) 118 | """ 119 | return __fetch(symbol, 's') 120 | 121 | 122 | def get_name(symbol): 123 | """ 124 | Returns: A string of the name of a given security. 125 | """ 126 | return __fetch(symbol, 'n') 127 | 128 | 129 | def get_ask(symbol): 130 | """ 131 | Returns: The ask price of a given security in real-time. 132 | """ 133 | return __fetch(symbol, 'a') 134 | 135 | 136 | def get_bid(symbol): 137 | """ 138 | Returns: The bid price of a given security in real-time. 139 | """ 140 | return __fetch(symbol, 'b') 141 | 142 | 143 | def get_open(symbol): 144 | """ 145 | Returns: A one-dimensional list containing the string representation 146 | of the opening price for a given security. 147 | """ 148 | return __fetch(symbol, 'o') 149 | 150 | 151 | def get_prev_close(symbol): 152 | """ 153 | """ 154 | return __fetch(symbol, 'p') 155 | 156 | 157 | def get_price(symbol): 158 | """ 159 | """ 160 | return __fetch(symbol, 'l1') 161 | 162 | 163 | def get_change(symbol): 164 | """ 165 | """ 166 | return __fetch(symbol, 'c1') 167 | 168 | 169 | def get_volume(symbol): 170 | """ 171 | """ 172 | return __fetch(symbol, 'v') 173 | 174 | 175 | def get_avg_daily_volume(symbol): 176 | """ 177 | """ 178 | return __fetch(symbol, 'a2') 179 | 180 | 181 | def get_after_hours_change(symbol): 182 | """ 183 | """ 184 | return __fetch(symbol, 'c8') 185 | 186 | 187 | def get_trade_date(symbol): 188 | """ 189 | """ 190 | return __fetch(symbol, 'd2') 191 | 192 | 193 | def get_float_shares(symbol): 194 | """ 195 | """ 196 | return __fetch(symbol, 'f6') 197 | 198 | 199 | def get_annualized_gain(symbol): 200 | """ 201 | """ 202 | return __fetch(symbol, 'g3') 203 | 204 | 205 | def get_holdings_gain(symbol): 206 | """ 207 | """ 208 | return __fetch(symbol, 'g6') 209 | 210 | 211 | def get_days_value_change(symbol): 212 | """ 213 | """ 214 | return __fetch(symbol, 'w4') 215 | 216 | 217 | def get_stock_exchange(symbol): 218 | """ 219 | """ 220 | return __fetch(symbol, 'x') 221 | 222 | 223 | def get_market_cap(symbol): 224 | """ 225 | """ 226 | return __fetch(symbol, 'j1') 227 | 228 | 229 | def get_book_value(symbol): 230 | """ 231 | """ 232 | return __fetch(symbol, 'b4') 233 | 234 | 235 | def get_ebitda(symbol): 236 | """ 237 | """ 238 | return __fetch(symbol, 'j4') 239 | 240 | 241 | def get_dividend_per_share(symbol): 242 | """ 243 | """ 244 | return __fetch(symbol, 'd') 245 | 246 | 247 | def get_dividend_yield(symbol): 248 | """ 249 | """ 250 | return __fetch(symbol, 'y') 251 | 252 | 253 | def get_earnings_per_share(symbol): 254 | """ 255 | """ 256 | return __fetch(symbol, 'e') 257 | 258 | 259 | def get_52_week_high(symbol): 260 | """ 261 | """ 262 | return __fetch(symbol, 'k') 263 | 264 | 265 | def get_52_week_low(symbol): 266 | """ 267 | """ 268 | return __fetch(symbol, 'j') 269 | 270 | 271 | def get_50day_moving_avg(symbol): 272 | """ 273 | """ 274 | return __fetch(symbol, 'm3') 275 | 276 | 277 | def get_200day_moving_avg(symbol): 278 | """ 279 | """ 280 | return __fetch(symbol, 'm4') 281 | 282 | 283 | def get_price_earnings_ratio(symbol): 284 | """ 285 | """ 286 | return __fetch(symbol, 'r') 287 | 288 | 289 | def get_price_earnings_growth_ratio(symbol): 290 | """ 291 | """ 292 | return __fetch(symbol, 'r5') 293 | 294 | 295 | def get_price_sales_ratio(symbol): 296 | """ 297 | """ 298 | return __fetch(symbol, 'p5') 299 | 300 | 301 | def get_price_book_ratio(symbol): 302 | """ 303 | """ 304 | return __fetch(symbol, 'p6') 305 | 306 | 307 | def get_short_ratio(symbol): 308 | """ 309 | """ 310 | return __fetch(symbol, 's7') 311 | --------------------------------------------------------------------------------