Showing posts with label Business cycle. Show all posts
Showing posts with label Business cycle. Show all posts

Tuesday, March 31, 2026

The idea of Japan joining the EU, why not.

"Japan will join the EU!", I would like to shout on the 1st April. 

Added on 31st March 2026

There is a possibility that the great circle distance of the sea route between the European Union (EU) and Japan will be significantly shortened under this global warming. The new arctic sea route is emerging due to the ice meltdown. Although there are still various challenges to explore this route, it is demanded all the more than before now. 

The recent Middle Eastern incidence and the unstable political situation in South Asia may alert Japan and Europe to explore the alternative trade route. North American countries are focusing on the possibly high market potential in this Arctic route. On the top of the trade route between the EU and Japan, this area is essential for shipping the natural energy resources such as petrol oil and natural gas in this region. It is the common geopolitical interest for both the EU and Japan to secure the exploration of this trade route is necessary rather than expectation nowadays. 

Furthermore, we must not forget that the legal code of Japan has been based on the legal positivism of the continental Europe since the 19th century! The legal code of Japan is one of the examples backing up the proverb saying "All roads lead to Rome". Yes, the continental European legal code is originated from that of the Roman law. 

Japan also kept the exclusive trade tie with the Netherlands from the 17th to the 19th century. When Americans landed on Japan in the 19th century, Dutch was used as the intermediary language between American and Japanese individuals at their first encounters.  It might sound plausible Japan could closer to the EU than the USA in terms of this regard especially since the first arrival of Jesuits in the 17th century, 

Added on 1st April 2026

Of course, I know there are non-negligible drawbacks in this case scenario. First of all, the EU is heavily bureaucratic which frustrates individual habitants in their daily life as well as their economic and scientific activities. Secondly, their macroeconomic policy still faces the challenge which even the first governor of the European Central Bank (ECB) has pointed out. They have not fixed the problem of the fiscal policy under the European common monetary (EMU) policy while the characteristics of fiscal policy agents in the member states are still not harmonised enough. The aforementioned heavy frustrating bureaucracy tends to keep this kind of required reforms being slower than expected.

Originally written on 4-5th February 2023 

The followings are considered to be the conditions to join the European Union (EU) or any other possible economic and political union of countries/states. 

- Microeconomics:
  1. The high cross border trade (export and import) frequency
  2. The labour and capital mobility across the border

- Macroeconomics:
  3. The synchronised business cycle (boom and recession) among the member states
  4. The balanced fiscal policy neither disrupting the fiscal and monetary policy conducts nor depreciating the economic credibility of the entire union.

- The other aspects:
  5. Cultural and historic tie among the member states
  6. Geopolitical diplomatic interest

Japan fulfils these conditions except for the forth one because of the massive national debt of Japan. The second and third conditions might be questionable but they are not insignificant at all.

Remember that the foreign tourism is accounted as export&import!  The EU members and Japan trade not only physical items but also tourists a lot with each other. 

Also remember that Japan had had the international trade with Europeans more than the others since 17th century till the end of Shogunate era! In particular, during Tokugawa dynasty, lasting for approximately 300 years, the Netherlands was only the country which was permitted to trade with Japan implementing the national isolation. Before then, Spanish and Portuguese were the major diplomatic partners until they were banned from it. 

Both the EU and Japan very often share the remarkable foreign diplomatic and geopolitical interest. For example, both frequently suffer from Russian aggressions and the geopolitical interests of containing Russia. Both the EU and Japan are required to maintain their sea-lane for both economic and political stabilities so that they had better share their sea-lane and its security.

Thus, I have actually posted on a social network page of European Federalist to request Japan to join the EU to fill the membership position of the United Kingdom of Great Britain and Northern Ireland (UK). 


PS. This is just a simulation which is not feasible in real so that please do not take this issue seriously.

 


 

 

 

 

Monday, March 04, 2024

Python: Combination of Singular Spectrum Analysis (SSA) and Fast Fourier Transform (FFT)

 

 

This is my non-linear time series analysis combining Singular Spectrum Analysis (SSA) and Fast Fourier Transform (FFT). 

The dataset is the foreign exchange (FX) rate of Euro (EUR) based on US-Dollar (USD) obtained from Frankfurter App provided by the European Central Bank (ECB).

