Sheldon  Grant

Sheldon Grant


How to Grab The UNIX Timestamp in JavaScript

Getting the timestamp using JavaScript

When you create a new Date instance using the constructor, JavaScript will return date and time represented in human-readable format:

const date = new Date("01/20/2021");
console.log(date); // Wed Jan 20 2021 00:00:00

The Date object instance already contains the Number value that represents milliseconds since 1 January 1970 UTC. When you need the UNIX timestamp representation of the date, you can call the valueOf() method on the Date instance.

Here’s an example:

const date = new Date("01/20/2021");
console.log(date.valueOf()); // 1611075600000

Or if you want the representation of the current time, you can use the method as follows:

const date =;
console.log(date); // 1620483960166

The UNIX timestamp above are expressed in milliseconds, you if you want it to be expressed in seconds, you need to divide the value by one thousand. Also, wrap the operation with the Math.floor() method so that the value returned will round down to the last second.

const date = new Date("01/20/2021").valueOf();
const seconds = Math.floor(date / 1000);
console.log(seconds); // 1611075600

Finally, you can also write the shortest syntax to get the current timestamp by using the unary operator + before the Date constructor as follows:

console.log(+new Date()); // return the current UNIX timestamp
console.log(+new Date("01/20/2021")); // 1611075600000

And that’s how you can retrieve the UNIX timestamp using JavaScript 😉

Original article source at:

#javascript #time 

How to Grab The UNIX Timestamp in JavaScript

It's Editing-time, Do You Know Where Your Methods Are?


CodeTracking can be thought of as an extension of Julia's InteractiveUtils library. It provides an interface for obtaining:

  • the strings and expressions of method definitions
  • the method signatures at a specific file & line number
  • location information for "dynamic" code that might have moved since it was first loaded
  • a list of files that comprise a particular package.

CodeTracking is a minimal package designed to work with Revise.jl (for versions v1.1.0 and higher). CodeTracking is a very lightweight dependency.


@code_string and @code_expr

julia> using CodeTracking, Revise

julia> print(@code_string sum(1:5))
function sum(r::AbstractRange{<:Real})
    l = length(r)
    # note that a little care is required to avoid overflow in l*(l-1)/2
    return l * first(r) + (iseven(l) ? (step(r) * (l-1)) * (l>>1)
                                     : (step(r) * l) * ((l-1)>>1))

julia> @code_expr sum(1:5)
[ Info: tracking Base
    #= toplevel:977 =#
    function sum(r::AbstractRange{<:Real})
        #= /home/tim/src/julia-1/base/range.jl:978 =#
        l = length(r)
        #= /home/tim/src/julia-1/base/range.jl:980 =#
        return l * first(r) + if iseven(l)
                    (step(r) * (l - 1)) * l >> 1
                    (step(r) * l) * (l - 1) >> 1

@code_string succeeds in that case even if you are not using Revise, but @code_expr always requires Revise. (If you must live without Revise, you can use Meta.parse(@code_string(...)) as a fallback.)

"Difficult" methods are handled more accurately with @code_expr and Revise. Here's one that's defined via an @eval statement inside a loop:

julia> @code_expr Float16(1) + Float16(2)
:(a::Float16 + b::Float16 = begin
          #= /home/tim/src/julia-1/base/float.jl:398 =#
          Float16(Float32(a) + Float32(b))

whereas @code_string cannot return a useful result:

julia> @code_string Float16(1) + Float16(2)
"# This file is a part of Julia. License is MIT:\n\nconst IEEEFloat = Union{Float16, Float32, Float64}"

Consequently it's recommended to use @code_expr in preference to @code_string wherever possible.

@code_expr and @code_string have companion functional variants, code_expr and code_string, which accept the function and a Tuple{T1, T2, ...} of types.

@code_expr and @code_string are based on the lower-level function definition; you can read about it with ?definition.

Location information

julia> using CodeTracking, Revise

julia> m = @which sum([1,2,3])
sum(a::AbstractArray) in Base at reducedim.jl:648

julia> Revise.track(Base)  # also edit reducedim.jl

julia> file, line = whereis(m)
("/home/tim/src/julia-1/usr/share/julia/base/reducedim.jl", 642)

julia> m.line

In this (ficticious) example, sum moved because I deleted a few lines higher in the file; these didn't affect the functionality of sum (so we didn't need to redefine and recompile it), but it does change the starting line number of the file at which this method appears. whereis reports the current line number, and m.line the old line number. (For technical reasons, it is important that m.line remain at the value it had when the code was lowered.)

Other methods of whereis allow you to obtain the current position corresponding to a single statement inside a method; see ?whereis for details.

CodeTracking can also be used to find out what files define a particular package:

julia> using CodeTracking, Revise, ColorTypes

julia> pkgfiles(ColorTypes)
PkgFiles(ColorTypes [3da002f7-5984-5a60-b8a6-cbb66c0b333f]):
  basedir: /home/tim/.julia/packages/ColorTypes/BsAWO
  files: ["src/ColorTypes.jl", "src/types.jl", "src/traits.jl", "src/conversions.jl", "src/show.jl", "src/operations.jl"]

You can also find the method-signatures at a particular location:

julia> signatures_at(ColorTypes, "src/traits.jl", 14)
1-element Array{Any,1}:

julia> signatures_at("/home/tim/.julia/packages/ColorTypes/BsAWO/src/traits.jl", 14)
1-element Array{Any,1}:

CodeTracking also helps correcting for Julia issue #26314:

julia> @which uuid1()
uuid1() in UUIDs at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\UUIDs\src\UUIDs.jl:50

julia> CodeTracking.whereis(@which uuid1())
("C:\\Users\\SomeOne\\AppData\\Local\\Julia-1.1.0\\share\\julia\\stdlib\\v1.1\\UUIDs\\src\\UUIDs.jl", 50)

A few details

CodeTracking has limited functionality unless the user is also running Revise, because Revise populates CodeTracking's internal variables. (Using whereis as an example, CodeTracking will just return the file/line info in the method itself if Revise isn't running.)

CodeTracking is perhaps best thought of as the "query" part of Revise.jl, providing a lightweight and stable API for gaining access to information it maintains internally.

Download Details:

Author: Timholy
Source Code: 
License: MIT license

#julia #methods #time 

It's Editing-time, Do You Know Where Your Methods Are?
Nat  Grady

Nat Grady


Quantmod: Quantitative Financial Modelling Framework


quantmod is an R package that provides a framework for quantitative financial modeling and trading. It provides a rapid prototyping environment that makes modeling easier by removing the repetitive workflow issues surrounding data management and visualization.

quantmod for enterprise

Available as part of the Tidelift Subscription.

The maintainers of quantmod and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Supporting quantmod development

If you are interested in supporting the ongoing development and maintenance of quantmod, please consider becoming a sponsor.


The current release is available on CRAN, which you can install via:


To install the development version, you need to clone the repository and build from source, or run one of:

# lightweight
# or

You may need tools to compile C, C++, or Fortran code. See the relevant appendix in the R Installation and Administration manual for your operating system:

Getting Started

It is possible to import data from a variety of sources with one quantmod function: getSymbols(). For example:

> getSymbols("AAPL", src = "yahoo")    # from yahoo finance
[1] "AAPL"
> getSymbols("DEXJPUS", src = "FRED")  # FX rates from FRED

Once you've imported the data, you can use chartSeries() to visualize it and even add technical indicators from the TTR package:

