<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michaela Woods on Medium]]></title>
        <description><![CDATA[Stories by Michaela Woods on Medium]]></description>
        <link>https://medium.com/@mwoods_20994?source=rss-972021150910------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y86Hori6Yqws02_lr1bu_Q.png</url>
            <title>Stories by Michaela Woods on Medium</title>
            <link>https://medium.com/@mwoods_20994?source=rss-972021150910------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:24:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mwoods_20994/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Analyzing Stock Data with kdb+: Loading and calculating VWAP & OHLC from NYSE TAQ]]></title>
            <link>https://medium.com/kx-systems/analyzing-stock-data-with-kdb-loading-and-calculating-vwap-ohlc-from-nyse-taq-3fa6eef9a2c5?source=rss-972021150910------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fa6eef9a2c5</guid>
            <category><![CDATA[trading-analysis]]></category>
            <category><![CDATA[financial-data]]></category>
            <category><![CDATA[nyse]]></category>
            <category><![CDATA[kdb]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Michaela Woods]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 16:57:16 GMT</pubDate>
            <atom:updated>2025-01-02T11:13:25.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*965eHZpKibMN5MiQ-Un6bA.png" /></figure><p>If you’ve ever worked with financial data, you know how challenging it can be to process and analyze large datasets, especially when dealing with <strong>Trade and Quote (TAQ)</strong> data. TAQ data from the NYSE provides rich information about market activity — trades, quotes, and various other metrics — giving you an incredible opportunity to uncover valuable insights. But this data can be overwhelming without the right tools.</p><p>This is where <strong>kdb+ </strong>can help, it’s a high-performance database engine designed for time-series data analysis. In this guide, we’ll walk through how to use <strong>kdb+</strong> to process, load, and query NYSE Daily TAQ data. By the end of this article, you’ll be able to efficiently analyze TAQ data calculating some common analytics like VWAP and OHLC using <strong>kdb+</strong> and its query language <strong>q</strong>.</p><h3>Why kdb+?</h3><p>Before we dive into the practical steps, you might wonder why <strong>kdb+</strong> is a great choice for analyzing TAQ data.</p><ul><li><strong>Performance</strong>: kdb+ is optimized for time-series data, making it perfect for analyzing trading data, which is heavily timestamped and requires fast querying.</li><li><strong>Simplicity</strong>: The <strong>q</strong> language used by kdb+ is simple but powerful, designed to handle large datasets efficiently with minimal code.</li><li><strong>Scalability</strong>: kdb+ can handle massive datasets, which is important when working with years of trading data.</li></ul><h3>Getting Started: Setting Up Your Environment</h3><p>Let’s get things set up so we can start analyzing.</p><h4>Prerequisites</h4><ul><li><a href="https://kx.com/kdb-personal-edition-download/">kdb+</a> installed on your machine</li><li>NYSE Daily TAQ files from <a href="https://github.com/KxSystems/kdb-taq/blob/master/ftp.nyse.com">ftp.nyse.com</a></li></ul><h4>1. Download the TAQ Data</h4><p>The first step is to get the data you’ll be working with. NYSE offers <strong>Daily TAQ</strong> files, which are updated regularly and can be downloaded directly from their FTP server.</p><p>Here’s an example of how to download a file using <strong>wget</strong>:</p><pre>wget https://ftp.nyse.com/Historical%20Data%20Samples/DAILY%20TAQ/EQY_US_ALL_TRADE_20240702.gz</pre><p>These files are <strong>~2GB each</strong>, so expect them to take some time to download depending on your connection speed.</p><h4>2. Clone the Repository</h4><p>Next, grab the <a href="https://github.com/KxSystems/kdb-taq/tree/master"><strong>kdb-taq</strong> repository</a>, which includes scripts and utilities to process TAQ data.</p><pre>git clone https://github.com/KxSystems/kdb-taq.git<br>cd kdb-taq</pre><p>This repository contains a script (tq.q) that helps process and load the data.</p><h4>3. Prepare the Data</h4><p>After downloading the data, you’ll need to decompress and organize it into a directory that <strong>kdb+</strong> can use.</p><pre>mkdir SRC<br>mv /path/to/EQY_US_ALL_TRADE_20240702.gz SRC/<br>gzip -d SRC/*</pre><h4>4. Process the Data</h4><p>Now, it’s time to process the raw TAQ data. The tq.q script included in the repository handles this step.</p><p>Run the following command to process the data:</p><pre>q tq.q -s 8 SRC</pre><p>Here, the <a href="https://code.kx.com/q/basics/cmdline/#-s-secondary-threads">-s</a> flag specifies the number of threads for processing, and SRC is the directory containing your TAQ files. The processing step reads and parses the raw data into a format suitable for querying.</p><h4>5. Load the Data into kdb+</h4><p>Once the data is processed, you can load it into the environment using<a href="https://code.kx.com/q/basics/syscmds/#l-load-file-or-directory">\l</a> which is the load command:</p><pre>q)\l tq</pre><h3>Querying the Data</h3><p>With the data now loaded, let’s run a few simple queries to get a feel for how to interact with it.</p><h4>View the Schema:</h4><p>To see the structure of the <strong>trade</strong> table and its columns, use the <a href="https://code.kx.com/q/ref/meta/">meta</a> command:</p><pre>q)meta trade<br><br>c                                 | t f a<br>----------------------------------| -----<br>date                              | d    <br>Time                              | n    <br>Exchange                          | c    <br>Symbol                            | s   p<br>SaleCondition                     | s    <br>TradeVolume                       | i    <br>TradePrice                        | e    <br>TradeStopStockIndicator           | b    <br>TradeCorrectionIndicator          | h    <br>SequenceNumber                    | i    <br>TradeId                           | C    <br>SourceofTrade                     | c    <br>TradeReportingFacility            | b    <br>ParticipantTimestamp              | n    <br>TradeReportingFacilityTRFTimestamp| n    <br>TradeThroughExemptIndicator       | b</pre><p>This will display the column names and <a href="https://code.kx.com/q/ref/#datatypes">data types</a>, so you know how to interact with the table.</p><h4>Example: Count the Number of Trades by Stock</h4><p>Here’s a quick example of how to analyze the data. We can find the number of trades that occurred for each symbol, as well as the highest trade price:</p><pre>q)select numTrade:count i, maxPrice:max TradePrice by Symbol from trade<br><br>Symbol | numTrade maxPrice<br>-------| -----------------<br>A      | 29655    133.03  <br>AA     | 36623    41.15   <br>AAA    | 51       25.07   <br>AAAU   | 2786     23.13   <br>AACG   | 108      0.86    <br>AACI   | 6        11.45   <br>AACT   | 1033     11.38   <br>AACT.U | 1        10.745  <br>AACT.WS| 24       0.1365  <br>....</pre><p>When we are querying our database, different query structures can have a drastic effect on performance. We can use the function “\t” before a q expression as a way to extract the time taken, in milliseconds, for a query to complete:</p><pre>q)\t select numTrade:count i, maxPrice:max TradePrice by Symbol from trade<br><br>113</pre><h3>Advanced Analysis</h3><p>Now that you have a basic understanding of how to load and query NYSE TAQ data, here are a few more advanced analysis examples you can try with <strong>kdb+.</strong></p><h4>Volume Profile</h4><p>The volume profile helps traders understand the concentration of trades at various price levels throughout the day. By analyzing how volume accumulates during different periods, traders can make more informed decisions about entry and exit points for stocks.</p><p>We can group up the size of the orders into 5 minute time intervals using <a href="https://code.kx.com/q/ref/xbar/">xbar</a>:</p><pre>q)select sum TradeVolume by 5 xbar Time.minute from trade where Symbol = `AAPL<br><br>minute| TradeVolume<br>------| -----------<br>04:00 | 10805      <br>04:05 | 2257       <br>04:10 | 1078       <br>04:15 | 2216       <br>04:20 | 1365       <br>04:25 | 4717       <br>...</pre><p>We could also use <a href="https://code.kx.com/q/ref/sum/#sums">sums</a> to show the rolling sum throughout the day for a symbol.</p><pre>q)select Time, sums TradeVolume from trade where Symbol = `AAPL<br><br>Time                 TradeVolume<br>--------------------------------<br>0D04:00:00.017646926 1          <br>0D04:00:00.020101346 21         <br>0D04:00:00.022979538 22         <br>0D04:00:00.022987522 42         <br>0D04:00:00.023776991 67         <br>0D04:00:00.023920135 69 <br>....</pre><p>This output could then be charted to illustrate the change throughout the day. I am using <a href="https://code.kx.com/analyst/">KX Analyst</a> to create quick and easy charts, you can also use <a href="https://code.kx.com/developer/">KX Developer</a> which is available for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJm7ibGCGeTx53nYsEAZbQ.png" /></figure><p>The steep increases in the curve highlight periods of significant trading activity, reflecting market volatility or heightened interest in the stock. This type of visualization is helpful for analyzing intraday trends and identifying periods of concentrated trading volume.</p><p>For example, if the volume profile shows a high concentration of trades at a particular price, it suggests that this price has a strong historical significance and might act as a support or resistance level in future trading.</p><h4>Volume Weighted Average</h4><p>Volume-weighted averages give a more accurate reflection of a stock’s price movement by incorporating trading volume at different price levels. This can be especially useful in understanding whether a price move is supported by strong market participation or is just a result of a few trades.</p><p>The weighted average function <a href="https://code.kx.com/q/ref/avg/#wavg">wavg</a> can be used to find out the weighted average over time intervals.</p><pre>q)select TradeVolume wavg TradePrice by Symbol from trade<br><br>Symbol | TradePrice<br>-------| ----------<br>A      | 126.0225  <br>AA     | 40.73105  <br>AAA    | 25.03718  <br>AAAU   | 23.01037  <br>AACG   | 0.8178756 <br>AACI   | 11.37241  <br>... </pre><p>We often want the weight average over time intervals (different volumes and prices throughout the day).</p><pre>q)select LastPrice:last TradePrice, <br>         WeightedPrice:TradeVolume wavg TradePrice<br>   by 15 xbar Time.minute <br>   from trade <br>   where Symbol = `IBM<br><br>minute| LastPrice WeightedPrice<br>------| -----------------------<br>04:00 | 175.02    175.02       <br>04:30 | 174.99    174.99       <br>05:15 | 174.98    174.98       <br>05:30 | 174.93    174.8051     <br>05:45 | 174.96    174.91       <br>06:00 | 174.96    174.9558     <br>...</pre><p>The data shows IBM’s stock price movements throughout the day, with both the “LastPrice” and “WeightedPrice” remaining closely aligned, indicating stable pricing with minimal influence from trade volume. This suggests a moderate upward trend in IBM’s stock price, with small fluctuations in the morning and more noticeable gains later in the day, reflecting overall positive market sentiment during the trading session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eE-koJcIoLmj8P5W58t6g.png" /></figure><p>The “VWAP” (Volume Weighted Average Price) is often used by institutional traders to enter or exit positions without influencing the market too much.</p><h4>Open-High-Low-Close</h4><p>Analysts use OHLC tables to track trends of securities, especially in the short term. We can easily write a query that will calculate the OHLC for a particular date and sym and the vwap for each 5-minute interval.</p><pre>q)select low:min TradePrice,<br>         open:first TradePrice,<br>         close:last TradePrice,<br>         high:max TradePrice,<br>         volume:sum TradeVolume,<br>         vwap:TradeVolume wavg TradePrice <br>   by 5 xbar Time.minute  <br>   from trade where Symbol=`AAPL<br><br>minute| low      open     close    high     volume  vwap    <br>------| ----------------------------------------------------<br>04:00 | 215.89   216.6    216.11   216.6    10805   216.2432<br>04:05 | 216.1    216.18   216.27   216.27   2257    216.151 <br>04:10 | 216.2    216.28   216.35   216.35   1078    216.2547<br>04:15 | 216.28   216.3    216.39   216.46   2216    216.3775<br>04:20 | 216.24   216.38   216.26   216.42   1365    216.3638<br>04:25 | 216.21   216.28   216.4    216.43   4717    216.323 <br>.....</pre><p>We can create this query as a function so analysts can use it to retrieve the result for a particular stock.</p><pre>q)ohlcLookup:{[symbol] <br>    select low:min TradePrice,<br>           open:first TradePrice,<br>           close:last TradePrice,<br>           high:max TradePrice,<br>           volume:sum TradeVolume,<br>           vwap:TradeVolume wavg TradePrice <br>        by 5 xbar Time.minute  <br>        from trade where Symbol=symbol}<br><br>q)ohlcLookup[`MSFT]<br><br>minute| low      open     close    high     volume  vwap    <br>------| ----------------------------------------------------<br>04:00 | 455.29   456.2    455.61   456.7    5742    455.8347<br>04:05 | 455.11   455.5    455.32   455.67   1352    455.4394<br>04:10 | 455.07   455.33   455.37   455.47   1879    455.238 <br>...<br><br>q)ohlcLookup[`GOOG]<br>minute| low      open     close    high     volume vwap    <br>------| ---------------------------------------------------<br>04:00 | 183.94   184.01   184.14   184.38   2315   184.0851<br>04:05 | 183.97   184.07   184.02   184.07   373    184.0005<br>04:10 | 184.06   184.06   184.1    184.23   239    184.1581<br>...</pre><h3>Conclusion</h3><p>In this guide, we’ve walked through everything from downloading and processing NYSE TAQ data, to performing basic and advanced queries using <strong>kdb+</strong>.</p><p>With <strong>kdb+</strong> and the <strong>kdb-taq</strong> repository, analyzing NYSE TAQ data has never been easier. Whether you’re tracking daily trading patterns, calculating key metrics, or exploring price fluctuations, <strong>kdb+</strong> provides the tools you need to get meaningful insights from massive datasets quickly.</p><p>Now that you have the basics down, try running these queries on your own dataset. Explore different symbols or apply the advanced analysis techniques to detect trends and trading patterns. <a href="https://kx.com/kdb-personal-edition-download/">Download kdb+</a> to get started or reach out to ask any questions on our <a href="http://kx.com/slack">Slack community</a>.</p><p>Have you worked with NYSE TAQ data before? Share your experiences or ask any questions in the comments section below. I’d love to hear how you’re applying <strong>kdb+</strong> for your own financial data analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fa6eef9a2c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kx-systems/analyzing-stock-data-with-kdb-loading-and-calculating-vwap-ohlc-from-nyse-taq-3fa6eef9a2c5">Analyzing Stock Data with kdb+: Loading and calculating VWAP &amp; OHLC from NYSE TAQ</a> was originally published in <a href="https://medium.com/kx-systems">KX Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[kdb+ Security Made Simple: How to Protect Your Data with Permissions and Access Control]]></title>
            <link>https://medium.com/kx-systems/kdb-security-made-simple-how-to-protect-your-data-with-permissions-and-access-control-3516bc7355d4?source=rss-972021150910------2</link>
            <guid isPermaLink="false">https://medium.com/p/3516bc7355d4</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kdb]]></category>
            <dc:creator><![CDATA[Michaela Woods]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 15:03:07 GMT</pubDate>
            <atom:updated>2024-12-17T12:34:29.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yl7ljoZDt8hzct8ZNtYA5A.png" /></figure><p>Imagine you’re managing a kdb+ system for a high-frequency trading desk. Your system runs like clockwork — queries blaze through in milliseconds, data flows smoothly — until one day, an unauthorized query causes chaos. Maybe it’s a mistyped command or a deliberate attempt to breach security. Either way, the result could be devastating. How do you safeguard your system from such risks?</p><p>This article isn’t about turning you into a permissions-system architect from scratch — after all, KX offers enterprise-grade solutions for production environments. But understanding the ins and outs of kdb+ permissions is invaluable. It equips you with the tools to build robust systems, troubleshoot like a pro, and confidently navigate access management challenges.</p><p>Let’s explore how to secure your kdb+ system step-by-step, diving into practical examples to implement authentication, track connections, and control user permissions.</p><h3>Why Does Security Matter for kdb+ Systems?</h3><p>Kdb+ is renowned for speed and efficiency, but with great power comes great responsibility. Whether you’re working with financial data, telemetry from a Formula 1 car, or sensitive user analytics, the stakes are high. Unauthorized access can lead to financial losses, system instability, or breaches of compliance regulations.</p><p>Securing your kdb+ system ensures:</p><ul><li><strong>Data Integrity:</strong> Only authorized users can interact with your database.</li><li><strong>System Stability:</strong> Prevent malicious or accidental misuse.</li><li><strong>Auditability:</strong> Track who’s accessing what and when.</li></ul><p>With these goals in mind, let’s dive into the tools kdb+ offers to protect your system.</p><h3>The Building Blocks of kdb+ Security: .z Handlers</h3><p>Think of .z handlers as your security toolkit. Each handler serves a specific purpose, from validating credentials to logging connection events. Here are the key players:</p><ul><li><a href="https://code.kx.com/q/ref/dotz/#zpw-validate-user"><strong>.z.pw</strong></a><strong>:</strong> The gatekeeper, validating user credentials.</li><li><a href="https://code.kx.com/q/ref/dotz/#zpo-open"><strong>.z.po</strong></a><strong> &amp; </strong><a href="https://code.kx.com/q/ref/dotz/#zpc-close"><strong>.z.pc</strong></a><strong>:</strong> The connection managers, tracking opens and closures.</li><li><a href="https://code.kx.com/q/ref/dotz/#zpg-get"><strong>.z.pg</strong></a><strong>:</strong> The enforcer, restricting query execution based on permissions.</li><li><a href="https://code.kx.com/q/ref/dotz/#zps-set"><strong>.z.ps</strong></a><strong>:</strong> The firewall, controlling asynchronous messages.</li><li><a href="https://code.kx.com/q/ref/dotz/#zph-http-get"><strong>.z.ph</strong></a><strong>:</strong> The web gatekeeper, managing HTTP queries.</li></ul><p>We’ll focus on the first four handlers to build a secure, role-based access system</p><h3>Prerequisites: Setting Up kdb+</h3><p>Before diving into permissions and access control, ensure your kdb+ environment is up and running. Download the appropriate version of kdb+ for your system from <a href="https://kx.com/kdb-insights-personal-edition-license-download/">kx.com</a> and follow these <a href="https://code.kx.com/insights/core/install.html#binary-installation-linux">installation instructions</a>.</p><h3>Step 1: Building Your Gatekeeper with .z.pw</h3><p>Imagine .z.pw as your system’s digital bouncer. Its job? Ensuring only users with the right credentials cross the threshold.</p><h4>Define Your Guest List</h4><p>First start a kdb+ instances on ports 5001, this will be our remote process or in this analogy - the systems nightclub.</p><pre>$ q -p 5001</pre><p>Then create a table containing the usernames and their corresponding passwords to manage access on a separate instance. Working from port 5000 we are going to use the handle h to define the table on the remote process (port 5001).</p><pre>$ q -p 5000<br>q)h:hopen 5001<br>7i<br><br>// Defining .perm.users on 5001 <br>q)users:([user:`mary`john`ann ] class:`basicUser`superUser`basicUser; password:(&quot;pwd&quot;;&quot;pwd&quot;;&quot;pwd&quot;))<br>q)h(set;`.perm.users;users)<br>q)h&quot;.perm.users&quot;<br>user| class     password<br>----| ------------------<br>mary| basicUser &quot;pwd&quot;   <br>john| superUser &quot;pwd&quot;   <br>ann | basicUser &quot;pwd&quot; </pre><p>You might notice we have used a few different methods here to call to the remote process, using both brackets and quotes. To learn more about these methods and IPC in kdb+ you can check out the free <a href="https://learninghub.kx.com/courses/kdb-developer-level-2/lessons/inter-process-communication/">KX Academy module</a>.</p><h4>Set the Rules</h4><p>Once the user table is defined, you can set .z.pw to check the username and password during the connection attempt.</p><pre>q)h&quot;.z.pw:{[user;pswd] $[pswd~.perm.users[user][`password]; 1b; 0b]}&quot;</pre><p>In this example, if the provided password matches the stored password, it returns 1b (true); otherwise, it returns 0b (false).</p><h4>Test the Gatekeeper</h4><p>When you attempt to connect with the wrong password, you will receive an <strong>access</strong> error:</p><pre>q)hopen `::5001:mary:wrongpwd  // incorrect credentials<br>&#39;access<br><br>q)hopen `::5001:mary:pwd       // correct credentials<br>8i</pre><p>If you run into any trouble, you can expunge any event handler with \x.This will undo the definition of .z.pw and allow all users to connect again:</p><pre>q)h&quot;\\x .z.pw&quot;</pre><p>As .z.pwis simply a function it can be used to implement rules stored locally like checking against a table we maintain of authenticated users on our server; or we could go out to external resources like an LDAP or Kerberos.</p><h3>Step 2: Tracking Connections with .z.po and .z.pc</h3><p>Once users can connect, you can also manage and track connections using .z.po (port open) and .z.pc (port close) handlers. These event handlers allow you to capture information about the connections, such as the IP address and user.</p><h4>Log Open Connections with .z.po</h4><p>You can maintain a list of connection handles or even log the connection details in a table. Let’s define an empty table first:</p><pre>q)h&quot;.ipc.connections: ([handle:()];time: ();user:();id:();state:())&quot;</pre><p>And define our open connection handler .z.po to update the table with the connection details. We can see the .ipc.connections table is empty at this point.</p><pre>q)ID:`Client5000<br>q)h&quot;.z.po:{ `.ipc.connections insert (x;.z.p;.z.u;.z.w `ID;`open)}&quot;<br>q)h&quot;.ipc.connections&quot;<br>handle| time user id state<br>------| ------------------</pre><p>When a connection is opened, the system records:</p><ul><li>Handle (x)</li><li>Time (.z.p)</li><li>User (.z.u)</li><li>ID on Remote process — can reference with .z.w</li><li>State (open/close)</li></ul><p>Let’s open a connection then check our .ipc.connections table:</p><pre>q)hopen 5001<br>9i<br><br>q)h&quot;.ipc.connections&quot;<br>handle| time                          user   id         state<br>------| -----------------------------------------------------<br>9     | 2024.11.21D17:12:13.572488665 mwoods Client5000 open <br></pre><p>Re-running this a few times you can see how the table is getting added to with each open connection.</p><pre>q)hopen 5001<br>10i<br>q)hopen 5001<br>11i<br>q)hopen 5001<br>12i<br>q)h&quot;.ipc.connections&quot;<br>handle| time                          user   id         state<br>------| -----------------------------------------------------<br>9     | 2024.11.21D17:12:13.572488665 mwoods Client5000 open <br>10    | 2024.11.21D17:12:18.428053708 mwoods Client5000 open <br>11    | 2024.11.21D17:12:19.434530122 mwoods Client5000 open <br>12    | 2024.11.21D17:12:20.217362997 mwoods Client5000 open</pre><h4>Connection Closures with .z.pc</h4><p>When a connection is closed, you can update the state or remove the connection from the list:</p><pre>q)h&quot;.z.pc:{`.ipc.connections upsert `handle`time`state!(x;.z.p;`close)}&quot;<br>q)hclose 9i<br>q)h&quot;.ipc.connections&quot;<br>handle| time                          user   id         state<br>------| -----------------------------------------------------<br>9     | 2024.11.21D17:13:36.937625898 mwoods Client5000 close<br>10    | 2024.11.21D17:12:18.428053708 mwoods Client5000 open <br>11    | 2024.11.21D17:12:19.434530122 mwoods Client5000 open <br>12    | 2024.11.21D17:12:20.217362997 mwoods Client5000 open </pre><p>You can see that after closing handle 9i that the state has changed from open to close. This ensures a complete log of open and closed connections.</p><p>Note that in this case the handle 9i on client matched handle 9i on server but this is a coincidence, the number is not not guaranteed to be same on either end. You could run this same and see a different handle has closed. To check the handle to close you can run 9&quot;.z.w&quot; first, then close the handle returned.</p><h3>Step 3: Restricting Queries with .z.pg</h3><p>The .z.pg event handler can be used to control access to specific users. For example, you can restrict certain users from executing queries based on their class or permission level. Let’s take a look at the class column in the users table.</p><pre>user| class     password<br>----| ------------------<br>mary| basicUser &quot;pwd&quot;   <br>john| superUser &quot;pwd&quot;   <br>ann | basicUser &quot;pwd&quot; </pre><p>This ensures that only users with the superUser class can run certain queries, while others are restricted.</p><p>Before we do anything further, let’s see if our users John &amp; Mary still have access to connect.</p><pre>q)johnHandle:hopen `::5001:john:pwd<br>q)maryHandle:hopen `::5001:mary:pwd</pre><p>Now let&#39;s define .z.pg to allow any superUser connecting to run their query but prevents basicUsers from doing so.</p><pre>q)h&quot;.z.pg:{[query]class:.perm.users[.z.u][`class]; <br>         $[class~`superUser;<br>           value query;<br>           \&quot;No Permissions\&quot;]}&quot;</pre><p>Let&#39;s re-run as John &amp; Mary again:</p><pre>q)johnHandle&quot;2+2&quot;     // all ok <br>4<br><br>q)maryHandle&quot;2+2&quot;     // not ok anymore<br>&quot;No Permissions&quot;</pre><p>As Mary only has the class basicUser she is not allowed to run her query on the process. This is a very basic example of how .z.pg can be modified to restrict access to incoming queries.</p><h3>Other Event Handlers</h3><h4>Asynchronous Message Handler — .z.ps</h4><p>The <strong>asynchronous message handler</strong> (.z.ps) is similar to the synchronous message handler (.z.pg), but with a key difference: when .z.ps is invoked, it <strong>does not return a result</strong> to the calling process. Even if the function defined within .z.ps explicitly specifies a return value, that value won&#39;t be returned to the caller.</p><h4>Firewalling with .z.ps</h4><p>When you need to prevent external connections from invoking asynchronous messages, .z.ps can be used as a security measure. By assigning an empty function to .z.ps, you can effectively block asynchronous messages.</p><p>For example, setting:</p><pre>q)h&quot;.z.ps:{}&quot;  // Disables asynchronous message handling</pre><p>This prevents any asynchronous requests from being executed, acting as a form of firewall to protect your system.</p><h4>Event Handlers for HTTP — .z.ph</h4><p>When handling HTTP connections, .z.ph is the default event handler. This handler manages HTTP queries by composing HTML pages, executing queries, and formatting results into an HTML table. You can supplement or completely redefine .z.ph if needed.</p><h3>Real World Application : Formula 1 Capstone Project</h3><p>To apply all these concepts in a real-world context, the <a href="https://learninghub.kx.com/courses/kdb-developer-level-3/lessons/advanced-ipc/"><strong>Formula 1 Motorsports Project</strong></a> involves securing the infrastructure of an F1 racing team where you’re tasked with securing the infrastructure for an F1 racing team.</p><p>For example:</p><ul><li>Create a secure API for real-time telemetry.</li><li>Encrypt sensitive data like passwords using SHA-1 hashing.</li><li>Ensure only authorized engineers can modify race strategies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*-9CSnHORIlZg9N7aPROf_A.png" /></figure><p>This project ties together everything we’ve covered, showing how to secure a kdb+ system in a high-stakes environment.</p><p><strong>Try the Capstone Project to put these principles in this article into practice and secure the system for a Formula 1 racing team!</strong></p><h3>Conclusion: Take Control of Your kdb+ Security</h3><p>Even if you rely on KX’s commercial solutions for enterprise-grade security, understanding the fundamentals of kdb+ permissions is invaluable. By customizing .z handlers, you can:</p><ul><li>Secure your system against unauthorized access.</li><li>Log and monitor connections.</li><li>Enforce role-based query restrictions.</li></ul><p>Start experimenting with these techniques today to take your kdb+ system’s security to the next level. For more advanced needs, explore <a href="http://code.kx.com/">KX’s</a> offerings to complement your foundational knowledge, <a href="https://kx.com/kdb-personal-edition-download/">download kdb+</a> to get started or reach out to ask any questions on our <a href="http://kx.com/slack">Slack community</a>.</p><h3>Further Reading</h3><ul><li><a href="https://kx.com/blog/kdb-q-insights-deferred-response/">Deferred Response with kdb+</a></li><li><a href="https://code.kx.com/q/wp/permissions/">Permissions with kdb+</a></li><li><a href="https://code.kx.com/q/wp/websockets/">KDB+ and WebSockets</a></li><li><a href="https://code.kx.com/q/wp/socket-sharding/">Socket sharding with kdb+ and Linux</a></li><li><a href="https://code.kx.com/q/kb/callbacks/">KDB+ and Callbacks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3516bc7355d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kx-systems/kdb-security-made-simple-how-to-protect-your-data-with-permissions-and-access-control-3516bc7355d4">kdb+ Security Made Simple: How to Protect Your Data with Permissions and Access Control</a> was originally published in <a href="https://medium.com/kx-systems">KX Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where do I even start learning kdb+?]]></title>
            <link>https://medium.com/kx-systems/where-do-i-even-start-learning-kdb-71d464d8969e?source=rss-972021150910------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d464d8969e</guid>
            <category><![CDATA[kdb]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Michaela Woods]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 20:38:32 GMT</pubDate>
            <atom:updated>2024-12-12T19:03:33.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDrpEJKRLJWBGT6ibx65eQ.png" /></figure><p>I often get asked: <strong><em>Where do I even start with kdb+?</em></strong> Honestly, my answer always depends — on who you are and what you’re trying to achieve. Are you a developer diving into time-series data? A data engineer setting up systems? Or maybe just someone curious about how to query kdb+ databases?</p><p>To make it easier, I’ve decided to put all my go-to recommendations into one place. Whether you’re just testing the waters or ready to go deep, here’s how you can kickstart your kdb+ journey with <a href="https://learninghub.kx.com/academy/"><strong>KX Academy</strong></a> — a free, interactive learning platform designed for every skill level.</p><h3>What’s kdb+ Anyway?</h3><p>At its core, <a href="https://code.kx.com/q/learn/install/">kdb+</a> is a high-performance, time-series database from <a href="http://kx.com/">KX</a>, built to handle massive datasets. It’s a powerhouse in fields like finance, IoT, and real-time analytics. And one of its secret sauces is the query language, <strong>q</strong>, which is super-efficient at slicing and dicing data.</p><p>But let’s face it — learning something new can be daunting. That’s where KX Academy comes in, offering interactive courses that walk you through the basics all the way to advanced topics. Plus, no installs or setups needed — it’s all cloud-based.</p><h3>Learning Paths for Every Goal</h3><p>The way I see it, there are a few main learning paths you can take when it comes to kdb+, so I’ve outlined them below to help you figure out where to begin. No matter where you’re starting or what you’re aiming for, KX Academy’s got you covered. Here’s a breakdown of the main paths:</p><p><strong>1. Quick Querying for Beginners</strong></p><p>If your goal is to quickly query an existing kdb+ database and analyze data, KX Academy offers a perfect starting point with the <a href="https://learninghub.kx.com/courses/kdb-developer-level-1/"><strong>kdb+ Level 1 Course</strong></a>. This course is designed to give a hands-on, practical introduction to querying data using qSQL, without diving too deep into the language’s underlying principles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDfRB4xNo6d07PVsEPF53A.png" /></figure><p><strong>What’s Inside:</strong></p><ul><li>Preloaded datasets to start querying instantly.</li><li>Basics of <strong>qSQL</strong> (think SQL but turbocharged): filtering rows, joining tables, and navigating kdb+ structures.</li><li>Bite-sized video tutorials for visual learners.</li><li>No setup — use the Jupyter-based sandbox for hands-on practice</li><li>Lots of exercises and solutions to test what you’ve just learned!</li><li>Straightforward, practical, and gets you querying real-world data fast.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfmKuswsW9VPt9A1-h0nGQ.png" /></figure><p>This one’s ideal if you’re a quant, data analyst or developer who just needs to query and analyze data, without mastering the whole language straight away.</p><p><strong>2. Building a Data Capture System</strong></p><p>If you’re interested in building a kdb+ data capture system, KX Academy has a new course designed just for you: <a href="https://learninghub.kx.com/courses/kdb-architecture/"><strong>kdb+ Architecture for Real-Time Data Capture</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTRK5pl6lJvBOtjpgdg_UA.png" /></figure><p><strong>What You’ll Learn:</strong></p><ul><li>The architecture of a real-time kdb+ system — from scratch!</li><li>Customize architecture by adding data feeds and feedhandlers.</li><li>Implementing custom streaming analytics for real time analysis.</li><li>Understand custom end of day behavior.</li><li>Advanced data retrieval and setting up query gateways.</li><li>Beginner-friendly, no prior experience with q required.</li></ul><p>This one is perfect for data engineers and operations folks who need to focus on system setup, where understanding the architecture of kdb+ is more important than mastering the language itself.</p><p><strong>3. Becoming a kdb+ Developer</strong></p><p>For those who want to learn the q language in detail and become proficient kdb+ developers, KX Academy offers a comprehensive learning path through <a href="https://learninghub.kx.com/courses/kdb-developer-level-2/"><strong>kdb+ Level 2</strong></a><strong> </strong>and<strong> </strong><a href="https://learninghub.kx.com/courses/kdb-developer-level-3/"><strong>Level 3</strong></a> courses. These courses are designed to give you a deep understanding of the language, its data structures, and its applications in real-world development tasks.</p><p><strong>What You’ll Learn:</strong></p><ul><li>From atoms and lists to advanced concepts like database structure and maintenance, memory management and query optimization.</li><li>Hands-on end of course capstone projects, like optimizing a Formula 1 team’s database or building analytics for an investment bank.</li><li>The capstones put all the concepts you have learned to the test in a real world challenge complete with automated testing and feedback to keep you on track.</li><li>By the end, you’ll be a pro at handling large datasets and writing efficient q code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlLeHZmLoOs-LCPiRmI3nw.png" /></figure><p>If you’re serious about becoming a kdb+ developer, these advanced courses are the perfect way to deepen your knowledge and expertise.</p><p><strong>4. Python First Approach with PyKX</strong></p><p><a href="https://code.kx.com/pykx/3.0/"><strong>PyKX</strong></a> is an essential tool for Python developers who want to harness the power of kdb+ without needing to learn the q language initially. PyKX enables you to interact with kdb+ directly from Python, making it much easier to integrate kdb+ into your existing Python-based workflows. The <a href="https://learninghub.kx.com/courses/introduction-to-pykx/">Introduction to PyKX</a> course is a great place to start getting hands on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGMjDQS3aDfqvZX-7VJtow.png" /></figure><p><strong>What You’ll Learn:</strong></p><ul><li>Importing and exporting data to and from kdb+.</li><li>Running kdb+ queries directly from Python.</li><li>Integrating Python with kdb+ for real-time data analysis, visualization, and more.</li></ul><p>By leveraging PyKX, you can take advantage of kdb+’s speed and efficiency while working within a familiar Python environment, whether you’re a data scientist, engineer, or developer.</p><h4>Extra Tools and Resources</h4><p>Want to go beyond just querying or coding? KX Academy offers more:</p><ul><li><a href="https://learninghub.kx.com/courses/introduction-to-kx-dashboards/"><strong>KX Dashboards</strong>:</a> Learn to visualize your data like a pro.</li><li><a href="https://learninghub.kx.com/forums/"><strong>Discussion Forum</strong>:</a> Ask questions, share tips, and connect with seasoned devs in the kdb+ space.</li><li><a href="http://kx.com/slack"><strong>Slack Channel:</strong></a><strong> </strong>Reach out to chat 1:1 with our community experts if you have any questions.</li></ul><h3>What People Are Saying</h3><p><em>“Overall, this kdb architecture course was excellent. It provided a comprehensive overview of the core principles and offered valuable insights into designing and maintaining production-ready kdb systems.”</em></p><p><em>“Very nice intro course, I really enjoyed it. Great pacing and nice density of content.”</em></p><p><em>“The tutorials are brilliant, Really Easy To Follow..Michaela has done a great job.. Can’t wait to get up-to speed with this software, really enjoying everything about it.”</em></p><h3>Final Thoughts</h3><p>No matter your goal — whether you’re looking to quickly query data, build a kdb+ system, or become a kdb+ developer — KX Academy has a course designed for you. Start with the <a href="https://learninghub.kx.com/courses/kdb-developer-level-1/"><strong>kdb+ Level 1</strong></a><strong> </strong>course if you’re just getting started, explore the <a href="https://learninghub.kx.com/courses/kdb-architecture/"><strong>real-time data capture architecture</strong></a> course if you want to build something practical quickly, dive into <a href="https://learninghub.kx.com/courses/kdb-developer-level-2/"><strong>Level 2</strong></a><strong> </strong>and<strong> </strong><a href="https://learninghub.kx.com/courses/kdb-developer-level-3/"><strong>Level 3</strong> </a>if you’re ready to master the language and become a kdb+ developer, or the <a href="https://learninghub.kx.com/courses/introduction-to-pykx/">PyKX</a> course if you want to interact with kdb+ directly from Python.</p><p>Start your journey into kdb+ and real-time data analytics today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d464d8969e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kx-systems/where-do-i-even-start-learning-kdb-71d464d8969e">Where do I even start learning kdb+?</a> was originally published in <a href="https://medium.com/kx-systems">KX Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading, Partitioning, and Querying Parquet Data in kdb+]]></title>
            <link>https://medium.com/kx-systems/loading-partitioning-and-querying-parquet-data-in-kdb-0d4cfd9ec2d7?source=rss-972021150910------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d4cfd9ec2d7</guid>
            <category><![CDATA[apache-arrow]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[kdb]]></category>
            <dc:creator><![CDATA[Michaela Woods]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:53:18 GMT</pubDate>
            <atom:updated>2025-01-30T15:30:23.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtgAiE1U60dGtM265nrfDw.png" /></figure><p>Handling large datasets efficiently is crucial for data engineers, and one of the most effective ways to achieve this is by using partitioned databases. In this post, we’ll explore how to load the <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page">NYC Taxi and Limousine Commission (TLC) Trip Record</a> data (available in Parquet format) into a kdb+ database. We’ll utilize the <a href="https://github.com/KxSystems/arrowkdb"><strong>arrowkdb</strong></a> interface, which bridges the gap between Apache Arrow and kdb+, enabling us to load Parquet files seamlessly into a kdb+ database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7a-O8N9zMHcwlkLgXQffIQ.png" /><figcaption>Parquet to kdb+ using arrowkdb</figcaption></figure><p>By the end of this tutorial, you’ll be able to load, partition, and analyze your own large Parquet datasets using kdb+.</p><p>To follow along with this tutorial, you’ll need:</p><ul><li><strong>kdb+</strong> installed (see <a href="https://code.kx.com/q/learn/install/">documentation</a> for setup details and to sign up for a free trial).</li><li><strong>arrowkdb:</strong> This library is essential for reading Parquet files into kdb+ tables. You can find installation instructions <a href="https://github.com/KxSystems/arrowkdb">here on GitHub</a>.</li><li><strong>NYC TLC Trip Data:</strong> Download the 2023 Parquet files from the <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page">NYC TLC website.</a> The data is free to use. For this example, I have used the files for January, February, and March of 2023.</li></ul><h3>Loading Parquet Files into kdb+ with arrowkdb</h3><p><a href="https://parquet.apache.org/">Apache Parquet</a> is a popular format for big data because it provides efficient storage and compression. By using <strong>arrowkdb</strong>, we can read Parquet files directly into kdb+, leveraging the performance benefits of both the Parquet format and kdb+’s in-memory data processing.</p><p>Start by loading the <strong>arrowkdb</strong> library to your instance of kdb+.</p><pre>q)system&quot;l arrowkdb.q&quot;</pre><p>Before loading the file directly into memory, it can be a good idea to first check how many rows of data there is in each file on average so we can make an informed decision on how best to store it.</p><p>We can use the built in <strong>readParquetRowGroupsToTable</strong> API to check the number of records in the Parquet file.</p><pre>q)file:&quot;yellow_tripdata_2024-06.parquet&quot;<br>q)count .arrowkdb.pq.readParquetRowGroupsToTable[file;::;::;::]<br><br>3539193 </pre><p>Fortunately, kdb+ offers a number of different methods to store tables which will allow for efficient storage and querying for different sized datasets: flat, splayed, partitioned and segmented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*mSuH4IaGvqxm-VPCTs37cA.png" /><figcaption>On disk table types in kdb+</figcaption></figure><p>A general rule of thumb around which format to choose depends on three things:</p><ul><li><strong>Will the table continue to grow at a fast rate?</strong> — if not, then flat or splayed depending on the size, if yes then partitioned or segmented depending on data volumes</li><li><strong>Am I working in a RAM constrained environment?</strong> — if yes, then you may prefer to store your reference tables as splayed rather than flat format. Flat table require all the data be read into memory before use, while splayed table only retrieve table rows after applying the qSQL constraints.</li><li><strong>What level of performance do I want?</strong> — if high performance is central to the system and there are additional disk mounts available, a well structured segmented database can avoid some of the I/O competition that a partitioned table on one disk mount would face for the same query.</li></ul><p>Given the taxi Parquet files contains <strong>~3 million rows per month</strong>, <a href="https://code.kx.com/q/kb/partition/">partitioning</a> by <strong>month</strong> will be a good approach. Without partitioning, queries that span large time periods would require scanning entire datasets, which can be very slow and resource-intensive. By partitioning data, kdb+ can limit the query scope to the relevant partitions, significantly speeding up the process.</p><p>If the dataset contained significantly more rows (e.g. millions of rows per day), we might have chosen to partition by <strong>day</strong> or even <strong>hour</strong>. However, since the dataset fits well into monthly partitions, partitioning by <strong>month</strong> offers a good balance between query performance and manageability.</p><p><strong><em>To learn more about partitioning in kdb+ check out the free </em></strong><a href="https://learninghub.kx.com/courses/kdb-developer-level-3/"><strong><em>KX Academy module</em></strong></a><strong><em>.</em></strong></p><p>Next, we define a function <strong>parseMonth</strong> that extracts the month from the filename, which we’ll use as the partition key for saving the data.</p><pre>q)files:(&quot;yellow_tripdata_2024-06.parquet&quot;; <br>         &quot;yellow_tripdata_2024-07.parquet&quot;;<br>         &quot;yellow_tripdata_2024-08.parquet&quot;)<br>q)parseMonth:{[file]&quot;M&quot;$7#last &quot;_&quot; vs ssr[file;&quot;-&quot;;&quot;.&quot;]}<br>q)parseMonth each files<br> <br>2024.06 2024.07 2024.08m </pre><p>This function splits the filename and grabs the month (e.g., “yellow_tripdata_2024–06.parquet “ becomes “ 2024–06m”).</p><p>Next, we define <strong>readFile</strong> to read each Parquet file, leveraging <strong>arrowkdb</strong>’s <strong>readParquetToTable</strong> to load the data into a kdb+ table. One extra step here is filtering out only the records for the specified month, since some files contain extra dates outside of the month indicated in the filename. This ensures each partition is accurate and only contains data relevant to that month.</p><pre>q)readFile:{[file;month]<br>     t:.arrowkdb.pq.readParquetToTable[file;::];<br>     select from t where tpep_dropoff_datetime.month=month<br>   }</pre><p>Additionally, the arrowkdb interface offers a <strong>writeParquetFromTable </strong>function that can convert a kdb+ table to an Arrow table and then write it to a Parquet file.</p><p>Let’s load in the first file so we can take a quick look at the schema of the table, we use the <strong>meta</strong> function to inspect the schema in kdb+.</p><pre>q)taxi:readFile[files[0];parseMonth files[0]]<br>q)meta taxi<br><br>c                    | t f a<br>---------------------| -----<br>VendorID             | i    <br>tpep_pickup_datetime | p    <br>tpep_dropoff_datetime| p    <br>passenger_count      | j    <br>trip_distance        | f    <br>RatecodeID           | j    <br>store_and_fwd_flag   | C    <br>PULocationID         | i    <br>DOLocationID         | i    <br>payment_type         | j    <br>fare_amount          | f    <br>extra                | f    <br>mta_tax              | f    <br>tip_amount           | f    <br>tolls_amount         | f    <br>improvement_surcharge| f    <br>total_amount         | f    <br>congestion_surcharge | f    <br>Airport_fee          | f</pre><p>The <strong>arrowkdb</strong> interface has inferred the column name and datatypes using the <a href="https://github.com/KxSystems/arrowkdb/blob/main/docs/arrow-types.md">type mapping</a> between Arrow and kdb+. You can change any of these datatypes before saving down to disk using <a href="https://code.kx.com/q/ref/cast/">casting</a>, as well as making any desired changes like renaming the columns or filtering out certain rows/columns you don’t need.</p><p>Once you are happy with the table contents, you can save it table to the partitioned database using <a href="https://code.kx.com/q/ref/dotq/#dpft-save-table">.Q.dpft</a>. This function writes data to the database, parting it by the VendorID column, with partitions specified by the months. We create a new function called <strong>saveDB </strong>that parses the month from the filename, reads the file and saves it to disk.</p><pre>q)saveDB:hsym `$&quot;/home/arrowkdb/data&quot;<br><br>q)saveFile:{[file]<br>     month:parseMonth file;<br>     taxi::readFile[file;month];<br>     .Q.dpft[saveDB;month;`VendorID;`taxi]<br>   }<br><br>q)saveFile each files</pre><p>We’ve now saved three months of NYC Taxi data into a partitioned kdb+ database! Each table has been partitioned by the month, making it easier to run time-based queries, such as filtering by month or analyzing trends across time periods.</p><h3>Querying kdb+ data with q and Python (PyKX)</h3><p>After we’ve successfully loaded and partitioned the data, we now turn our attention to querying the partitioned database. By utilizing kdb+’s high-performance query language q and Python interface <a href="https://kx.com/developers/developer-tools/?section=pykx">PyKX</a>, we can efficiently filter, aggregate, and analyze the data. In this section, we will demonstrate how to run aggregations and perform trend analysis on the NYC Taxi data, making use of the partitioning strategy we implemented earlier.</p><p>Let’s load this partitioned data into memory allowing us to query it, and see how many rows there are for each month:</p><pre>q)system&quot;l data&quot;<br>q)select count i by month from taxi<br><br>month  | x      <br>-------| -------<br>2024.06| 3538367<br>2024.07| 3076044<br>2024.08| 2977905</pre><p>You might notice this <strong>month</strong> column is newly added in the partitioning step. When querying a large partitioned database, it is important to include the partition (in our case <strong>month</strong>) as the first constraint in the clause. This speeds up queries, as kdb+ only has to search through the specified partitions, as opposed to all of them.</p><p>Alternatively, we can aggregate data across all partitions without needing to pass the partition as the first constraint. Let’s calculate the <strong>total fare amount</strong>, <strong>total tip amount</strong>, and <strong>trip count</strong> per day. This summary provides insight into daily patterns in fare and tipping behavior across different days in each month.</p><pre>q)select sum fare_amount,<br>         sum tip_amount,<br>         num_trips:count i<br>   by tpep_dropoff_datetime.date <br>   from taxi <br><br>date      | fare_amount tip_amount num_trips<br>----------| --------------------------------<br>2024.06.01| 2369774     367174.7   128508   <br>2024.06.02| 2310844     368190.2   108614   <br>2024.06.03| 2168822     384829.4   109614      <br>.. </pre><p>This summary allows us to track daily fare and tip totals, giving a view into high and low demand days across the month.</p><p>Next, let’s take a look at how to query this partitioned data both using <strong>Python</strong> (PyKX), the Python interface to kdb+, and visualize insights with popular libraries like <strong>Matplotlib</strong>.</p><p>PyKX installation can be as simple as <strong>pip install pykx</strong>, with full instructions covered in the <a href="https://code.kx.com/pykx/2.3/getting-started/installing.html">documentation</a>. Once installed, import the library and map the partitioned database we created above to make it available to PyKX.</p><pre>import pykx as kx<br>db=kx.DB(path=&#39;/home/arrowkdb/data&#39;)</pre><p>Next, let’s run another aggregation query this time grouping by hourly amounts instead of days.</p><pre>col=kx.Column<br>tab=db.taxi.select( <br>        columns = col(&#39;fare_amount&#39;).sum() &amp;<br>                  col(&#39;tip_amount&#39;).sum() &amp;<br>                  col(&#39;tip_amount&#39;).count().name(&#39;num_trips&#39;), <br>        by=col(&#39;tpep_dropoff_datetime&#39;).hour.name(&#39;hour&#39;))<br>tab.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*at1zuLaemW8iPM-4mW4EwQ.png" /><figcaption>Hourly stats for taxi table</figcaption></figure><p>Finally, let’s plot these results using <strong>Matplotlib</strong> to see how they look during the day. We should convert the table to a Pandas DataFrame for easy plotting.</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>df=tab.pd()<br>df = df.reset_index()<br><br># Set up the plot<br>plt.figure(figsize=(12, 6))<br><br># Plot each metric by hour<br>plt.plot(df[&#39;hour&#39;], df[&#39;fare_amount&#39;], label=&#39;Fare Amount&#39;, color=&#39;blue&#39;)<br>plt.plot(df[&#39;hour&#39;], df[&#39;tip_amount&#39;], label=&#39;Tip Amount&#39;, color=&#39;green&#39;)<br>plt.plot(df[&#39;hour&#39;], df[&#39;num_trips&#39;], label=&#39;Number of Trips&#39;, color=&#39;orange&#39;)<br><br># Add titles and labels<br>plt.title(&#39;NYC Taxi Data by Hour&#39;)<br>plt.xlabel(&#39;Hour of Day&#39;)<br>plt.ylabel(&#39;Amount&#39;)<br>plt.legend()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*9F-bstG41oOz5fb2QoKQLw.png" /><figcaption>NYC Taxi data by hour</figcaption></figure><p>The data shows that while the number of taxi trips is steady, <strong>fare and tip amounts increase significantly in the afternoon and early evening hours</strong>, likely reflecting longer trips or higher demand during these times. This pattern can provide insights into high-demand periods, which may be useful for scheduling and resource allocation for NYC taxi services.</p><h3>Wrapping Up</h3><p>This tutorial has demonstrated how to efficiently load, partition, and query large Parquet datasets in kdb+ using the <strong>arrowkdb</strong> interface. One of the key advantages of using kdb+ for partitioning is its ability to manage large volumes of time-series data efficiently. By partitioning data based on time (such as monthly or hourly), kdb+ allows you to quickly query specific time ranges, significantly reducing query latency.</p><p>We also showcased how to run aggregations, analyze trends, and visualize the data using q, Python (PyKX) and popular libraries like Matplotlib. With these techniques, you’ll be well-equipped to handle large-scale datasets in kdb+ and extract meaningful insights.</p><p><strong>To try out this tutorial s</strong><a href="https://kx.com/kdb-personal-edition-download/"><strong>ign up for kdb+</strong></a><strong> for free today! Also, you can reach out to us on </strong><a href="http://kx.com/slack"><strong>Slack</strong></a><strong> to chat 1:1 with our community experts if you have any questions.</strong></p><p>Happy querying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d4cfd9ec2d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kx-systems/loading-partitioning-and-querying-parquet-data-in-kdb-0d4cfd9ec2d7">Loading, Partitioning, and Querying Parquet Data in kdb+</a> was originally published in <a href="https://medium.com/kx-systems">KX Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>