Implementing FFT for each reconstruction component (RC) of SSA gives us much more precise insights of the periodicity of the time series fluctuation. 

# Execute this cell to have access to the API of Frankfurter App
import requests
import json

# importing necessary tools
import networkx as nx
import numpy as np
import pandas as pd
import random
import statistics
import scipy.linalg
from numpy import linalg as LA
from scipy.stats import qmc
from scipy import stats
import statsmodels.formula.api as sm
import math
import cmath
from scipy.linalg import hankel

import scipy.odr
from scipy import odr

# For using Frankfurter app
import ast

# For graphing
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns

# Fast Fourier Transform (FFT) https://docs.scipy.org/doc/scipy/tutorial/fft.html
from scipy.fft import fft, ifft, fftfreq

# Showing the plots bigger
plt.rcParams["figure.figsize"] = (20,10)
# defining imaginary number
i=complex(0,1)
i


## Downloading the time series data from Frankfurter App
# Connecting to the API https://www.frankfurter.app/docs/ to get the EUR/USD rates
url = "http://api.frankfurter.app/1999-01-01.."
resp = requests.get(url,{'to':'USD'})
#print(resp.url)
#print(resp.status_code)
#print("Type:", type(resp.content))
#print(resp.content)

print("Type:", type(resp))

# Preparing for the right encoding
import ast
byte_str = resp.content
dict_str = byte_str.decode("UTF-8")
mydata = ast.literal_eval(dict_str)
print("Type:", type(mydata))

#mydata #show the accessed data
EURUSD=(mydata["rates"])
#EURUSD

#mydata #show the accessed data
EURUSD=(mydata["rates"])
#EURUSD

# Sorting the data into the Python dictionary form
Dates_EURUSD=[]
Rates_EURUSD=[]

for key, value in EURUSD.items():
    Dates_EURUSD.append(key)
    for ky,vl in value.items():
        Rates_EURUSD.append(vl)

EURUSD=dict(zip(Dates_EURUSD,Rates_EURUSD))
print('First week:',list(EURUSD.keys())[0],',  Last week:',list(EURUSD.keys())[-1])

#Rates_EURUSD

### Graph output (1) ###

NW=6 # Number of windows to slice this time series dataset
LI=math.floor(len(EURUSD)/NW) # The length of interval

fig, axs = plt.subplots(NW)
for k in range(NW):
    axs[k].plot(Dates_EURUSD[k*LI:(k+1)*LI], Rates_EURUSD[k*LI:(k+1)*LI])

print("Length of data:",len(Rates_EURUSD))


## Singular Spectrum Analysis (SSA)
print("The following refers to https://stats.stackexchange.com/questions/544105/singular-spectrum-analysis-and-their-eigentriplets")
print('This SSA method is almost identical to the one based on MATLAB "Singular Spectrum Analysis - Beginners guide" (MathWorks)')
print(' https://uk.mathworks.com/matlabcentral/fileexchange/58967-singular-spectrum-analysis-beginners-guide which I attempted to duplicate with Python. ')

# Re-defining the time series and its length
s=Rates_EURUSD;
N=len(Rates_EURUSD)

# Getting window length L and lagged length K
#L = 500-1
L = 100
K = N - L + 1

# Constructing the time lagged Hankel matrix
X=np.zeros((K,L))
for m in range (0, L):
    X[:,m] = s[m:K+m]
   

# Trajectory matrix
Cemb = np.dot(X.T,X)/K

# Eigen decomposition
eigenValues, eigenVectors = np.linalg.eig(Cemb)
idx = eigenValues.argsort()[::-1]  
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

# Vectors of Principal Components
PC = np.dot(X,eigenVectors)

# Pre-allocating Reconstructed Component Matrix
RC = np.zeros((N, L))
# Reconstruct the elementary matrices without storing them
for k in range(L):
    myBuf = np.outer(PC[:,k], eigenVectors[:,k].T)
    myBuf = myBuf[::-1]
    RC[:,k] = [myBuf.diagonal(j).mean()\
               for j in range(-myBuf.shape[0]+1, myBuf.shape[1])]
       
### Graph output (2) ###

# First 6 RC
fig, ax = plt.subplots(3,2)
ax = ax.flatten()
for k in range (0, 6):
    ax[k].plot(RC[:,k])
    ax[k].set_title(str(i))
