20230918: Cutting Bank Reserve Ratio

On 14 Sep (Thu) evening, the regulator surprised the market by further cutting reserve ratio for banks by 25bp, to release over 500b CNY to the financial system.

Lots have speculated that the regulator is aiming to support the market; but unfortunately, market still slide further on Friday. Foreign investors continue to pull out from Chinese markets.

The economy is said to be recovering, according to National Bureau of Statistics (NBS), where August had industrial output rose 4.5% beating the estimated 3.9%, and the July had 3.7%. Retail increased 4.6% in August beating estimated 3% against July’s 2.5%.

Commodities usually do not have trending opportunities on Sep and Oct due to the golden week holiday, so I’ve cut the risk allocation to half.

On the other side of the world, SP500 is trading higher, with the momentum model increased allocation to 70%. Lots have been saying that US would have bad year for 2024 and the Street is selling off whenever market rebounds. I wouldn’t bet on where would the peak would be, and continues to follow the trend.

Configure Mirror For Maven in Eclipse

Downloading from maven central is rather slow from China, while one way to speed up the download is to use local mirror, a server closer to me, e.g. aliyun, or tsinghua. Spring Tool Suites comes with builtin maven, so it took me some analysis to figure out how to mirror it correctly. Following are the steps that worked for me.

  1. Create ${user.home}/.m2/settings.xml

I have to manually create the file, because the folder does not have it. Following the tip from maven’s official site, I copied the global setting over.

  1. Customize settings.xml

Update mirror to use aliyun so that it downloads faster.

    <mirror>
      <id>alivaven</id>
      <mirrorOf>central</mirrorOf>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
    </mirror>
  1. Apply changes to Eclipse

Window>Preference>Maven>User Settings>“User Settings”

  1. Update Maven Repository

Package Explorer>pml.xml>“Maven”>Update Project

Reference

20230906: Stimulus On Properties Market

Chinese government has put further stimulus package on properties market aiming to push up the sliding market. Saver is still getting punished by the even lower rates, while those seeking leverages will find the cost is reducing. This stimulus was implemented in 2nd layer cities but with not much effect, so now it comes into major cities, including Shanghai.

There are speculations that housing price would go further down before it rebounds back a bit, as the stimulus plan was favorable to house owners who wants to upgrade their home.

The market seems to be forming the bottom shape over the past 5 trading sessions. As long as the market is not strong, the strategy won’t start putting in any risks.

Commodities market is rebounding, but August has lost what has gained in July. Typically, September is not a good month for CTA, as October’s golden week comes here. But I will let the model run, and reduce risks when the holiday draws near.

On the other side of the world, US stock market is gaining strength, and the strategy has bought 50% of risks. Lots are speculating that US economy would deteriorate in 2024, so the stock market should seek selling points rather than buying in.

Securing Rest Service

I have scrapers running in cloud to download stock prices, and then how do I expose the service to my home pc for read only access? Spring Data provides a toolbox for it by using JPA and Rest Services. One thing to note is on data security.

Create project from “start.spring.io”, and include: web, jpa and security as the core modules; and add additional dependencies for sqlite.

<dependency>
	<groupId>org.xerial</groupId>
	<artifactId>sqlite-jdbc</artifactId>
	<version>3.42.0.0</version>
</dependency>
<dependency>
	<groupId>org.hibernate.orm</groupId>
	<artifactId>hibernate-community-dialects</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>32.1.2-jre</version>
</dependency>
spring.datasource.initialization-mode=always
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.community.dialect.SQLiteDialect
spring.datasource.platform=sqlite3
spring.datasource.driver-class-name = org.sqlite.JDBC
spring.datasource.url = jdbc:sqlite:C:/scratch/hello_boot/sqlitesample.db
#spring.datasource.url = jdbc:sqlite:test
spring.datasource.dbcp2.default-auto-commit=true
spring.datasource.username = 
spring.datasource.password = 

Add a controller to provide static contents, and later on you can replace it to call from Jpa services.

@RestController
public class ResourceController {
	@GetMapping("/home")
	public String homeEndpoint() {
		return "Hello Security!";
	}
}

Call service from curl, and notice the error on authentication. screenshot to be created.

Exclude default autoconfiguration for security, by either applicatoin.properties or from annotation @SpringBootApplication.

@SpringBootApplication(
	exclude= {
		SecurityAutoConfiguration.class,
		UserDetailsServiceAutoConfiguration.class
	}
)
public class HellosecurityApplication {

	public static void main(String[] args) {
		SpringApplication.run(HellosecurityApplication.class, args);
	}
}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

Add authentication for rest services by api-token, by building filter, authentication-service, and authentication object.

public class AuthenticationFilter extends GenericFilterBean{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest)request);
			SecurityContextHolder.getContext().setAuthentication(authentication);
		}catch(Exception e) {
			HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);			httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
			PrintWriter writer = httpResponse.getWriter();
			writer.print(e.getMessage());
			writer.flush();
			writer.close();
		}
		chain.doFilter(request, response);
	}
}
public class AuthenticationService {
	private static final String AUTH_TOKEN_HEADER_NAME="X-API-KEY";
	private static final String AUTH_TOKEN = "mytoken12345678";
	
	public static Authentication getAuthentication(HttpServletRequest request) {
		String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME);
		if(apiKey==null || !apiKey.equals(AUTH_TOKEN)) {
			throw new BadCredentialsException("Invalid API Key");
		}
		
		return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES);
	}
}
public class ApiKeyAuthentication extends AbstractAuthenticationToken {
	private final String apiKey;
	public ApiKeyAuthentication(String apiKey, Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.apiKey = apiKey;
		setAuthenticated(true);
	}