> getSymbols("AAPL")
[1] "AAPL"
> chartSeries(AAPL)
> addMACD()
> addBBands()

Have a question?

Ask your question on Stack Overflow or the R-SIG-Finance mailing list (you must subscribe to post).


Please see the contributing guide.

See Also

  • TTR: functions for technical trading rules
  • xts: eXtensible Time Series based on zoo


Jeffrey Ryan, Joshua Ulrich

Download Details:

Author: joshuaulrich
Source Code: 
License: GPL-3.0 license

#r #finance #time #data #import 

Quantmod: Quantitative Financial Modelling Framework

Now: A Time toolkit for Golang


Now is a time toolkit for golang


go get -u


Calculating time based on current time

import ""

time.Now() // 2013-11-18 17:51:49.123456789 Mon

now.BeginningOfMinute()        // 2013-11-18 17:51:00 Mon
now.BeginningOfHour()          // 2013-11-18 17:00:00 Mon
now.BeginningOfDay()           // 2013-11-18 00:00:00 Mon
now.BeginningOfWeek()          // 2013-11-17 00:00:00 Sun
now.BeginningOfMonth()         // 2013-11-01 00:00:00 Fri
now.BeginningOfQuarter()       // 2013-10-01 00:00:00 Tue
now.BeginningOfYear()          // 2013-01-01 00:00:00 Tue

now.EndOfMinute()              // 2013-11-18 17:51:59.999999999 Mon
now.EndOfHour()                // 2013-11-18 17:59:59.999999999 Mon
now.EndOfDay()                 // 2013-11-18 23:59:59.999999999 Mon
now.EndOfWeek()                // 2013-11-23 23:59:59.999999999 Sat
now.EndOfMonth()               // 2013-11-30 23:59:59.999999999 Sat
now.EndOfQuarter()             // 2013-12-31 23:59:59.999999999 Tue
now.EndOfYear()                // 2013-12-31 23:59:59.999999999 Tue

now.WeekStartDay = time.Monday // Set Monday as first day, default is Sunday
now.EndOfWeek()                // 2013-11-24 23:59:59.999999999 Sun

Calculating time based on another time

t := time.Date(2013, 02, 18, 17, 51, 49, 123456789, time.Now().Location())
now.With(t).EndOfMonth()   // 2013-02-28 23:59:59.999999999 Thu

Calculating time based on configuration

location, err := time.LoadLocation("Asia/Shanghai")

myConfig := &now.Config{
    WeekStartDay: time.Monday,
    TimeLocation: location,
    TimeFormats: []string{"2006-01-02 15:04:05"},

t := time.Date(2013, 11, 18, 17, 51, 49, 123456789, time.Now().Location()) // // 2013-11-18 17:51:49.123456789 Mon
myConfig.With(t).BeginningOfWeek()         // 2013-11-18 00:00:00 Mon

myConfig.Parse("2002-10-12 22:14:01")     // 2002-10-12 22:14:01
myConfig.Parse("2002-10-12 22:14")        // returns error 'can't parse string as time: 2002-10-12 22:14'


Don't be bothered with the WeekStartDay setting, you can use Monday, Sunday

now.Monday()              // 2013-11-18 00:00:00 Mon
now.Monday("17:44")       // 2013-11-18 17:44:00 Mon
now.Sunday()              // 2013-11-24 00:00:00 Sun (Next Sunday)
now.Sunday("18:19:24")    // 2013-11-24 18:19:24 Sun (Next Sunday)
now.EndOfSunday()         // 2013-11-24 23:59:59.999999999 Sun (End of next Sunday)

t := time.Date(2013, 11, 24, 17, 51, 49, 123456789, time.Now().Location()) // 2013-11-24 17:51:49.123456789 Sun
now.With(t).Monday()              // 2013-11-18 00:00:00 Mon (Last Monday if today is Sunday)
now.With(t).Monday("17:44")       // 2013-11-18 17:44:00 Mon (Last Monday if today is Sunday)
now.With(t).Sunday()              // 2013-11-24 00:00:00 Sun (Beginning Of Today if today is Sunday)
now.With(t).Sunday("18:19:24")    // 2013-11-24 18:19:24 Sun (Beginning Of Today if today is Sunday)
now.With(t).EndOfSunday()         // 2013-11-24 23:59:59.999999999 Sun (End of Today if today is Sunday)

Parse String to Time

time.Now() // 2013-11-18 17:51:49.123456789 Mon

// Parse(string) (time.Time, error)
t, err := now.Parse("2017")                // 2017-01-01 00:00:00, nil
t, err := now.Parse("2017-10")             // 2017-10-01 00:00:00, nil
t, err := now.Parse("2017-10-13")          // 2017-10-13 00:00:00, nil
t, err := now.Parse("1999-12-12 12")       // 1999-12-12 12:00:00, nil
t, err := now.Parse("1999-12-12 12:20")    // 1999-12-12 12:20:00, nil
t, err := now.Parse("1999-12-12 12:20:21") // 1999-12-12 12:20:21, nil
t, err := now.Parse("10-13")               // 2013-10-13 00:00:00, nil
t, err := now.Parse("12:20")               // 2013-11-18 12:20:00, nil
t, err := now.Parse("12:20:13")            // 2013-11-18 12:20:13, nil
t, err := now.Parse("14")                  // 2013-11-18 14:00:00, nil
t, err := now.Parse("99:99")               // 2013-11-18 12:20:00, Can't parse string as time: 99:99

// MustParse must parse string to time or it will panic
now.MustParse("2013-01-13")             // 2013-01-13 00:00:00
now.MustParse("02-17")                  // 2013-02-17 00:00:00
now.MustParse("2-17")                   // 2013-02-17 00:00:00
now.MustParse("8")                      // 2013-11-18 08:00:00
now.MustParse("2002-10-12 22:14")       // 2002-10-12 22:14:00
now.MustParse("99:99")                  // panic: Can't parse string as time: 99:99

Extend now to support more formats is quite easy, just update now.TimeFormats with other time layouts, e.g:

now.TimeFormats = append(now.TimeFormats, "02 Jan 2006 15:04")

Please send me pull requests if you want a format to be supported officially


You can help to make the project better, check out for things you can do.

Download Details:

Author: jinzhu
Source Code: 
License: MIT license

#go #golang #time 

Now: A Time toolkit for Golang
Rupert  Beatty

Rupert Beatty


Collection of advice on optimizing compile times of Swift projects

Optimizing Swift build times

Collection of advice on optimizing compile times of Swift projects.

Swift is constantly improving ❤️. For the time being, though, long compile times persist as a big issue when working on medium-to-large apps. The goal of this project is to gather all there is that can help you shorten your build times.

👷🏻 Maintainer: Arek Holko. Anything missing? Issues and pull requests welcomed!

Incremental Compilation Mode with No Optimization

Until Xcode 10, it was common to enable Whole Module Optimization to speed up Debug builds. It was a workaround that's no longer needed in Xcode 10!

Currently, the recommended setup is to have Incremental Compilation Mode set for Debug builds and Whole Module for Release builds. Also, No Optimization should be chosen for Optimization Level setting of Debug builds.

📖 Sources:

Type checking of functions and expressions

Swift build times are slow mostly because of expensive type checking. By default Xcode doesn't show code that's slow to compile. You can instruct it to show slowly compiling functions and expressions, though by adding:

  • -Xfrontend -warn-long-function-bodies=100 (100 means 100ms here, you should experiment with this value depending on your computer speed and project)
  • -Xfrontend -warn-long-expression-type-checking=100

to Other Swift Flags in build settings:

Build again and you should now see warnings like these:

Next step is to address code that Swift compiler has problems with. John Sundell and Robert Gummesson are here to help you with that.

📖 Sources:

Slowly compiling files

The previous section described working on an expression- and function-level but it’s often interesting to know compile times of whole files too.

There’s no UI in Xcode for that, though, so you have to build the project from the CLI with correct flags set:

xcodebuild -destination 'platform=iOS Simulator,name=iPhone 8' \
  -sdk iphonesimulator -project YourProject.xcodeproj \
  -scheme YourScheme -configuration Debug \
  clean build \
  OTHER_SWIFT_FLAGS="-driver-time-compilation \
    -Xfrontend -debug-time-function-bodies \
    -Xfrontend -debug-time-compilation" | \
tee profile.log

(Replace -project YourProject.xcodeproj with -workspace YourProject.xcworkspace if you use a workspace.)

Then extract the interesting statistics using:

awk '/Driver Compilation Time/,/Total$/ { print }' profile.log | \
  grep compile | \
  cut -c 55- | \
  sed -e 's/^ *//;s/ (.*%)  compile / /;s/ [^ ]*Bridging-Header.h$//' | \
  sed -e "s|$(pwd)/||" | \
  sort -rn | \
  tee slowest.log

You’ll end up with slowest.log file containing list of all files in the project, along with their compile times. Example:

2.7288 (  0.3%)  {compile: Account.o <= Account.swift }
2.7221 (  0.3%)  {compile: MessageTag.o <= MessageTag.swift }
2.7089 (  0.3%)  {compile: EdgeShadowLayer.o <= EdgeShadowLayer.swift }
2.4605 (  0.3%)  {compile: SlideInPresentationAnimator.o <= SlideInPresentationAnimator.swift }

📖 Sources:

Build active architecture only

This setting is a default but you should double check that it’s correct. Your project should build only active architecture in Debug configuration.

📖 Sources:

dSYM generation

By default in new projects, dSYM files aren’t generated at all for Debug builds. However, it’s sometimes useful to have them available when running on a device – to be able to analyze crashes happening without the debugger attached.

Recommended setup:

📖 Sources:

Third-party dependencies

There are two ways you can embed third-party dependencies in your projects:

  1. as a source that gets compiled each time you perform a clean build of your project (examples: CocoaPods, git submodules, copy-pasted code, internal libraries in subprojects that the app target depends on)
  2. as a prebuilt framework/library (examples: Carthage, static library distributed by a vendor that doesn’t want to provide the source code)

CocoaPods being the most popular dependency manager for iOS by design leads to longer compile times, as the source code of 3rd-party libraries in most cases gets compiled each time you perform a clean build. In general you shouldn’t have to do that often but in reality, you do (e.g. because of switching branches, Xcode bugs, etc.).

Carthage, even though it’s harder to use, is a better choice if you care about build times. You build external dependencies only when you change something in the dependency list (add a new framework, update a framework to a newer version, etc.). That may take 5 or 15 minutes to complete but you do it a lot less often than building code embedded with CocoaPods. You can even skip those initial minutes using Rome.

📖 Sources:

  • time spent waiting for Xcode to finish builds 😅


Incremental compilation in Swift isn’t perfect. There are projects where changing one string somewhere causes almost a whole project to get recompiled during an incremental build. It’s something that can be debugged and improved but a good tooling for that isn’t available yet.

To avoid issues like that, you should consider splitting your app into modules. In iOS, these are either: dynamic frameworks or static libraries (support for Swift was added in Xcode 9).

Let’s say your app target depends on an internal framework called DatabaseKit. The main guarantee of this approach is that when you change something in your app project, DatabaseKit won’t get recompiled during an incremental build.

📖 Sources:


XIBs/storyboards vs. code. 🔥 It’s as hot a topic as they go but let’s not discuss it fully here. What’s interesting is that when you change the contents of a file in Interface Builder, only that file gets compiled (to NIB format). On the other hand, Swift compiler may decide to recompile a big part of your project when you change e.g. a single line in a public method in a UIView subclass.

📖 Sources:

Xcode Schemes

Let’s say we have a common project setup with 3 targets:

  • App
  • AppTests
  • AppUITests

Working with only one scheme is fine but we can do better. The setup we’ve been using recently consists of three schemes:


Builds only the app on cmd-B. Runs only unit tests. Useful for short iterations, e.g. on a UI code, as only the needed code gets built.

App - Unit Test Flow

Builds both the app and unit test target. Runs only unit tests. Useful when working on code related to unit tests, because you find about compile errors in tests immediately after building a project, not even having to run them!

This scheme is useful when your UI tests take too long to run them often.

App - All Tests Flow

Builds the app and all test targets. Runs all tests. Useful when working on code close to UI which impacts UI tests.

📖 Sources:

Use the new Xcode build system

In Xcode 9 Apple introduced a new build system. To enable it, go to Workspace or Project Settings from the File menu in Xcode. There you can switch build systems to the new build system.

📖 Sources:

Showing build times in Xcode

Finally, to be able to actually know whether your build times are improving, you should enable showing them in Xcode’s UI. To do that, run this from the command line:

$ defaults write ShowBuildOperationDuration -bool YES

Once done, after building a project (cmd-B) you should see:

I recommend comparing build times under same conditions each time, e.g.

  1. Quit Xcode.
  2. Clear Derived Data ($ rm -rf ~/Library/Developer/Xcode/DerivedData).
  3. Open your project in Xcode.
  4. Start a build either immediately after Xcode opens or after indexing phase completes. The first approach seems to be more representative because starting with Xcode 9 building also performs indexing.

Alternatively, you can time builds from the command line:

$ time xcodebuild other params

📖 Sources:

Download Details:

Author: Fastred
Source Code: 
License: MIT license

#swift #time #compile 

Collection of advice on optimizing compile times of Swift projects

3D Room Acoustics Finite Difference Time Domain (FDTD) Simulator

AcFDTD (this library is unmantained)

Finite Difference Time Domain (FDTD) method for room acoustic simulation


From the Julia command line hit:


Once the package is installed you can update it along with the others issuing Pkg.update() in the command line.


Import the package by typing using AcFDTD. First you need to specify an acoustic environment and FDTD scheme:

using AcFDTD
X = 0.1                   # spatial sampling
env = FDTDEnv(X,IISO())   # create new acoustic env with default values

where IISO() returns the Interpolated Isotropic scheme. Alternatively one can choose a samplng frequency instead of a spatial sampling:

Fs = 2000.                          # sampling frequency in Hz
env = FDTDEnv(IISO(),Fs; c = 340)   # create new acoustic env with default values

notice that in the latter line the speed of sound was chosen to be 340 m/s. By default this is set to 343 m/s. Set the acoustic impedance ξ and room geometry room geometry:

ξ = [50.;50.;100.;30.;50.;50.]; # [   ξx1    ;    ξx2   ;    ξy1   ;    ξy2    ;  ξz1 ;   ξz2  ]
                                # [front wall; rear wall; left wall; right wall; floor; ceiling]
geo = CuboidRoom(10, 11, 12, ξ, env)

The first three parameters indicate the number of spatial samples of the x, y and z directions.
Alternatively one can specify the room dimensions in meters:

geo = CuboidRoom(4., 5., 3., ξ, env)

which are then approximated on the grid. Set the number of time steps Nt Create a band-limited sound source with e.g. the DSP package:

using DSP
Nt = round(Int,env.Fs)         # number of time steps (1 sec)
s = zeros(Nt)                    # source signal
s[3] = 1
f2 = geo.env.Fs/2*0.175          # cut-off frequency of source
filt!(s,digitalfilter(Bandpass(10,f2;fs = geo.env.Fs),Butterworth(5)),s)

Define the position of microphone and sound sources:

xr = [(2, 2, 2), (2, geo.Ny-1, geo.Nz-1)] # mic positions
xs = (geo.Nx-1, geo.Ny-1, geo.Nz-1) # sound source position
#positions must be Tuple{Int,Int,Int} or Array{Tuple{Int,Int,Int},1} 

Now type:

p = fdtd(xr,xs,Nt,geo,s)

to obtain the sound pressure of the microphones.

For more details on the methods type:



AcFDTD.jl is developed by Niccolò Antonello at KU Leuven, ESAT/Stadius.

Download Details:

Author: Nantonel
Source Code: 
License: View license

#julia #3d #time 

3D Room Acoustics Finite Difference Time Domain (FDTD) Simulator
Rupert  Beatty

Rupert Beatty


BuildTimeanalyzer-for-Xcode: Build Time Analyzer for Swift

Build Time Analyzer for Xcode


Build Time Analyzer is a macOS app that shows you a break down of Swift build times. See this post and this post on Medium for context.


Open up the app and follow the instructions.



Download the code and open it in Xcode, archive the project and export the build. Easy, right?


If you encounter any issues or have ideas for improvement, I am open to code contributions.

Download Details:

Author: RobertGummesson
Source Code: 
License: MIT license

#swift #time #xcode #analyzer 

BuildTimeanalyzer-for-Xcode: Build Time Analyzer for Swift

TimeArrays.jl: Temporary Repo to Explore Combining Arrays


temporary repo to explore combining Arrays of SeriesPair into multicolumn type with similar behavior

API in progress (check back often)

julia> using TimeArrays, MarketData

julia> ohlc
505x6 TimeArray{Float64,2} 1980-01-03 to 1981-12-31

             Open    High    Low     Close   Volume       Adj Cl
1980-01-03 | 105.76  106.08  103.26  105.22  50480000.00  105.22
1980-01-04 | 105.22  107.08  105.09  106.52  39130000.00  106.52
1980-01-07 | 106.52  107.80  105.80  106.81  44500000.00  106.81
1980-01-08 | 106.81  109.29  106.29  108.95  53390000.00  108.95
1981-12-24 | 122.31  123.06  121.57  122.54  23940000.00  122.54
1981-12-28 | 122.54  123.36  121.73  122.27  28320000.00  122.27
1981-12-29 | 122.27  122.90  121.12  121.67  35300000.00  121.67
1981-12-30 | 121.67  123.11  121.04  122.30  42960000.00  122.30
1981-12-31 | 122.30  123.42  121.57  122.55  40780000.00  122.55

julia> ohlc[1]
1x6 TimeArray{Float64,2} 1980-01-03 to 1980-01-03

             Open    High    Low     Close   Volume       Adj Cl
1980-01-03 | 105.76  106.08  103.26  105.22  50480000.00  105.22

julia> ohlc[1:2]
2x6 TimeArray{Float64,2} 1980-01-03 to 1980-01-04

             Open    High    Low     Close   Volume       Adj Cl
1980-01-03 | 105.76  106.08  103.26  105.22  50480000.00  105.22
1980-01-04 | 105.22  107.08  105.09  106.52  39130000.00  106.52

julia> ohlc[[firstday, tenthday]]
2x6 TimeArray{Float64,2} 1980-01-03 to 1980-01-16

             Open    High    Low     Close   Volume       Adj Cl
1980-01-03 | 105.76  106.08  103.26  105.22  50480000.00  105.22
1980-01-16 | 111.14  112.90  110.38  111.05  67700000.00  111.05

julia> ohlc["Low"][1:2]
2x1 TimeArray{Float64,2} 1980-01-03 to 1980-01-04

1980-01-03 | 103.26
1980-01-04 | 105.09

julia> ohlc["Open", "Close"][1:2]
2x2 TimeArray{Float64,2} 1980-01-03 to 1980-01-04

             Open    Close
1980-01-03 | 105.76  105.22
1980-01-04 | 105.22  106.52

julia> op[1:3] .- cl[2:4]
2x1 TimeArray{Float64,1} 1980-01-04 to 1980-01-07

1980-01-04 | -1.30
1980-01-07 | -0.29

Download Details:

Author: Milktrader
Source Code: 
License: MIT license

#julia #time #arrays 

TimeArrays.jl: Temporary Repo to Explore Combining Arrays

Surgically Polyfills Timezone Support in Intl.DateTimeformat API

Intl.DateTimeFormat timezone polyfill

Surgically polyfills timezone support in Intl.DateTimeFormat API 

Some browsers do not support arbitrary time zone in Intl.DateTimeFormat API (becuase its optional as per ECMA-402 standard). This polyfill is only to bring this support. Polyfill contains historical timezone data, CLDR data & tiny code to polyfill this support.

How to use?

Install via nodejs:

npm i date-time-format-timezone

And then import in your code:

require('date-time-format-timezone'); // polyfill is ready

In the browser

include everything:

<script src="">

or include individual files:

<script src="">
<script src="">
<script src="">
<script src="">

This polyfill can add this support.

new Intl.DateTimeFormat('hi', {
    timeZone: 'Asia/Calcutta',
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
}).format(new Date());

"११/१/२०१७, पू १:२६ भारतीय मानक समय"

new Intl.DateTimeFormat('en', {
    timeZone: 'America/Los_Angeles',
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
}).format(new Date());

"1/10/2017, 12:00 PM Pacific Standard Time"



Generate latest data from

git checkout
npm install
grunt download
npm publish

Browserified file size

top zones1 only no locale369.32KB71KB
all zones no locale303.19KB75KB
top zones1 top locale2641.86KB148KB

*1. top zones are custom listed timezones here.

*2. top locales are custom listed locales here.



Download Details:

Author: Formatjs
Source Code: 
License: View license

#javascript #date #time #timezone 

Surgically Polyfills Timezone Support in Intl.DateTimeformat API

4 Best PHP Libraries for Date and Time

In today's post we will learn about 4 Best PHP Libraries for Date and Time. 

What is Date and Time?

The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways.

Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions.

Table of contents:

  • Carbon - A simple DateTime API extension.
  • Chronos - A DateTime API extension supporting both mutable and immutable date/time.
  • Moment.php - Moment.js inspired PHP DateTime handler with i18n support.
  • Yasumi - An library to help you calculate the dates and names of holidays.

1 - Carbon:

A simple DateTime API extension.

An international PHP extension for DateTime.


use Carbon\Carbon;

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  //implicit __toString()
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2016)->addYears(4);

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