plt.tight_layout()

### Graph output (3) ###

# Plotting a graph comparison
RawSSA=RC[:,0]
for k in range(L-1):
    RawSSA=np.add(RawSSA,RC[:,k+1])
SCs=10 # Smoothed cycle components
SmoothedSSA=RC[:,0]
for k in range(SCs-1):
    SmoothedSSA=np.add(SmoothedSSA,RC[:,k+1])
plt.subplot(2,1,1)
plt.title("Original vs. Reconstructed time series")
plt.plot(s[:])
plt.plot(RawSSA)
plt.subplot(2,1,2)
plt.title("Reconstructed raw vs. smoothed time series")
plt.plot(RawSSA)
plt.plot(SmoothedSSA)


# sample spacing
Days=N*7 # Number of days
Months=N*7//30 # Number of months
Years=N*7//360 # Number of years
T=1/Months # Defining the sample spacing step-size

yf = fft(s)
xf = fftfreq(N, T) #[:N//2]


# FFT for each RC
RC_fft=[]
RC_fft_power=[]
for l in range(L):
    RC_fft.append(fft(RC[:,l])) #[0:N//2])
    RC_fft_power.append(np.abs(RC_fft[l]))

# Denoise FFT of RC
dn_RC_fft=RC_fft.copy()
dn_RC_fft_power=RC_fft_power.copy()
for j in range(len(RC_fft)):
    for k in range(len(RC_fft[0])):
        DenoisingThreshhold=(sum(RC_fft_power[j])/len(RC_fft_power[j]))
        #DenoisingThreshhold=(max(RC_fft_power[j]))*0.90
        if RC_fft_power[j][k]<DenoisingThreshhold:
            dn_RC_fft_power[j][k]=0
            dn_RC_fft[j][k]=0
        else:
            continue

