Skip to content

Instantly share code, notes, and snippets.

@jorgemanrubia
Created January 15, 2023 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgemanrubia/b9c7463cb22ebc01143e09310d841234 to your computer and use it in GitHub Desktop.
Save jorgemanrubia/b9c7463cb22ebc01143e09310d841234 to your computer and use it in GitHub Desktop.
ChatGPT prompt 5
class Bar
attr_accessor :time, :open, :high, :low, :close, :volume
def initialize(time, open, high, low, close, volume)
@time = time
@open = open
@high = high
@low = low
@close = close
@volume = volume
end
end
require 'csv'
require 'date'
class BarReader
include Enumerable
def initialize(from_date, to_date)
@from_date = from_date
@to_date = to_date
end
def each
Dir.glob("*.zip") do |file|
date = Date.parse(file.split("_")[0])
if date >= @from_date && date <= @to_date
CSV.foreach(file, headers: false) do |row|
time, open, high, low, close, volume = row
yield Bar.new(time, open, high, low, close, volume)
end
end
end
end
end
I have a directory with ZIP files with this format:
20050906_trade.zip
20050907_trade.zip
20050908_trade.zip
Where the first segment of the file name correspond with a date. That date represents a day with the minute bar data for the corresponding date and security. If you open the ZIP file you would find a CSV file with this format:
0,3847.50,3847.50,3847.00,3847.50,91
60000,3847.25,3847.50,3847.25,3847.25,106
120000,3847.25,3847.25,3846.75,3847.00,114
180000,3846.75,3846.75,3846.25,3846.25,78
The columns are, in this order, date (milliseconds from midnight), open, high, low, close and volume.
I would like to create two classes. A “Bar” class that captures a single OHLC bar that also includes the time and volume. And a “BarReader” class that you can use like this:
```
from_date = Date.parse("2021-01-1")
to_date = Date.parse("2022-01-1")
bar_reader = BarReader.new(from_date, to_date)
bars = bar_reader.to_a
```
In that example, “bars” would contain all the bars read from the corresponding files between the 2021-01-1 and 2022-01-1. I’d like to implement the “BarReader” class with an “each” method and include Enumerable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment