├── LICENSE.txt ├── README.md ├── hive-ohlcbars-example.sql ├── spark-ohlcbars-example.py └── spark-scala-dataframe-example.scala /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## DISCLAIMER 3 | 4 | Please note: all tools/ scripts in this repo are released for use "AS IS" without any warranties of any kind, including, but not limited to their installation, use, or performance. We disclaim any and all warranties, either express or implied, including but not limited to any warranty of noninfringement, merchantability, and/ or fitness for a particular purpose. We do not warrant that the technology will meet your requirements, that the operation thereof will be uninterrupted or error-free, or that any errors will be corrected. Any use of these scripts and tools is at your own risk. There is no guarantee that they have been through thorough testing in a comparable environment and we are not responsible for any damage or data loss incurred with their use. You are responsible for reviewing and testing any scripts you run thoroughly before use in any non-testing environment. 5 | 6 | ## Release Notes 7 | 8 | This is an example referenced in [this blog on Hive and Spark](https://www.mongodb.com/blog/post/using-mongodb-hadoop-spark-part-1-introduction-setup). 9 | -------------------------------------------------------------------------------- /hive-ohlcbars-example.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE EXTERNAL TABLE minute_bars 3 | ( 4 | id STRUCT, 5 | Symbol STRING, 6 | Timestamp STRING, 7 | Day INT, 8 | Open DOUBLE, 9 | High DOUBLE, 10 | Low DOUBLE, 11 | Close DOUBLE, 12 | Volume INT 13 | ) 14 | STORED BY 'com.mongodb.hadoop.hive.MongoStorageHandler' 15 | WITH SERDEPROPERTIES('mongo.columns.mapping'='{"id":"_id", 16 | "Symbol":"Symbol", "Timestamp":"Timestamp", "Day":"Day", "Open":"Open", "High":"High", "Low":"Low", "Close":"Close", "Volume":"Volume"}') 17 | TBLPROPERTIES('mongo.uri'='mongodb://localhost:27017/marketdata.minbars'); 18 | 19 | CREATE TABLE five_minute_bars 20 | ( 21 | id STRUCT, 22 | Symbol STRING, 23 | Timestamp STRING, 24 | Open DOUBLE, 25 | High DOUBLE, 26 | Low DOUBLE, 27 | Close DOUBLE 28 | ); 29 | 30 | INSERT INTO TABLE five_minute_bars 31 | SELECT m.id, m.Symbol, m.OpenTime as Timestamp, m.Open, m.High, m.Low, m.Close 32 | FROM 33 | (SELECT 34 | id, 35 | Symbol, 36 | FIRST_VALUE(Timestamp) 37 | OVER ( 38 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 39 | ORDER BY Timestamp) 40 | as OpenTime, 41 | LAST_VALUE(Timestamp) 42 | OVER ( 43 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 44 | ORDER BY Timestamp) 45 | as CloseTime, 46 | FIRST_VALUE(Open) 47 | OVER ( 48 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 49 | ORDER BY Timestamp) 50 | as Open, 51 | MAX(High) 52 | OVER ( 53 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 54 | ORDER BY Timestamp) 55 | as High, 56 | MIN(Low) 57 | OVER ( 58 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 59 | ORDER BY Timestamp) 60 | as Low, 61 | LAST_VALUE(Close) 62 | OVER ( 63 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 64 | ORDER BY Timestamp) 65 | as Close 66 | FROM minute_bars) as m 67 | WHERE unix_timestamp(m.CloseTime, 'yyyy-MM-dd HH:mm') - unix_timestamp(m.OpenTime, 'yyyy-MM-dd HH:mm') = 60*4; 68 | -------------------------------------------------------------------------------- /spark-ohlcbars-example.py: -------------------------------------------------------------------------------- 1 | 2 | # set up parameters for reading from MongoDB via Hadoop input format 3 | config = {"mongo.input.uri": "mongodb://localhost:27017/marketdata.minbars"} 4 | inputFormatClassName = "com.mongodb.hadoop.MongoInputFormat" 5 | 6 | # these values worked but others might as well 7 | keyClassName = "org.apache.hadoop.io.Text" 8 | valueClassName = "org.apache.hadoop.io.MapWritable" 9 | 10 | # read the 1-minute bars from MongoDB into Spark RDD format 11 | minBarRawRDD = sc.newAPIHadoopRDD(inputFormatClassName, keyClassName, valueClassName, None, None, config) 12 | 13 | # configuration for output to MongoDB 14 | config["mongo.output.uri"] = "mongodb://localhost:27017/marketdata.fiveminutebars" 15 | outputFormatClassName = "com.mongodb.hadoop.MongoOutputFormat" 16 | 17 | # takes the verbose raw structure (with extra metadata) and strips down to just the pricing data 18 | minBarRDD = minBarRawRDD.values() 19 | 20 | import calendar, time, math 21 | 22 | dateFormatString = '%Y-%m-%d %H:%M' 23 | 24 | # sort by time and then group into each bar in 5 minutes 25 | groupedBars = minBarRDD.sortBy(lambda doc: str(doc["Timestamp"])).groupBy(lambda doc: 26 | (doc["Symbol"], math.floor(calendar.timegm(time.strptime(doc["Timestamp"], dateFormatString)) / (5*60)))) 27 | 28 | # define function for looking at each group and pulling out OHLC 29 | # assume each grouping is a tuple of (symbol, seconds since epoch) and a resultIterable of 1-minute OHLC records in the group 30 | 31 | # write function to take a (tuple, group); iterate through group; and manually pull OHLC 32 | def ohlc(grouping): 33 | low = sys.maxint 34 | high = -sys.maxint 35 | i = 0 36 | groupKey = grouping[0] 37 | group = grouping[1] 38 | for doc in group: 39 | #take time and open from first bar 40 | if i == 0: 41 | openTime = doc["Timestamp"] 42 | openPrice = doc["Open"] 43 | #assign min and max from the bar if appropriate 44 | if doc["Low"] < low: 45 | low = doc["Low"] 46 | if doc["High"] > high: 47 | high = doc["High"] 48 | i = i + 1 49 | # take close of last bar 50 | if i == len(group): 51 | close = doc["Close"] 52 | outputDoc = {"Symbol": groupKey[0], 53 | "Timestamp": openTime, 54 | "Open": openPrice, 55 | "High": high, 56 | "Low": low, 57 | "Close": close} 58 | # tried returning [None, outputDoc] and seemed exception earlier 59 | return (None, outputDoc) 60 | 61 | 62 | resultRDD = groupedBars.map(ohlc) 63 | 64 | # This causes ClassCastException apparently because of an issue in Spark logged as SPARK-5361. Should write to MongoDB but could not test. 65 | # resultRDD.saveAsNewAPIHadoopFile("file:///placeholder", outputFormatClassName, None, None, None, None, config) 66 | -------------------------------------------------------------------------------- /spark-scala-dataframe-example.scala: -------------------------------------------------------------------------------- 1 | 2 | // ** Representing a MongoDB collection as a DataFrame ** 3 | 4 | //Import the relevant packages and classes 5 | import com.mongodb.casbah.{WriteConcern => MongodbWriteConcern} 6 | import com.stratio.provider._ 7 | import com.stratio.provider.mongodb._ 8 | import com.stratio.provider.mongodb.schema._ 9 | import com.stratio.provider.mongodb.writer._ 10 | import org.apache.spark.sql.hive.HiveContext 11 | import MongodbConfig._ 12 | 13 | //Configure which database and collection to read from, with optional parameters too 14 | val mcInputBuilder = MongodbConfigBuilder(Map(Host -> List("localhost:27017"), Database -> "marketdata", Collection -> "minbars", SamplingRatio -> 1.0, WriteConcern -> MongodbWriteConcern.Normal)) 15 | val readConfig = mcInputBuilder.build() 16 | 17 | //HiveContext uses Hive's SQL parser with a superset of features of SQLContext so I used that one 18 | // See http://spark.apache.org/docs/1.4.0/sql-programming-guide.html#starting-point-sqlcontext for more info 19 | val sqlContext = new HiveContext(sc) //sc is already defined as a SparkContext by the shell 20 | val dfOneMin = sqlContext.fromMongoDB(readConfig) //set up the MongoDB collection to read from as a DataFrame 21 | dfOneMin.registerTempTable("minbars") //make the table minbars available to the SQL expressions later 22 | 23 | // ** Querying Results and Saving to MongoDB ** 24 | 25 | //This applies a SQL windowing functions to partition the 1-minute bars into 5-minute windows 26 | // and then selects the open, high, low, & close price within each 5 minute window 27 | val dfFiveMinForMonth = sqlContext.sql( 28 | """ 29 | SELECT m.Symbol, m.OpenTime as Timestamp, m.Open, m.High, m.Low, m.Close 30 | FROM 31 | (SELECT 32 | 33 | Symbol, 34 | FIRST_VALUE(Timestamp) 35 | OVER ( 36 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 37 | ORDER BY Timestamp) 38 | 39 | as OpenTime, 40 | 41 | LAST_VALUE(Timestamp) 42 | OVER ( 43 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 44 | ORDER BY Timestamp) 45 | 46 | as CloseTime, 47 | 48 | FIRST_VALUE(Open) 49 | OVER ( 50 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 51 | ORDER BY Timestamp) 52 | 53 | as Open, 54 | MAX(High) 55 | OVER ( 56 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 57 | ORDER BY Timestamp) 58 | 59 | as High, 60 | 61 | MIN(Low) 62 | OVER ( 63 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 64 | ORDER BY Timestamp) 65 | 66 | as Low, 67 | LAST_VALUE(Close) 68 | OVER ( 69 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 70 | ORDER BY Timestamp) 71 | 72 | as Close 73 | FROM minbars) 74 | as m 75 | WHERE unix_timestamp(m.CloseTime, 'yyyy-MM-dd HH:mm') - unix_timestamp(m.OpenTime, 'yyyy-MM-dd HH:mm') = 60*4""" 76 | ) 77 | 78 | //Configure which table we want to write to in MongoDB 79 | val fiveMinOutputBuilder = MongodbConfigBuilder(Map(Host -> List("localhost:27017"), Database -> "marketdata", Collection -> "fiveMinBars", SamplingRatio -> 1.0, WriteConcern -> MongodbWriteConcern.Normal, SplitKey -> "_id", SplitSize -> 8)) 80 | val writeConfig = fiveMinOutputBuilder.build() 81 | 82 | //Write the data to MongoDB - because of Spark's just-in-time execution, this actually triggers running the query to read from the 1-minute bars table in MongoDB and then writing to the 5-minute bars table in MongoDB 83 | dfFiveMinForMonth.saveToMongodb(writeConfig) 84 | 85 | // ** Running Spark on any slice of data ** 86 | 87 | val dfFiveMinForMonth = sqlContext.sql( 88 | """ 89 | SELECT m.Symbol, m.OpenTime as Timestamp, m.Open, m.High, m.Low, m.Close 90 | FROM 91 | (SELECT 92 | 93 | Symbol, 94 | FIRST_VALUE(Timestamp) 95 | OVER ( 96 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 97 | ORDER BY Timestamp) 98 | 99 | as OpenTime, 100 | 101 | LAST_VALUE(Timestamp) 102 | OVER ( 103 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 104 | ORDER BY Timestamp) 105 | 106 | as CloseTime, 107 | 108 | FIRST_VALUE(Open) 109 | OVER ( 110 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 111 | ORDER BY Timestamp) 112 | 113 | as Open, 114 | MAX(High) 115 | OVER ( 116 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 117 | ORDER BY Timestamp) 118 | 119 | as High, 120 | 121 | MIN(Low) 122 | OVER ( 123 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 124 | ORDER BY Timestamp) 125 | 126 | as Low, 127 | LAST_VALUE(Close) 128 | OVER ( 129 | PARTITION BY floor(unix_timestamp(Timestamp, 'yyyy-MM-dd HH:mm')/(5*60)) 130 | ORDER BY Timestamp) 131 | 132 | as Close 133 | FROM minbars 134 | WHERE Timestamp >= '2010-07-01' AND Timestamp < '2010-08-01') 135 | as m 136 | WHERE unix_timestamp(m.CloseTime, 'yyyy-MM-dd HH:mm') - unix_timestamp(m.OpenTime, 'yyyy-MM-dd HH:mm') = 60*4""" 137 | ) --------------------------------------------------------------------------------