# enable automatic reloading of the notebook
%load_ext autoreload
%autoreload 2
Overview¶
This notebook provides a demonstration how the ts2g2 library can be used to convert time series into graphs and graphs into time series, with links to more detailed tutorials. To that end, we use a dataset with the history of daily prices of Amazon stock (AMZN) and Apple stock (APPLE). All the column descriptions are provided. Currency is USD.
import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(nb_dir)
import matplotlib.pyplot as plt
from core.model import Timeseries, TimeseriesPreprocessing, TimeseriesPreprocessingSegmentation, TimeseriesPreprocessingSlidingWindow, TimeseriesPreprocessingComposite, TimeseriesView, TimeGraph, ToSequenceVisitorSlidingWindow, ToSequenceVisitor, ToSequenceVisitorOrdinalPartition
from tsg_io.input import CsvFile
from from_graph.strategy_to_time_sequence import StrategyNextValueInNodeRandom, StrategyNextValueInNodeRandomForSlidingWindow, StrategyNextValueInNodeRoundRobin, StrategyNextValueInNodeRoundRobinForSlidingWindow, StrategySelectNextNodeRandomlyFromNeighboursAcrossGraphs, StrategySelectNextNodeRandomlyFromNeighboursFromFirstGraph, StrategySelectNextNodeRandomly, StrategySelectNextNodeRandomDegree, StrategySelectNextNodeRandomWithRestart, StrategyNextValueInNodeOrdinalPartition
from to_graph.strategy_linking_graph import StrategyLinkingGraphByValueWithinRange, LinkNodesWithinGraph
from to_graph.strategy_linking_multi_graphs import LinkGraphs
from to_graph.strategy_to_graph import BuildTimeseriesToGraphNaturalVisibilityStrategy, BuildTimeseriesToGraphHorizontalVisibilityStrategy, BuildTimeseriesToGraphOrdinalPartition, BuildTimeseriesToGraphQuantile
import warnings
warnings.filterwarnings('ignore')
Loading data¶
We first load the dataset :)
amazon_path = os.path.join(os.getcwd(), "amazon", "AMZN.csv")
apple_path = os.path.join(os.getcwd(), "apple", "APPLE.csv")
def plot_timeseries(sequence, title, x_legend, y_legend, color = "black"):
plt.figure(figsize=(10, 6))
plt.plot(sequence, linestyle='-', color=color)
plt.title(title)
plt.xlabel(x_legend)
plt.ylabel(y_legend)
plt.grid(True)
plt.show()
plot_timeseries(CsvFile(amazon_path, "Close").from_csv(), "Original Sequence", "Year", "Value")
For easier presentation and understanding we will only analyze a segment of this timeseries.
plot_timeseries(CsvFile(amazon_path, "Close").from_csv()[100:200], "Segment", "Year", "Value", color="blue")
Univariate graphs¶
We can now turn this segment of timeseries into a univariate graph:
timegraph = Timeseries(CsvFile(amazon_path, "Close").from_csv())\
.with_preprocessing(TimeseriesPreprocessingSegmentation(100, 200))\
.to_graph(BuildTimeseriesToGraphNaturalVisibilityStrategy().get_strategy())\
.draw()
Multivariate graphs¶
If we have multiple segments of timeseries, we can turn them into one connected graph, based on given strategy:
multivariate_timegraph = Timeseries(CsvFile(amazon_path, "Close").from_csv())\
.with_preprocessing(TimeseriesPreprocessingSegmentation(100, 200))\
.add(Timeseries(CsvFile(amazon_path, "Close").from_csv())\
.with_preprocessing(TimeseriesPreprocessingSegmentation(200, 300)))\
.to_graph(BuildTimeseriesToGraphNaturalVisibilityStrategy().get_strategy())\
.link(LinkGraphs().time_cooccurrence())\
.draw()
About graphs¶
There are multiple of different methods of turning timeseries into graphs. So far we have implemented:
Natural visibility strategy: ...
Horizontal visibility strategy: ...
Strategy using quantiles: ...
Ordinal partition strategy: ...
proximity network strategy: ...
timeseries correlation strategy: ...
Along with these strategies, we have constructed strategy, to turn timeseries into a
- sliding window graph: ...
After we have turned our segment into a graph, we can furthrt supplement our graph with some methods like:
add_edge(node_1, node_2, weight=None): adds edge between node_1 and node_2 with weight weight if it is not none.
link(link_strategy: LinkNodesWithinGraph): links nodes in graph based on a link_strategy object.
combine_identical_nodes(): combines nodes that have the same attributes.
To timeseries¶
When we have our graph, we can also generate a timeseries from it.
timegraph.to_sequence(ToSequenceVisitor()\
.next_node_strategy(StrategySelectNextNodeRandomDegree())\
.next_value_strategy(StrategyNextValueInNodeRoundRobin())\
.ts_length(100))\
.draw_sequence()
<core.model.TimeGraph at 0x1339db07e60>
multivariate_timegraph.to_sequence(ToSequenceVisitor()\
.next_node_strategy(StrategySelectNextNodeRandomlyFromNeighboursAcrossGraphs())\
.next_value_strategy(StrategyNextValueInNodeRandom())\
.ts_length(100))\
.draw_sequence()
<core.model.TimeGraph at 0x1339df80680>
There are also many different ways of generating timeseries. You can take closer look at them here: ...
A compact tutorial of different timeseries to graph and back methods along with some extra functions can be found here: ...
Timeseries and graph embeddings¶
We can compare different graphs and timeseries among each other by creating and calculating distance between their embeddings. You can take a closer look how this is done here: ...