// Don't really want this to happen so mock now
Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));

// comparisons are always done in UTC
if (Carbon::now()->gte($internetWillBlowUpOn)) {

// Phew! Return to normal behaviour

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
// Over 200 languages (and over 500 regional variants) supported:
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
echo Carbon::now()->subMinutes(2)->locale('zh_CN')->diffForHumans(); // '2分钟前'
echo Carbon::parse('2019-07-23 14:51')->isoFormat('LLLL'); // 'Tuesday, July 23, 2019 2:51 PM'
echo Carbon::parse('2019-07-23 14:51')->locale('fr_FR')->isoFormat('LLLL'); // 'mardi 23 juillet 2019 14:51'

// ... but also does 'from now', 'after' and 'before'
// rolling up to seconds, minutes, hours, days, months, years

$daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays();


With Composer

$ composer require nesbot/carbon
    "require": {
        "nesbot/carbon": "^2.16"
require 'vendor/autoload.php';

use Carbon\Carbon;

printf("Now: %s", Carbon::now());

Without Composer

Why are you not using composer? Download the Carbon latest release and put the contents of the ZIP archive into a directory in your project. Then require the file autoload.php to get all classes and dependencies loaded on need.

require 'path-to-Carbon-directory/autoload.php';

use Carbon\Carbon;

printf("Now: %s", Carbon::now());

View on Github

2 - Chronos:

A DateTime API extension supporting both mutable and immutable date/time.

Chronos aims to be a drop-in replacement for nesbot/carbon. It focuses on providing immutable date/datetime objects. Immutable objects help ensure that datetime objects aren't accidentally modified keeping data more predictable.


Installing with composer:

$ composer require cakephp/chronos

You can then use Chronos:

require 'vendor/autoload.php';

use Cake\Chronos\Chronos;

printf("Now: %s", Chronos::now());

Differences with nesbot/carbon

The biggest and main difference is that Chronos extends DateTimeImmutable instead of DateTime. Immutability for date values has proven to be a great way of avoiding bugs and reduce the amount of code, since developers don't have to manually copy the instance every time they need a change.

Another important feature it offers is the Date class, which is used for representing dates without time (calendar dates). Any time method called on this type of object is basically a no-op.

There are other implementation changes, but one that users might not notice is Chronos considers Monday as the start of the week instead of Sunday. This follows the ISO-8601 and current versions of PHP 5.6 and PHP 7.

A minor but still noticeable difference is that Chronos has no external dependencies, it is completely standalone.

Finally, Chronos is faster than Carbon as it has been optimized for the creation of hundreds of instances with minimal overhead.

Migrating from Carbon

First add cakephp/chronos to your composer.json:

php composer.phar require cakephp/chronos

By default Chronos includes a compatibility script that creates aliases for the relevant Carbon classes. This will let most applications upgrade with very little effort. If you'd like to permanently update your code, you will need to update imports and typehints. Assuming src contains the files you want to migrate, we could use the following to update files:

# Replace imports
find ./src -type f -name '*.php' -exec sed -i '' 's/use Carbon\\CarbonInterval/use Cake\\Chronos\\ChronosInterval/g' {} \;
find ./src -type f -name '*.php' -exec sed -i '' 's/use Carbon\\CarbonImmutable/use Cake\\Chronos\\Chronos/g' {} \;
find ./src -type f -name '*.php' -exec sed -i '' 's/use Carbon\\Carbon/use Cake\\Chronos\\Chronos/g' {} \;

# Replace typehints and extensions
find ./src -type f -name '*.php' -exec sed -i '' 's/CarbonInterval/ChronosInterval/g' {} \;
find ./src -type f -name '*.php' -exec sed -i '' 's/CarbonImmutable/Chronos/g' {} \;
find ./src -type f -name '*.php' -exec sed -i '' 's/Carbon/Chronos/g' {} \;

At this point your code should mostly work as it did before. The biggest difference is that Chronos instances are immutable.

View on Github

3 - Moment.php:

Moment.js inspired PHP DateTime handler with i18n support.


What is moment.php?

Date library for parsing, manipulating and formatting dates w/ i18n.

Any dependencies?

PHP 5.3 or later since moment.php is based on php's DateTime Class.


Easy install via composer. Still no idea what composer is? Inform yourself here.

composer require fightbulc/moment

Quick examples

Get a moment

$m = new \Moment\Moment(); // default is "now" UTC
echo $m->format(); // e.g. 2012-10-03T10:00:00+0000

$m = new \Moment\Moment('now', 'Europe/Berlin');
echo $m->format(); // e.g. 2012-10-03T12:00:00+0200

$m = new \Moment\Moment('2017-06-06T10:00:00', 'Europe/Berlin');
echo $m->format(); // e.g. 2012-10-03T12:00:00+0200

$m = new \Moment\Moment(1499366585);
echo $m->format(); // e.g. 2017-07-06T18:43:05+0000

Accepted date formats

Moment parses the following date formats as input:

const ATOM = 'Y-m-d\TH:i:sP'; // 2005-08-15T15:52:01+00:00
const COOKIE = 'l, d-M-y H:i:s T'; // Monday, 15-Aug-2005 15:52:01 UTC
const ISO8601 = 'Y-m-d\TH:i:sO'; // 2005-08-15T15:52:01+0000
const RFC822 = 'D, d M y H:i:s O'; // Mon, 15 Aug 05 15:52:01 +0000
const RFC850 = 'l, d-M-y H:i:s T'; // Monday, 15-Aug-05 15:52:01 UTC
const RFC1036 = 'D, d M y H:i:s O'; // Mon, 15 Aug 05 15:52:01 +0000
const RFC1123 = 'D, d M Y H:i:s O'; // Mon, 15 Aug 2005 15:52:01 +0000
const RFC2822 = 'D, d M Y H:i:s O'; // Mon, 15 Aug 2005 15:52:01 +0000
const RSS = 'D, d M Y H:i:s O'; // Mon, 15 Aug 2005 15:52:01 +0000
const W3C = 'Y-m-d\TH:i:sP'; // 2005-08-15T15:52:01+00:00

// Moment also tries to parse dates without timezone or without seconds

const NO_TZ_MYSQL = 'Y-m-d H:i:s'; // 2005-08-15 15:52:01
const NO_TZ_NO_SECS = 'Y-m-d H:i'; // 2005-08-15 15:52
const NO_TIME = 'Y-m-d'; // 2005-08-15

// time fractions ".000" will be automatically removed
$timeWithFraction = '2016-05-04T10:00:00.000';

View on Github

4 - Yasumi:

An library to help you calculate the dates and names of holidays.


Yasumi (Japanese for 'Holiday'「休み」) is the easy PHP library that helps you retrieve the dates and names of holidays and other special celebrations from various countries/states. It is calculation and rule driven avoiding the need of a comprehensive database.

Many services exist that can provide holiday information, however are either not entirely free or only offer limited information. In addition, no exhaustive PHP library exists today covering a wide range of holidays and countries. PEAR's Date_Holidays library was a similar attempt, however it hasn't been updated for a long time.


The goal of Yasumi is to be powerful while remaining lightweight, by utilizing PHP native classes wherever possible. Yasumi's calculation is provider-based (i.e. by country/state), making it easy to add new holiday providers that calculate holidays.

  • Straightforward API
  • Framework-agnostic
  • Use of Providers to easily extend and expand new Holidays
  • Common Holiday Providers
  • Accounts for the date/time when holidays have been officially established and/or abolished
  • Filters enabling to easily select certain holiday types (Official, Observed, Bank, Seasonal or Other)
  • Global Translations
  • Timezone aware
  • Implements ArrayIterator to easily process a provider's holidays
  • Fully documented
  • Fully unit tested
  • Composer ready, PSR-12 and PSR-4 compliant


Yasumi’s documentation is available on You will find all the necessary information how to install Yasumi and also recipes how you can use Yasumi in your project.

View on Github

Thank you for following this article.

Related videos:

PHP Date and Time Manipulation using the DateTime, DateInterval, DateTimeImmutable and DateTimeZone

#php #date #time 

4 Best PHP Libraries for Date and Time

A Customizable Progressive Time Picker for Flutter


A Customizable Progressive Time Picker for Flutter. This package allow us to customize time picker based on our requirements for selecting a specific range from time picker and it's supports multiple platforms.

Key Features

  • supports selection of both or single picker handler.
  • easy customization for decorating a time picker.
  • gives feature to show clock numbers in both 12 or 24 hours format and also supports customization for it.



Basic Usage

Import it to your project file

import 'package:progressive_time_picker/progressive_time_picker.dart';

And add it in its most basic form like it:

    initTime: PickedTime(h: 0, m: 0),
    endTime: PickedTime(h: 8, m: 0),
    onSelectionChange: (a, b) =>
            'onSelectionChange => init : ${a.h}:${a.m}, end : ${b.h}:${b.m}'),
    onSelectionEnd: (a, b) =>
            'onSelectionEnd => init : ${a.h}:${a.m}, end : ${b.h}:${b.m}'),