	@Override
	public Object getCredentials() {
		return null;
	}
	
	@Override
	public Object getPrincipal() {
		return apiKey;
	}
}

Enable SecurityFilterChain in config

@Configuration
@EnableWebSecurity
public class SecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
		http.csrf()
		.disable()
		.authorizeHttpRequests()
		.requestMatchers("/**")
		.authenticated()
		.and()
		.httpBasic()
		.and()
		.sessionManagement()
		.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
		.and()
		.addFilterBefore(
			new AuthenticationFilter(),
			UsernamePasswordAuthenticationFilter.class
		);
		return http.build();
	}
}

Test curl on rest service curl –location –request GET “http://localhost:8080/home” curl –location –request GET “http://localhost:8080/home” –header “X-API-KEY: mytoken12345678”

Reference: https://www.baeldung.com/spring-boot-api-key-secret

Momentum Report

A report should show the state change of the account according to the calculation of the model. Contents are covering: current positions, actions (buy/sell), market sentiment, top list stocks.

The report model can be stored in database or directory; while sending email is a separated process, configurable from shell with parameters. For example, if we missed some prices for certain days, then we can re-run the report from the last available day to complete the reports, while we don’t want to receive emails again.

Current Positions $EOD

symbol name price position
WELL Welltower Inc 83.06 113

Orders $SOD

symbol name direction price size
WELL Welltower Inc 83.06 S 83.06

Ideal Allocation $SOD

symbol name last fund actual
WELL Welltower Inc 83.06 9400 8306

NAV are stored in database; while performance report should be generated based NAV golden source.

RoR Report (model instance running since yyyyMMdd)

1d 1w 2w 1m 2m 3m 6m 1y 2y 5y 10y

NAV Report Report of model’s asset values

distance date NAV
1d
2d
1w
2w
1m
2m
3m
6m
9m
1y
1y6m
2y
3y
5y
10y
20y

20230829: Stimulus Policy To Rescue

Over the past weekend, there has been announcements on stimulus policies trying to rescue the tanking stock markets, including cutting stamp duty, increase leverage allowance, forbids major shareholders from selling, and etc. Historically, such measures would push the markets up for weeks.

On Monday’s opening, the broad index was as high as 5%, but all indexes were drop for the entire day, till closes around 1%. Lots of investors was in loss if they joined the market at open.

It seems that the regulators fail to realize that the market lacks confidence on recovery of the economy, which has nothing much to do with tax, fees and leverage ratios. I feel safe that my risk allocation remains at 0%.

US stock market has been adjusting as well. The outlook of economy is strong, while central bank considers that they still have room to hike rates to further press down inflations. The market seems to be pricing further rate hikes. The momentum strategy is giving up some of its profit (about 4%), and now with risk allocation of 10%.

20230814: Bear in the play

Bear is in the play for the past month. In fact, the index is trading in weak momentum since end of April till today for more than 3 months, with such weak trend continues on.

The July statistics released have shown that the economy is further weakening (worst in record for the past decades for year to year matching); credit increment is 3459wy for July and short of 3498wy compared with last July, and M2 increment is 5282wy, short of 2703wy compared with last July. There has been lots of policy announcement in the past couple of weeks, but the market does not believe in what the government would put any measures into practice (or even worse that the measure put into practice does no help with the economy).

The momentum strategy has cut its last position in Jul and now holds 0% risks. I feel lucky that I hold no risk on book.

Coincidentally, the CTA strategy has now cut all long positions as well, with flat risk for the past couple of days. Maybe the market starts to realize that the government would not implement realistic measures to help the breaking economy? I’m not too sure…

On the other hand, US stock is showing weakening sign as well, with SP500 trading below the near term average. Momentum strategy has cut 4 positions already, with 2 more to be liquidated for next session to end up with around 40% risk. The US economy still shows strong sign that makes the market prices in further rates hike from its central bank.

20230705: US Stocks Continues Hiking

For the month of Jun, HS300 has nothing much happening. RMB continues downtrend, while the stock index was higher at the beginning of the month and remains dull till the end of the month. Overall, there’s nothing much for momentum trader to do anything.

The portfolio was 20% risk at the start of the month, and dropped to 10% at the end of the month. Account equity has not much changes.

SP500, on the other hand, continues strong trend. The portfolio has allocation on technology (30%), industry (29%), consumption (29%), and healthcare (10%). From start of Apr to end of Jun, the strategy enjoyed 10.37% (vs SP500 8.03%).

Geopolitics continues between US and China, where US is planning to ban China from access cloud services offered by US companies (e.g. amazon, google, and microsoft) to ensure that it takes the lead on AI area. On the other hand, high ranked officials start to visit China. It may seem contradictory, but seems the tie between these two countries couldn’t get any worse.

Chinese government might start money printing to resolve the huge deficit from local governments, as it has rumored. As a matter of fact, the government bond has crashed at closing session on 4 Jul 2023, with more than 3 times of its usual volatility.

Commodities prices are not changing much. The CTA strategy had drawback for around -5% for the month of Jun. I did minor adjustment to the strategy to improve its exit signals.

Backtest CTA via POBO Quant

After GoldMiner (掘金量化) starts their professional service, I abandon it, as the fee is too much for me (10000RMB per year for their license). For the long term, I decide to move to BackTrader, which has quite good documentation; while for the short term, I will migrate the backtest models to Pobo Quant.

  • Basics of Pobo Quant
  • Backtest DEAV3