# Defining the cycle length
CycLen=(xf[0:N//2]) # Cycle length
#CycLen=CycLen[::-1]
CycLen

### Graph output (4) ###

# Showing some examples of the cycle lengths of the frequencies

fig, axs = plt.subplots(7)
for k in range(1,8):
    axs[k-1].stem(CycLen,dn_RC_fft_power[-k*10][N//2-1:-1]) #[0:N//2])


# Summing all the frequencies of RCs for the inverse FFT
tp_dn_RC_fft=list(map(list, zip(*dn_RC_fft)))
tp_dn_RC_fft_power=list(map(list, zip(*dn_RC_fft_power)))

sum_dn_RC_fft=[]
sum_dn_RC_fft_power=[]

for k in range(len(tp_dn_RC_fft)):
    sum_dn_RC_fft.append(sum(tp_dn_RC_fft[k]))
    sum_dn_RC_fft_power.append(sum(tp_dn_RC_fft_power[k]))


# ### Graph output (5) ### Uncomment the following to display

#plt.stem of the denoised power stemplot
plt.stem(CycLen, sum_dn_RC_fft_power[N//2-1:-1])
plt.grid()
plt.show()

### Graph output (6) ### Uncomment the following to display
# Inverse FFT to reconstruct the time series
plt.plot(s)
plt.plot(ifft(sum_dn_RC_fft).real)






Monday, January 08, 2024

The European Monetary Union is inevitable, but has to be fundamentally revised

Published on 23/07/2011 09:18 British Summer Time

1. Introduction

This Eurozone crisis has been predicted by many economists. These economists put emphasis on the impact of the money supply volume on the stability of economic environments such as the price inflation rate, the unemployment rate, the gross domestic product (GDP), and the speculative trend on financial market. They argued that, when the monetary policy is unified, the common fiscal policy is also required to be established, all the member countries of this monetary union are supposed to have the financial regulation for all these countries, and the labour mobility needs to be flexible for workers in these member countries to move across these countries in order to stabilise the economic environments. In addition, the econometric analysis of the Eurozone average inflation rate indicated that the European Monetary Union (EMU) is beneficial to majority of the member countries owning to the harmonised inflation rate, but it still requires something to control the different inflation rate of each individual member country. The reason of German refusal of issuing Eurobond is assumed to be because of uncooperative attitudes of Greece. Mr. Trichet, the governor of the European Central Bank (ECB) also suggests that the EMU has to fundamentally change its overall structure before allowing any countries to keep incurring their debt. Overall, the solution of the currently ongoing Eurozone crisis is the fundamental improvement on the EMU fiscal, financial, and labour market structure, and getting rid of the common currency will never be a solution.


2. The problem caused by the monetary policy transformation

The disadvantage of abandoning the national monetary policy (to join the common monetary union) is that this country becomes no longer able to set her own interest rate and the volume of her own money supply. Greece used to be heavily relying on her own unique monetary policy, based on the money supply which was remarkably higher than the average of European countries, in order to finance her government expenditure which could not be sufficiently financed by her unsophisticated fiscal policy. However, after Greece joined the EMU, she could no longer use her high money supply. Greece may rely on the tax revenue burdened on her export revenue such as her tourist industry and the growth of her private sectors stimulated by the economic growth of the entire Eurozone economy. Nonetheless, unless she tightens her fiscal policy, when the entire Eurozone economy falls into recession and/or the demand of Greek tourist industry declines, Greece starts struggling to obtain her public finance resource. This problem has been seen in many Southern European Nations such as Italy, Spain, and Portugal. But, Greece seems to be more problematic than these Southern nations. Spanish government shows a strong commitment on tightening Spanish fiscal policy under the European central government’s induction. Italy still has her strong initiative in European economy thanks to her famous industries such as finance, manufacturing, and tourism. Portugal seems to be similar to Greece, but the quantitative data analysis shown in the next chapter indicates Portuguese suffers much less than Greece.




3. The econometric analysis of the Eurozone average inflation rate

This graph (Qualitative method) above shows the different inflation of the Eurozone countries (IMF, 2011). Majority of the Eurozone countries have a synchronised inflation rate trend from 2002 to 2010. The econometric analysis of the Eurozone average inflation rate, whose results are shown by the following figures, indicated that the price inflation of the individual countries joining the European Monetary Union (EMU) is influenced by the price inflation of the other different EMU countries.




This equation is the inflation rate of all individual Eurozone countries (〖Inflation〗_(i,t)) regressed on the inflation rate in the last year 〖Inflation〗_(i,t-1). As the coefficient of 〖Inflation〗_(i,t-1) is less than 1, this variable is stable enough to converge into a particular point in the long run as follows:




So, this proves that the Eurozone inflation rate is converging into 2% which is what the ECB targets to make! The following regression analysis proves that the GDP grows furthermore when the inflation rate becomes closer to 2%:




This result shows the natural log of the GDP in the Eurozone economy, ln⁡(〖GDP〗_(i,t) ) (Footnote 1.) , is significantly negatively correlated with the inflation rate deviating from 2% which is shown as the absolute number of the inflation rate minus 2, |〖Inf〗_(i,t)-2|. The following auxiliary regression shows both the GDP and the inflation are co-integrated each other:



〖 u〗_(i,t) is the residuals from the previous regression. As the lagged residuals 〖 u〗_(i,t-1) is negatively correlated with change in the residuals 〖∆u〗_(i,t), the variables used in the previous regression, ln⁡(〖GDP〗_(i,t) ) and |〖Inf〗_(i,t)-2|, are stable and co-integrated with the EU inflation rate, which means the movement of these variable affects on the other’s. However, the stability test for Greece and Ireland showed a relatively pessimistic result as follows:

Greek inflation on the inflation of the entire Eurozone countries



This analysis suggests that, , not only the percentage of the entire Eurozone inflation's contingency on Greek inflation rate is 47% in average, which is high,(Amended part) but also change Greek inflation is highly contingent to the entire Eurozone (Footnote 2.). Therefore, it is not only Greece suffers more than the other Eurozone countries and but also Greek economy is highly responsible on the entire Eurozone economy. This aspect may suggest both Greece and the entire Eurozone need to cooperate each other very seriously because Greece should not leave the EMU because her business cycle is already tied up with the EMU.

Irish inflation on the inflation of the entire Eurozone countries



On the other hand, Irish inflation rate is neither stable nor co-integrated with the entire Eurozone one. Therefore, Greece seems to suffer from the volatility of the inflation far more than the other Eurozone members so that she needs either the intervention by the European central government or the fiscal restructuration, or both, to calm down her inflation rate. Unlike Greece, Ireland may be benefitted when she leaves the EMU. Irish business cycle is not correlated with the Eurozone economy. But, if Ireland still wants to keep the membership, the Eurozone eventually needs to have a strong fiscal stimulus enough to enable Irish business cycle to harmonise with the entire Eurozone business cycle.

4. German refusal of participating into the Eurobond programme

The concern of Germany on Greece is that Greek catastrophic crisis will be permanent unless Greece tries to reform her fiscal policy fundamentally and cooperates with the EU central governmental policy rather than her own selfish and irrational nationalism. When a person purchases equity, s/he expects its value to be either stable in the long term or predicted to grow significantly. The value of Greek national debt seems to be neither stable in the long term nor predicted to increase its value in the short term. Even if German government is altruistic enough to sustain Greek public finance by purchasing Greek debt in order to rescue the entire Eurozone, there is a risk for Germany to be drawn into the recession or even to be bankrupt.
The Eurobond programme suggests the Eurozone countries to share both the risk and the benefit of issuing the government debts among the entire Eurozone countries rather than burdening the responsibility on each individual country for incurring the government debt. For example, as shown in the graph below, when Germany experiences the economic growth relatively higher than any other nations whilst France falls into the recession, it needs to tune the aggregate demand of both nations.


As there is no national monetary policy available for both France and Germany, one of the optimum solutions would be increasing the tax revenue of Germany to transfer it to subsidise France. The econometric analysis shown in the previous chapter indicates that French and German economies are highly contingent to each other so that French downturn has to be diverted by German contribution to save Germany herself. This is the idea of sharing the risk and benefit of the national debt and its usage under the collective responsibility among the countries.
Nonetheless, this mechanism may work efficiently and effectively because French fiscal policy does not have a problem like Greek. France and Germany have much more similar labour market situation than Greece. In addition, France and Germany are geographically closer each other than Greece. So, the labour mobility is much more flexible between France and Germany than between Greece and them. Furthermore, France and Germany balance their budget without relying on the excess money supply unlike Greece. If this case scenario were Greek instead of France, German tax revenue transfer to subsidise Greece is ineffective and inefficient.
The intervention from the European central government into Greek fiscal policy under the strict guideline of the central government is also emerged. Greece is still resisting against this intervention due to the sentimental irrational populist nationalism. The European central government regards that, in order to make this money transfer to Greece more effective and efficient, Greek fiscal reform lead by the further privatisation of the entire Greek economy are inevitably required. Greek labour market is rigid because of Greek economy’s reliance on the huge public sector, which disrupts the flexibility of the labour mobility. On the top of the inflexible labour mobility, Greek public sectors are not rational enough to balance their budget. They are not used to the market competition and the thread of bankruptcy because they are always protected by the nation unlike the private sectors. By contrast, the private sectors are much more used to balancing their budget under the market competition. As long as Greek public sectors struggle to rationalise their budget to be balanced by their own effort, the enforced privatisation seems to be only the antidote of the fiscal imbalance.
All in all, the responsibility of Greek fiscal policy should be burdened more on European central government to discourage Greek irrational populist nationalism which is notoriously uncooperative to solve this currently ongoing problem for both Greece herself and the entire Eurozone economy. In order to discourage this pathetic nationalism, the privatisation to minimise Greek national government authority can be a key solution before substituting the power of Greek nationalism with the European economic cooperation.


5. The ECB’s point of view and warning from Mr. Trichet

Focusing on the ECB’s point of view on the current Eurozone financial havoc, the ECB executives are suffering from the dilemma between putting priority on saving the Eurozone economy and focusing on calming the inflation by suggesting the fiscal policy of all Eurozone countries to be tightened. In particular, Mr. Trichet, the governor of the ECB, always rejects the optimism on the Eurobond programme without fundamentally reconstructing the fiscal structure in the entire Eurozone. Mr. Trichet has been always suspicious about the stability of the Eurozone economy since the ECB was established. His suspicion is related to the fiscal problem mentioned in the previous chapter.
The ECB has been purchasing a large volume of the national debt of the Eurozone countries by its quantitative easing. In order to keep the value of these bonds to invest to rescue these governments, the ECB has. The ECB cannot survive without an economic activity of these nations so that the ECB needs to save the national governments of the Eurozone. Otherwise, the value of Euro becomes zero so that the ECB itself disappears. However, the expected result still cannot be seen, and the aggregate government bonds incurred has never stopped expanding. This mechanism still enables the Euro exist, but it depreciates the value of Euro further. This phenomenon causes the inflation to hike up, and then the nominal interest rate eventually needs to rise. Overall, rescuing the Eurozone countries damages the private sectors and individual citizens by a high interest rate, and it creates further government deficit which requires the further ECB’s quantitative easing, which again induces a further inflation. Mr. Trichet has already warned this spiral would occur and urged to divert from it since the beginning of the Eurozone crisis (Footnote 3.). Thus, he rejects all the optimism of perpetuating this situation.
The ECB also struggles with negotiating with the private sectors. Although the previous chapter stated the positive aspect of the private sectors in terms of the fiscal policy, the private sectors cause problem in the monetary policy set by the ECB (Footnote 4.). The private sectors are willing to raise their profit and the wage for their executives, and detest the high interest rate. These characteristics of the private sectors perpetuate the inflation which discourages an economic growth of both countries and private sectors themselves in the long term. Generally speaking, the private sectors are uncooperative to the European economic stabilisation. Although the stabilised European economy which the ECB expects to establish benefits to the private sectors in the long term, these private sectors are less interested in it than the ECB.
This aspect infers a danger for European economy which is now also fund by the private sectors. This could be the reason why Mr. Trichet is modest about the private sector contribution to rescuing the Eurozone national economies .

6. Conclusion
In conclusion, there is no optimistic prospect on this current Eurozone economic situation. In order to solve these structural instabilities, the Eurozone may need a fundamental radical revolutionary act on altering both economic and political entire structure. But, they cannot stop the European economic integration because the almost all Eurozone economies are highly correlated with each other as proven by the econometric analysis. It seriously needs an IMF of Europe, which the ECB is trying to act like. The ECB should have a much stronger authority to instruct the fiscal policy of national governments in the Eurozone as same as the IMF does to the national governments in the globe. In addition, if the priority is saving the European economy, the heavy reliance on the private sectors contribution is very risky. Hence, the ECB policy based on Trichetian Monetarism, which is tough against the irrational egos of both the national government fiscal policy and the private sectors’ short-termism, seems to be only the reliable tool, and the economic agents had better listen to it.


-------------------------------------------------------------------------------
Footnotes:

1. When a variable is positively skewed, it needs to be logged or transformed into the root (E.g. square root and cube root) in order to offer a reliable, unbiased, and consistent statistical analysis.

2.


---------------------
My Additional Comment added on 4th of August 2011:

Well, as I mentioned in my essay, it depends on the hamonisation of the business cycles in these candidate nations (I referred to the price inflation rate as an indicator of the business cycle). When the business cycle is harmonised (Synchronised), the monetary union becomes necessary or inevitable, such as the Greek and the other Eurozone countries' case. Otherwise, such as Irish case, it should not join the monetary union or it has to have a great intervention to artificially harmonise the cycles.

Some African nations might be benefited because they trade each other often, and their economy is not self-sustainable i.e. needs to be corroborated each other. But, they indeed need to have a common fiscal policy to modernise and tighten the fiscal policy of all these nations.

South American nations should not have the monetary union yet. These individual South American countries are too big by means of the land mass relative to their population density (I.e. The cost of the inter-country trade inside South America is higher than the benefit from it). Furthermore, these countries do not trade each other often compared to the other blocks of countries in this world such as Europe, North America, Africa, and Asia (According to the statistics shown in Economics of Monetary Union (Paul De Grauwe)).

The trade frequency of among Asian nations is the highest of all the international trade made in this world. So, as Lee Kuan Yew, the first Singaporean prime minister, said forming Asian trade community could benefit Asian nations. However, other than economic factors, the political factors exist as the obstacles which disrupt forming this trade community.

Only the person concerning the EMU whom I can truely respect and trust is Mr. Trichet and his ECB. I claim that not only the EMU national fiscal policies but also all the private enterprises in the Eurozone economy should be instructed by the ECB based on Trichetian Monetarism...!

Tuesday, December 12, 2023

SSA attempt functioning: The main SSA codes copied from StackExchange

  

The synthetic data imitating the business cycle is my original although the functions of generating the complex time series refers to my supervisor's work.

The set of Python codes implementing Singular Spectrum Analysis is directly copied from "Singular spectrum analysis and their "eigentriplets" (Stack Exchange). This SSA method is almost identical to the one based on MATLAB "Singular Spectrum Analysis - Beginners guide" (MathWorks) which I attempted to duplicate with Python. 

This set of Python codes succeeds in the reconstruction component (RC) as shown in the graph.


# importing necessary tools
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import networkx as nx
import numpy as np
import pandas as pd
import random
import statistics
import scipy.linalg
from numpy import linalg
from scipy import stats
import statsmodels.formula.api as sm
import math
import cmath
from scipy.linalg import hankel

# Showing the plots bigger
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,10)


## Creating a synthetic time series imitating the business cycle

# Defining the function for the synthetic complex exponential  
def syn_exp(amp,freq,x):
    t=len(amp)
    y=[]
    for omg in range(len(x)):
        yi=0
        for ap in range(len(amp)):
            yi+=amp[ap]*cmath.exp(freq[ap]*x[omg])
        y.append(yi)
    return y

# Defining complex number
i=complex(0,1)
i


# Creating the synthetic data imitating the business cycle
phi = [0.03, 3*i, 10*i, -1+30*i, -1-20*i, 0.01+5*i];
alpha = [4, 3, 2, 2, 2, 1];

# sampling rate
S = 100

# number of exponentials in the signal
n = 600

# f_syn: samples used by Prony's methhod
_2n_1=(2*n-1)+1
omega = [2*math.pi/S*(_0__2n_1) for _0__2n_1 in range(_2n_1)]

# Defininig the synthetic time series
f_syn = syn_exp(alpha, phi, omega)

# Defining the noise
noise=[np.random.normal(0) for k in range(len(f_syn))]
noise=noise/linalg.norm(noise)

# eps: noise level, also try 10^(-0)
eps =  10^(-1);
#eps = 0

# f = f_syn added with random noise
f = f_syn + eps*noise;
f

# Re-defining the time series and its length
s=f;
N=len(f)


## The SSA starts
print("The following refers to https://stats.stackexchange.com/questions/544105/singular-spectrum-analysis-and-their-eigentriplets")
print("The SSA method of this set of Python codes is identical to the embedded covariance method of https://uk.mathworks.com/matlabcentral/fileexchange/58967-singular-spectrum-analysis-beginners-guide")

# Getting window length L and lagged length K
L = 500-1
K = N - L + 1

# Constructing the time lagged Hankel matrix
X=np.zeros((K,L))
for m in range (0, L):
    X[:,m] = s[m:K+m]
   
# Trajectory matrix
Cemb = np.dot(X.T,X)/K

# Eigen decomposition
eigenValues, eigenVectors = np.linalg.eig(Cemb)
idx = eigenValues.argsort()[::-1]  
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

# Vectors of Principal Components
PC = np.dot(X,eigenVectors)

# Pre-allocating Reconstructed Component Matrix
RC = np.zeros((N, L))
# Reconstruct the elementary matrices without storing them
for k in range(L):
    myBuf = np.outer(PC[:,k], eigenVectors[:,k].T)
    myBuf = myBuf[::-1]
    RC[:,k] = [myBuf.diagonal(j).mean()\
               for j in range(-myBuf.shape[0]+1, myBuf.shape[1])]
       
# # First 6 RC
# fig, ax = plt.subplots(3,2)
# ax = ax.flatten()
# for k in range (0, 6):
#     ax[k].plot(RC[:,k])
#     ax[k].set_title(str(i))
# plt.tight_layout()


# Plotting a graph comparison
RawSSA=RC[:,0]
for k in range(L-1):
    RawSSA=np.add(RawSSA,RC[:,k+1])
SCs=10 # Smoothed cycle components
SmoothedSSA=RC[:,0]
for k in range(SCs-1):
    SmoothedSSA=np.add(SmoothedSSA,RC[:,k+1])
plt.subplot(2,1,1)
plt.title("Original vs. Reconstructed time series")
plt.plot(s[:])
plt.plot(RawSSA)
plt.subplot(2,1,2)
plt.title("Reconstructed raw vs. smoothed time series")
plt.plot(RawSSA)
plt.plot(SmoothedSSA)