Required parameters of TimePicker

PickedTime initTimethe init PickedTime value in the selection
PickedTime endTimethe end PickedTime value in the selection
onSelectionChangecallback function when init and end PickedTime change
onSelectionEndcallback function when init and end PickedTime finish

Optional parameters of TimePicker

double height220height of the canvas
double width220width of the canvas
int primarySectors0the number of primary sectors to be painted
int secondarySectors0the number of secondary sectors to be painted
Widget childContainerwidget that would be mounted inside the circle
TimePickerDecoration decoration-used to decorate our TimePicker widget
bool isInitHandlerSelectabletrueused to enabled or disabled Selection of Init Handler
bool isEndHandlerSelectabletrueused to enabled or disabled Selection of End Handler

Required parameters of TimePickerDecoration

TimePickerSweepDecoration sweepDecorationused to decorate our sweep part or a part between our init and end point with various options
TimePickerHandlerDecoration initHandlerDecorationused to decorate our init or end handler of time picker
TimePickerHandlerDecoration endHandlerDecorationused to decorate our init or end handler of time picker

Optional parameters of TimePickerDecoration

Color baseColorcyanAccentdefines the background color of the picker
double pickerBaseCirclePadding0.0to add extra padding for picker base or outer circle
TimePickerSectorDecoration primarySectorsDecoration-used to decorate the primary sectors of out time picker
TimePickerSectorDecoration secondarySectorsDecoration-used to decorate the secondary of out time picker
TimePickerClockNumberDecoration clockNumberDecoration-Provides decoration options which will get applied to the internal clock's numbers when enable

Guideline for contributors

  • Contribution towards our repository is always welcome, we request contributors to create a pull request for development.

Guideline to report an issue/feature request

It would be great for us if the reporter can share the below things to understand the root cause of the issue.

  • Library version
  • Code snippet
  • Logs if applicable
  • Device specification like (Manufacturer, OS version, etc)
  • Screenshot/video with steps to reproduce the issue
  • Library used


progressive_time_picker is MIT-licensed.

Let us know!

We’d be really happy if you send us links to your projects where you use our component. Just send an email to And do let us know if you have any questions or suggestion regarding our work

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add progressive_time_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

  progressive_time_picker: ^0.0.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:progressive_time_picker/progressive_time_picker.dart'; 


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:progressive_time_picker/progressive_time_picker.dart';
import 'package:intl/intl.dart' as intl;

void main() {
  /// To set fixed device orientation
    (value) => runApp(MyApp()),

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  _MyHomePageState createState() => _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {
  ClockTimeFormat _clockTimeFormat = ClockTimeFormat.TWENTYFOURHOURS;
  ClockIncrementTimeFormat _clockIncrementTimeFormat =

  PickedTime _inBedTime = PickedTime(h: 0, m: 0);
  PickedTime _outBedTime = PickedTime(h: 8, m: 0);
  PickedTime _intervalBedTime = PickedTime(h: 0, m: 0);

  double _sleepGoal = 8.0;
  bool _isSleepGoal = false;

  void initState() {
    _isSleepGoal = (_sleepGoal >= 8.0) ? true : false;
    _intervalBedTime = formatIntervalTime(
      init: _inBedTime,
      end: _outBedTime,
      clockTimeFormat: _clockTimeFormat,
      clockIncrementTimeFormat: _clockIncrementTimeFormat,

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF141925),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
            'Sleep Time',
            style: TextStyle(
              color: Color(0xFF3CDAF7),
              fontSize: 30,
              fontWeight: FontWeight.bold,
            initTime: _inBedTime,
            endTime: _outBedTime,
            height: 260.0,
            width: 260.0,
            onSelectionChange: _updateLabels,
            onSelectionEnd: (a, b) => print(
                'onSelectionEnd => init : ${a.h}:${a.m}, end : ${b.h}:${b.m}'),
            primarySectors: _clockTimeFormat.value,
            secondarySectors: _clockTimeFormat.value * 2,
            decoration: TimePickerDecoration(
              baseColor: Color(0xFF1F2633),
              pickerBaseCirclePadding: 15.0,
              sweepDecoration: TimePickerSweepDecoration(
                pickerStrokeWidth: 30.0,
                pickerColor: _isSleepGoal ? Color(0xFF3CDAF7) : Colors.white,
                showConnector: true,
              initHandlerDecoration: TimePickerHandlerDecoration(
                color: Color(0xFF141925),
                radius: 12.0,
                icon: Icon(
                  size: 20.0,
                  color: Color(0xFF3CDAF7),
              endHandlerDecoration: TimePickerHandlerDecoration(
                color: Color(0xFF141925),
                radius: 12.0,
                icon: Icon(
                  size: 20.0,
                  color: Color(0xFF3CDAF7),
              primarySectorsDecoration: TimePickerSectorDecoration(
                color: Colors.white,
                width: 1.0,
                size: 4.0,
                radiusPadding: 25.0,
              secondarySectorsDecoration: TimePickerSectorDecoration(
                color: Color(0xFF3CDAF7),
                width: 1.0,
                size: 2.0,
                radiusPadding: 25.0,
              clockNumberDecoration: TimePickerClockNumberDecoration(
                defaultTextColor: Colors.white,
                defaultFontSize: 12.0,
                scaleFactor: 2.0,
                showNumberIndicators: true,
                clockTimeFormat: _clockTimeFormat,
                clockIncrementTimeFormat: _clockIncrementTimeFormat,
            child: Padding(
              padding: const EdgeInsets.all(62.0),
              child: Column(
                children: [
                    '${intl.NumberFormat('00').format(_intervalBedTime.h)}Hr ${intl.NumberFormat('00').format(_intervalBedTime.m)}Min',
                    style: TextStyle(
                      fontSize: 14.0,
                      color: _isSleepGoal ? Color(0xFF3CDAF7) : Colors.white,
                      fontWeight: FontWeight.bold,
            width: 300.0,
            decoration: BoxDecoration(
              color: Color(0xFF1F2633),
              borderRadius: BorderRadius.circular(25.0),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                    ? "Above Sleep Goal (>=8) 😄"
                    : 'below Sleep Goal (<=8) 😴',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
                  size: 25.0,
                  color: Color(0xFF3CDAF7),
                  size: 25.0,
                  color: Color(0xFF3CDAF7),

  Widget _timeWidget(String title, PickedTime time, Icon icon) {
    return Container(
      width: 150.0,
      decoration: BoxDecoration(
        color: Color(0xFF1F2633),
        borderRadius: BorderRadius.circular(25.0),
      child: Padding(
        padding: const EdgeInsets.all(25.0),
        child: Column(
          children: [
              style: TextStyle(
                color: Color(0xFF3CDAF7),
                fontSize: 25,
                fontWeight: FontWeight.bold,
            SizedBox(height: 15),
              style: TextStyle(
                color: Color(0xFF3CDAF7),
                fontSize: 16,
            SizedBox(height: 10),

  void _updateLabels(PickedTime init, PickedTime end) {
    _inBedTime = init;
    _outBedTime = end;
    _intervalBedTime = formatIntervalTime(
      init: _inBedTime,
      end: _outBedTime,
      clockTimeFormat: _clockTimeFormat,
      clockIncrementTimeFormat: _clockIncrementTimeFormat,
    _isSleepGoal = validateSleepGoal(
      inTime: init,
      outTime: end,
      sleepGoal: _sleepGoal,
      clockTimeFormat: _clockTimeFormat,
      clockIncrementTimeFormat: _clockIncrementTimeFormat,
    setState(() {});

Download Details:

Author: Mindinventory

Source Code:

#time #Picker #flutter 

A Customizable Progressive Time Picker for Flutter
Nat  Grady

Nat Grady


ShinyTime: A Timeinput Widget for Shiny



shinyTime provides a timeInput widget for Shiny. This widget allows intuitive time input in the hh:mm:ss or hh:mm (24-hour) format by using a separate numeric input for each time component. Setting and getting of the time in R is done with date-time objects.


# Install from CRAN


As the shinyTime package mimics the existing shiny functionality, using the package is easy:

ui <- fluidPage(
  # Using the default time 00:00:00
  timeInput("time1", "Time:"),

  # Set to current time
  timeInput("time2", "Time:", value = Sys.time()),

  # Set to custom time 
  timeInput("time3", "Time:", value = strptime("12:34:56", "%T")),
  # Set to custom time using hms
  timeInput("time4", "Time:", value = hms::as_hms("23:45:07")),

  # Set to custom time using character string
  timeInput("time5", "Time:", value = "21:32:43"),

  # Use hh:mm format
  timeInput("time6", "Time:", seconds = FALSE),

  # Use multiples of 5 minutes
  timeInput("time7", "Time:", minute.steps = 5)

Note that setting an initial value can be done with date-time (in the same way as setting a date in dateInput can be done with a Date object), but also with an hms::hms object or character string in hh:mm:ss format.

The value retrieved will be a date-time object (POSIXlt). You need to convert it to character to be able to show the time, as the default character representation does not include time. For example:

server <- function(input, output) {
  # Print the time in hh:mm:ss everytime it changes
  observe(print(strftime(input$time1, "%T")))
  # Print the time in hh:mm everytime it changes
  observe(print(strftime(input$time4, "%R")))

For a demo, visit the online example app or try the shinyTime::shinyTimeExample() function.

Download Details:

Author: Burgerga
Source Code: 
License: GPL-3.0 license

#r #time #widget 

ShinyTime: A Timeinput Widget for Shiny

Climatetools.jl: Climate Science Package for Julia

Climate analysis tools in Julia


Note. Compatible with Julia 1.2 and higher

ClimateTools.jl is a collection of commonly-used tools in Climate science. Basics of climate field analysis are covered, with some forays into exploratory techniques associated with climate scenarios design. The package is aimed to ease the typical steps of analysis climate models outputs and gridded datasets (support for weather stations is a work-in-progress).

ClimateTools.jl is registered on METADATA.jl and can be added and updated with Pkg commands. See installation documentation for detailed installation instructions and Python's dependencies (for mapping features).

Climate indices and bias correction functions are coded to leverage the use of multiple threads. To gain maximum performance, use (bash shell Linux/MacOSX) export JULIA_NUM_THREADS=n, where n is the number of threads. To get an idea of the number of threads you can use type (in Julia) Sys.THREADS. This is especially useful for bias correction.


If you'd like to have other climate indices coded, please, submit them through a Pull Request! I'd be more than happy to include them. Alternatively, provide the equation in Issues.


  • Extraction and visualization of CF-compliant netCDF datasets
  • Custom user-provided polygons and start and end date for localized studies
  • Climate indices from The joint CCl/CLIVAR/JCOMM Expert Team (ET) on Climate Change Detection and Indices (ETCCDI) as well as custom climate indices. See list.
  • Regridding of a datasets onto another grid
  • Post-processing of climate timeseries using Quantile-Quantile mapping method (cf. Themeßl et al. 2012, Piani et al. 2010)
  • Support for physical units through the Unitful.jl package.

Getting started

Note. More in-depth documentation is provided in the official documentation (Links: stable/latest).

using ClimateTools

Reading a NetCDF file

The entry point of ClimateTools is to load data with the load function. Optional polygon clipping feature is available. By providing such polygon, the load function returns a ClimGrid with grid points contained in the polygon.

C = load(filename::String, vari::String; poly::Array, data_units::String, start_date::Tuple, end_date::Tuple)

load returns a ClimGrid type. Using the optional poly argument, the user can provide a polygon and the returned ClimGrid will only contains the grid points inside the provided polygon. For some variable, the optional keyword argument data_units can be provided. For example, precipitation in climate models are usually provided as kg/m^2/s. By specifying data_units = mm, the load function returns accumulation at the data time resolution. Similarly, the user can provide Celsius as data_units and load will return Celsius instead of Kelvin.

The ClimGrid is a in-memory representation of a CF-compliant netCDF file for a single variable.

struct ClimGrid
  data::AxisArray # labeled axis
  longrid::AbstractArray{N,2} where N # the longitude grid
  latgrid::AbstractArray{N,2} where N # the latitude grid
  msk::Array{N, 2} where N
  grid_mapping::Dict # bindings of native grid
  project::String # CORDEX, CMIP5, etc.
  latunits::String # of the coordinate variable
  lonunits::String # of the coordinate variable
  variable::String # Type of variable (i.e. can be the same as "var", but it is changed when calculating indices)
  typeofvar::String # Variable type (e.g. tasmax, tasmin, pr)
  typeofcal::String # Calendar type
  timeattrib::Dict # Time attributes
  varattribs::Dict # Variable attributes
  globalattribs::Dict # Global attributes



Further subsets can be done in the temporal and spatial domains. spatialsubset function acts on ClimGrid type and subset the data using a user polygon. The function returns another ClimGrid.

C = spatialsubset(C::ClimGrid, poly:Array{N, 2} where N)

Temporal subset of the data is done with temporalsubset function, which returns a continuous timeserie between startdate and enddate.

C = temporalsubset(C::ClimGrid, startdate::Tuple, enddate::Tuple)

Resampling is available with the resample, which returns a given period for each year (e.g. only summer months).

C = resample(C::ClimGrid, startmonth::Int, endmonth::Ind)
C = resample(C::ClimGrid, season::String) # hardcoded seasons -> "DJF", "MAM", "JJA" and "SON"

Mapping the ClimGrid type

Mapping climate information can be done by using mapclimgrid.

mapclimgrid(C::ClimGrid; region = "World")

Which should return the time average of ClimGrid C over the world region.

Precipitation example

Note that if the ClimGrid data structure has 3 dimensions (time x longitude x latitude) the mapclimgrid function makes a time-average (i.e. climatological mean). Right now, there are a growing list of hardcoded regions (see help section of mapclimgrid function) and the default auto which use the maximum and minimum of the lat-long coordinates inside the ClimGrid structure. The user can also provide a polygon(s) and the mapclimgrid function will clip the grid points outside the specified polygon. Another option is to provide a mask (with dimensions identical to the spatial dimension of the ClimGrid data) which contains NaN and 1.0 and the data inside the ClimGrid struct will be clipped with the mask. Other regions will be added in the future, as well as the option to send a custom region defined by a lat-lon box.


More than 20 climate indices are available in the package, such as the annual number of tropical nights, annual maximum and minimum, etc. You can calculate such indices simply with:

ind = annualmax(C::ClimGrid)

Which returns another ClimGrid. You can also map this ClimGrid with the mapclimgrid function and returns the climatological mean of the annual maximum (e.g. daily precipitation in the example below). From the figure, we clearly sees the monsoon regions (India) and region with wind-driven precipitations (e.g. western sides of the oceans).

A list of indices can be found in the documentation and in the functions.jl source code.

Precipitation example

Climate indices can easily be developed by following the source code or looking at the available metadata inside a ClimGrid.


A typical step in climate analysis is to interpolate a given grid onto another grid. ClimateTools provides such a tool by wrapping Scipy griddata function. It is intended for visualization or as a 1st step before bias-correcting the ClimGrid dataset.

The following command will interpolate the data contained in ClimGrid A into the coordinates of ClimGrid B and returns a new ClimGrid C which contains the interpolated data of A into the grid of B.

C = regrid(A::ClimGrid, B::ClimGrid)

It is also possible to interpolate a ClimGrid onto specified longitude and latitude vectors.

C = regrid(A::ClimGrid, lon::AbstractArray{N, 1}, lat::AbstractArray{N, 1})


See Documentation.

Merging ClimGrids

Sometimes, the timeseries are split among multiple files (e.g. climate models outputs). To obtain the complete timeseries, you can merge 2 ClimGrid. The method is based on the merging of two AxisArrays and is overloaded for the ClimGrid type.

C = merge(C1::ClimGrid, C2::ClimGrid)


It is possible to export to a netCDF file with the command write

write(C::ClimGrid, filename::String)


  • Dashboard tool. This will return the main characteristics of a ClimGrid: maps of minimum, maximum and mean climatological values, seasonal cycle, timeseries of annual maximum, minimum and mean values, etc...
  • Create a WeatherStation type.
  • Add a more complex quantile-quantile mapping technique, combining extreme value theory and quantile-quantile standard technique

Download Details:

Author: JuliaClimate
Source Code: 
License: View license

#julia #tools #time 

Climatetools.jl: Climate Science Package for Julia
Nat  Grady

Nat Grady


RStudio Addin to Provide Easy & interactive Time Series Visualization


An RStudio addin to provide easy and interactive time series visualization. To be visible to the addin, time series must be stored in a dataframe in the global environment, with:

  • at least a column of type Date
  • at least a column of type numeric


You can install the released version of tsviz from CRAN with:


Or install the development version from Github:


Once you have installed the package, you do not need to load it with library(), the addins are installed on your machine as part of the package install process.


First, let us load some suitable data:

prices <- crypto_prices

Then, we can run the addin:

Tutorial gif

That’s it.

Have a look to the demo performed at erum 2020! Watch on YouTube:

Who we are

 A proudly 🇮🇹 software development and data science startup.
We consider ourselves a family of talented and passionate people building their own products and powerful solutions for our clients. Get to know us more on or follow us on LinkedIn.

Download Details:

Author: xtreamsrl
Source Code: 
License: Unknown, MIT licenses found

#r #time #visualization 

RStudio Addin to Provide Easy & interactive Time Series Visualization

Financial Market Technical analysis & indicators In Julia


Indicators is a Julia package offering efficient implementations of many technical analysis indicators and algorithms. This work is inspired by the TTR package in R and the Python implementation of TA-Lib, and the ultimate goal is to implement all of the functionality of these offerings (and more) in Julia. This package has been written to be able to interface with both native Julia Array types, as well as the TS time series type from the Temporal package. Contributions are of course always welcome for wrapping any of these functions in methods for other types and/or packages out there, as are suggestions for other indicators to add to the lists below.


Moving Averages

  • SMA (simple moving average)
  • WMA (weighted moving average)
  • EMA (exponential moving average)
  • TRIMA (triangular moving average)
  • KAMA (Kaufman adaptive moving average)
  • MAMA (MESA adaptive moving average, developed by John Ehlers)
  • HMA (Hull moving average)
  • ALMA (Arnaud-Legoux moving average)
  • SWMA (sine-weighted moving average)
  • DEMA (double exponential moving average)
  • TEMA (triple exponential moving average)
  • ZLEMA (zero-lag exponential moving average)
  • MMA (modified moving average)
  • VWMA (volume-weighted moving average)
  • MLR (moving linear regression)
    • Prediction
    • Slope
    • Intercept
    • Standard error
    • Upper & lower bound
    • R-squared

Momentum Indicators

  • Momentum (n-day price change)
  • ROC (rate of change)
  • MACD (moving average convergence-divergence)
  • RSI (relative strength index)
  • ADX (average directional index)
  • Parabolic SAR (stop and reverse)
  • Fast & slow stochastics
  • SMI (stochastic momentum indicator)
  • KST (Know Sure Thing)
  • Williams %R
  • CCI (commodity channel index)
  • Donchian channel
  • Aroon indicator + oscillator

Volatility Indicators

  • Bollinger Bands
  • Average True Range
  • Keltner Bands


  • Rolling/running mean
  • Rolling/running standard deviation
  • Rolling/running variance
  • Rolling/running covariance
  • Rolling/running correlation
  • Rolling/running maximum
  • Rolling/running minimum
  • Rolling/running MAD (mean absolute deviation)
  • Rolling/running quantiles

Wish List


  • Hamming moving average
  • VWAP (volume-weighted average price)
  • EVWMA (elastic, volume-weighted moving average)
  • VMA (variable-length moving average)
  • Chaikin Money Flow
  • Ultimate Oscillator
  • OBV (on-balance volume)
  • Too many more to name...always happy to hear suggestions though!


  • Moving Linear Regression
  • KAMA (Kaufman adaptive moving average)
  • DEMA (double exponential moving average)
  • TEMA (tripe exponential moving average)
  • ALMA (Arnaud Legoux moving average)
  • Parabolic SAR
  • Williams %R
  • KST (know sure thing)
  • CCI (commodity channel index)
  • ROC (rate of change)
  • Momentum
  • Donchian Channel
  • Aroon Indicator / Aroon Oscillator
  • Stochastics
    • Slow Stochastics
    • Fast Stochastics
    • Stochastic Momentum Index
  • MMA (modified moving average)
  • ZLEMA (zero lag exponential moving average)
  • VWMA (volume-weighted moving average)


Randomly generated data:

alt text

Apple (AAPL) daily data from 2015:

alt text

Corn futures daily data

alt text

Gold Futures Moving Regression

alt text

Download Details:

Author: Dysonance
Source Code: 
License: View license

#julia #time #finance 

Financial Market Technical analysis & indicators In Julia